Skip to content
DwarfDebug.cpp 100 KiB
Newer Older
      if (Element.getTag() == dwarf::DW_TAG_subprogram)
        ElemDie = CreateSubprogramDIE(DW_Unit,
Devang Patel's avatar
Devang Patel committed
                                      DISubprogram(Element.getNode()));
      else
        ElemDie = CreateMemberDIE(DW_Unit,
Devang Patel's avatar
Devang Patel committed
                                  DIDerivedType(Element.getNode()));
    if (CTy.isAppleBlockExtension())
      AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);

    unsigned RLang = CTy.getRunTimeLang();
    if (RLang)
      AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
              dwarf::DW_FORM_data1, RLang);
    break;
  }
  default:
    break;
  }

  // Add name if not anonymous or intermediate type.
    AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);

  if (Tag == dwarf::DW_TAG_enumeration_type ||
      Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
    // Add size if non-zero (derived types might be zero-sized.)
    if (Size)
      AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
    else {
      // Add zero size if it is not a forward declaration.
      if (CTy.isForwardDecl())
        AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
      else
        AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
    }

    // Add source line info if available.
    if (!CTy.isForwardDecl())
      AddSourceLine(&Buffer, &CTy);
  }
}

/// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
  int64_t L = SR.getLo();
  int64_t H = SR.getHi();
  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);

  AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
  if (L)
    AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
  if (H)
Daniel Dunbar's avatar
Daniel Dunbar committed
    AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);

  Buffer.AddChild(DW_Subrange);
}

/// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
                                       DICompositeType *CTy) {
  Buffer.setTag(dwarf::DW_TAG_array_type);
  if (CTy->getTag() == dwarf::DW_TAG_vector_type)
    AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);

  // Emit derived type.
  AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
  DIArray Elements = CTy->getTypeArray();

  // Construct an anonymous type for index type.
  DIE IdxBuffer(dwarf::DW_TAG_base_type);
  AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
  AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
          dwarf::DW_ATE_signed);
  DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);

  // Add subranges to array type.
  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
    DIDescriptor Element = Elements.getElement(i);
    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
Devang Patel's avatar
Devang Patel committed
      ConstructSubrangeDIE(Buffer, DISubrange(Element.getNode()), IndexTy);
  }
}

/// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
  const char *Name = ETy->getName();
  AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
  int64_t Value = ETy->getEnumValue();
  AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
  return Enumerator;
}

/// CreateGlobalVariableDIE - Create new DIE using GV.
DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
                                         const DIGlobalVariable &GV) {
  DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
  AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 
            GV.getDisplayName());

  const char *LinkageName = GV.getLinkageName();
  if (LinkageName) {
    // Skip special LLVM prefix that is used to inform the asm printer to not
    // emit usual symbol prefix before the symbol name. This happens for
    // Objective-C symbol names and symbol whose name is replaced using GCC's
    // __asm__ attribute.
    if (LinkageName[0] == 1)
      LinkageName = &LinkageName[1];
    AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
Daniel Dunbar's avatar
Daniel Dunbar committed
  AddType(DW_Unit, GVDie, GV.getType());
  if (!GV.isLocalToUnit())
    AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
  AddSourceLine(GVDie, &GV);

  // Add address.
  DIEBlock *Block = new DIEBlock();
  AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
  AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
                 Asm->Mang->getMangledName(GV.getGlobal()));
  AddBlock(GVDie, dwarf::DW_AT_location, 0, Block);

  return GVDie;
}

/// CreateMemberDIE - Create new member DIE.
DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
  DIE *MemberDie = new DIE(DT.getTag());
  if (const char *Name = DT.getName())
    AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);

  AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());

  AddSourceLine(MemberDie, &DT);

  DIEBlock *MemLocationDie = new DIEBlock();
  AddUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);

  uint64_t Size = DT.getSizeInBits();
  uint64_t FieldSize = Size;
  if (DT.getTypeDerivedFrom().getTag() != dwarf::DW_TAG_array_type)
    FieldSize = DT.getOriginalTypeSize();

  if (Size != FieldSize) {
    // Handle bitfield.
    AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
    AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());

    uint64_t Offset = DT.getOffsetInBits();
    uint64_t FieldOffset = Offset;
    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
    FieldOffset = (HiMark - FieldSize);
    Offset -= FieldOffset;

    // Maybe we need to work from the other end.
    if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
    AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);

    // Here WD_AT_data_member_location points to the anonymous
    // field that includes this bit field.
    AddUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);

  } else
    // This is not a bitfield.
    AddUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);

  AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);

  if (DT.isProtected())
    AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
            dwarf::DW_ACCESS_protected);
  else if (DT.isPrivate())
    AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
            dwarf::DW_ACCESS_private);

  return MemberDie;
}

/// CreateSubprogramDIE - Create new DIE using SP.
DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
                                     const DISubprogram &SP,
  DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);

  const char * Name = SP.getName();
  AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);

  const char *LinkageName = SP.getLinkageName();
  if (LinkageName) {
    // Skip special LLVM prefix that is used to inform the asm printer to not emit
    // usual symbol prefix before the symbol name. This happens for Objective-C
    // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
    if (LinkageName[0] == 1)
      LinkageName = &LinkageName[1];
    AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
  AddSourceLine(SPDie, &SP);

  DICompositeType SPTy = SP.getType();
  DIArray Args = SPTy.getTypeArray();

  // Add prototyped tag, if C or ObjC.
  unsigned Lang = SP.getCompileUnit().getLanguage();
  if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
      Lang == dwarf::DW_LANG_ObjC)
    AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);

  // Add Return Type.
  unsigned SPTag = SPTy.getTag();
  if (!IsConstructor) {
    if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
      AddType(DW_Unit, SPDie, SPTy);
    else
Devang Patel's avatar
Devang Patel committed
      AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getNode()));
  }

  if (!SP.isDefinition()) {
    AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);

    // Add arguments. Do not add arguments for subprogram definition. They will
    // be handled through RecordVariable.
    if (SPTag == dwarf::DW_TAG_subroutine_type)
      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
Devang Patel's avatar
Devang Patel committed
        AddType(DW_Unit, Arg, DIType(Args.getElement(i).getNode()));
        AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
        SPDie->AddChild(Arg);
      }
  }

    AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);

  // DW_TAG_inlined_subroutine may refer to this DIE.
Devang Patel's avatar
Devang Patel committed
  DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getNode());
  Slot = SPDie;
  return SPDie;
}

/// FindCompileUnit - Get the compile unit for the given descriptor.
///
CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
  DenseMap<Value *, CompileUnit *>::const_iterator I =
Devang Patel's avatar
Devang Patel committed
    CompileUnitMap.find(Unit.getNode());
  assert(I != CompileUnitMap.end() && "Missing compile unit.");
  return *I->second;
}

/// CreateDbgScopeVariable - Create a new scope variable.
DIE *DwarfDebug::CreateDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
  // Get the descriptor.
  const DIVariable &VD = DV->getVariable();
Devang Patel's avatar
Devang Patel committed
  const char *Name = VD.getName();
  if (!Name)
    return NULL;

  // Translate tag to proper Dwarf tag.  The result variable is dropped for
  // now.
  unsigned Tag;
  switch (VD.getTag()) {
  case dwarf::DW_TAG_return_variable:
    return NULL;
  case dwarf::DW_TAG_arg_variable:
    Tag = dwarf::DW_TAG_formal_parameter;
    break;
  case dwarf::DW_TAG_auto_variable:    // fall thru
  default:
    Tag = dwarf::DW_TAG_variable;
    break;
  }

  // Define variable debug information entry.
  DIE *VariableDie = new DIE(Tag);
  AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);

  // Add source line info if available.
  AddSourceLine(VariableDie, &VD);

  // Add variable type.
  // FIXME: isBlockByrefVariable should be reformulated in terms of complex addresses instead.
  if (VD.isBlockByrefVariable())
    AddType(Unit, VariableDie, GetBlockByrefType(VD.getType(), Name));
  else
    AddType(Unit, VariableDie, VD.getType());
  if (!DV->isInlinedFnVar()) {
    // Variables for abstract instances of inlined functions don't get a
    // location.
    MachineLocation Location;
    Location.set(RI->getFrameRegister(*MF),
                 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));

    if (VD.hasComplexAddress())
      AddComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
    else if (VD.isBlockByrefVariable())
Mike Stump's avatar
Mike Stump committed
      AddBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
    else
      AddAddress(VariableDie, dwarf::DW_AT_location, Location);

  return VariableDie;
}

/// getOrCreateScope - Returns the scope associated with the given descriptor.
///
DbgScope *DwarfDebug::getDbgScope(MDNode *N, const MachineInstr *MI,
                                  MDNode *InlinedAt) {
  ValueMap<MDNode *, DbgScope *>::iterator VI = DbgScopeMap.find(N);
  if (VI != DbgScopeMap.end())
    return VI->second;
  if (InlinedAt) {
    DILocation IL(InlinedAt);
    assert (!IL.isNull() && "Invalid InlindAt location!");
    ValueMap<MDNode *, DbgScope *>::iterator DSI = 
      DbgScopeMap.find(IL.getScope().getNode());
    assert (DSI != DbgScopeMap.end() && "Unable to find InlineAt scope!");
    Parent = DSI->second;
  } else {
    DIDescriptor Scope(N);
    if (Scope.isCompileUnit()) {
      return NULL;
    } else if (Scope.isSubprogram()) {
      DISubprogram SP(N);
      DIDescriptor ParentDesc = SP.getContext();
      if (!ParentDesc.isNull() && !ParentDesc.isCompileUnit())
        Parent = getDbgScope(ParentDesc.getNode(), MI, InlinedAt);
    } else if (Scope.isLexicalBlock()) {
      DILexicalBlock DB(N);
      DIDescriptor ParentDesc = DB.getContext();
      if (!ParentDesc.isNull())
        Parent = getDbgScope(ParentDesc.getNode(), MI, InlinedAt);
    } else
      assert (0 && "Unexpected scope info");
  }
  DbgScope *NScope = new DbgScope(Parent, DIDescriptor(N), InlinedAt);
  NScope->setFirstInsn(MI);
  else
    // First function is top level function.
    if (!FunctionDbgScope)
  DbgScopeMap.insert(std::make_pair(N, NScope));
  return NScope;
}


/// getOrCreateScope - Returns the scope associated with the given descriptor.
/// FIXME - Remove this method.
Devang Patel's avatar
Devang Patel committed
DbgScope *DwarfDebug::getOrCreateScope(MDNode *N) {
  DbgScope *&Slot = DbgScopeMap[N];
  if (Slot) return Slot;

  DbgScope *Parent = NULL;
  DILexicalBlock Block(N);
  // Don't create a new scope if we already created one for an inlined function.
Devang Patel's avatar
Devang Patel committed
  DenseMap<const MDNode *, DbgScope *>::iterator
    II = AbstractInstanceRootMap.find(N);
  if (II != AbstractInstanceRootMap.end())
    return LexicalScopeStack.back();

  if (!Block.isNull()) {
    DIDescriptor ParentDesc = Block.getContext();
    Parent =
Devang Patel's avatar
Devang Patel committed
      ParentDesc.isNull() ?  NULL : getOrCreateScope(ParentDesc.getNode());
Devang Patel's avatar
Devang Patel committed
  Slot = new DbgScope(Parent, DIDescriptor(N));

  if (Parent)
    Parent->AddScope(Slot);
  else
    // First function is top level function.
    FunctionDbgScope = Slot;

  return Slot;
}

/// ConstructDbgScope - Construct the components of a scope.
///
void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
                                   unsigned ParentStartID,
                                   unsigned ParentEndID,
                                   DIE *ParentDie, CompileUnit *Unit) {
  // Add variables to scope.
  SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
  for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
    DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
    if (VariableDie) ParentDie->AddChild(VariableDie);
  }

  // Add concrete instances to scope.
  SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
    ParentScope->getConcreteInsts();
  for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
    DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
    DIE *Die = ConcreteInst->getDie();

    unsigned StartID = ConcreteInst->getStartLabelID();
    unsigned EndID = ConcreteInst->getEndLabelID();

    // Add the scope bounds.
    if (StartID)
      AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
               DWLabel("label", StartID));
    else
      AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
               DWLabel("func_begin", SubprogramCount));

    if (EndID)
      AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
               DWLabel("label", EndID));
    else
      AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
               DWLabel("func_end", SubprogramCount));

    ParentDie->AddChild(Die);
  }

  // Add nested scopes.
  SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
  for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
    // Define the Scope debug information entry.
    DbgScope *Scope = Scopes[j];

    unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
    unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());

    // Ignore empty scopes.
    if (StartID == EndID && StartID != 0) continue;

    // Do not ignore inlined scopes even if they don't have any variables or
    // scopes.
    if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
        Scope->getConcreteInsts().empty())
      continue;

    if (StartID == ParentStartID && EndID == ParentEndID) {
      // Just add stuff to the parent scope.
      ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
    } else {
      DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);

      // Add the scope bounds.
      if (StartID)
        AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
                 DWLabel("label", StartID));
      else
        AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
                 DWLabel("func_begin", SubprogramCount));

      if (EndID)
        AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
                 DWLabel("label", EndID));
      else
        AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
                 DWLabel("func_end", SubprogramCount));

      // Add the scope's contents.
      ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
      ParentDie->AddChild(ScopeDie);
    }
  }
}

/// ConstructFunctionDbgScope - Construct the scope for the subprogram.
///
void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
                                           bool AbstractScope) {
  // Exit if there is no root scope.
  if (!RootScope) return;
  DIDescriptor Desc = RootScope->getDesc();
  if (Desc.isNull())
    return;

  // Get the subprogram debug information entry.
Devang Patel's avatar
Devang Patel committed
  DISubprogram SPD(Desc.getNode());
Devang Patel's avatar
Devang Patel committed
  DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getNode());
  if (!SPDie) {
    ConstructSubprogram(SPD.getNode());
    SPDie = ModuleCU->getDieMapSlotFor(SPD.getNode());
  }
  assert(SPDie && "Missing subprogram descriptor");

  if (!AbstractScope) {
    // Add the function bounds.
    AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
             DWLabel("func_begin", SubprogramCount));
    AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
             DWLabel("func_end", SubprogramCount));
    MachineLocation Location(RI->getFrameRegister(*MF));
    AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
  }
Devang Patel's avatar
Devang Patel committed
  ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
  // If there are global variables at this scope then add their dies.
  for (SmallVector<WeakVH, 4>::iterator SGI = ScopedGVs.begin(), 
       SGE = ScopedGVs.end(); SGI != SGE; ++SGI) {
    MDNode *N = dyn_cast_or_null<MDNode>(*SGI);
    if (!N) continue;
    DIGlobalVariable GV(N);
    if (GV.getContext().getNode() == RootScope->getDesc().getNode()) {
      DIE *ScopedGVDie = CreateGlobalVariableDIE(ModuleCU, GV);
      SPDie->AddChild(ScopedGVDie);
    }
  }
}

/// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
///
void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
Devang Patel's avatar
Devang Patel committed
  StringMap<DIE*> &Globals = ModuleCU->getGlobals();
  StringMap<DIE*>::iterator GI = Globals.find(MF->getFunction()->getName());
  if (GI != Globals.end()) {
    DIE *SPDie = GI->second;
    // Add the function bounds.
    AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
             DWLabel("func_begin", SubprogramCount));
    AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
             DWLabel("func_end", SubprogramCount));
    MachineLocation Location(RI->getFrameRegister(*MF));
    AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
/// GetOrCreateSourceID - Look up the source id with the given directory and
/// source file names. If none currently exists, create a new id and insert it
/// in the SourceIds map. This can update DirectoryNames and SourceFileNames
/// maps as well.
unsigned DwarfDebug::GetOrCreateSourceID(const char *DirName,
                                         const char *FileName) {
  unsigned DId;
  StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
  if (DI != DirectoryIdMap.end()) {
    DId = DI->getValue();
  } else {
    DId = DirectoryNames.size() + 1;
    DirectoryIdMap[DirName] = DId;
    DirectoryNames.push_back(DirName);
  unsigned FId;
  StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
  if (FI != SourceFileIdMap.end()) {
    FId = FI->getValue();
  } else {
    FId = SourceFileNames.size() + 1;
    SourceFileIdMap[FileName] = FId;
    SourceFileNames.push_back(FileName);
  DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
    SourceIdMap.find(std::make_pair(DId, FId));
  if (SI != SourceIdMap.end())
    return SI->second;
  unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
  SourceIdMap[std::make_pair(DId, FId)] = SrcId;
  SourceIds.push_back(std::make_pair(DId, FId));
Devang Patel's avatar
Devang Patel committed
void DwarfDebug::ConstructCompileUnit(MDNode *N) {
  DICompileUnit DIUnit(N);
  const char *FN = DIUnit.getFilename();
  const char *Dir = DIUnit.getDirectory();
  unsigned ID = GetOrCreateSourceID(Dir, FN);
  DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
  AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
                   DWLabel("section_line", 0), DWLabel("section_line", 0),
                   false);
  AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
            DIUnit.getProducer());
  AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
          DIUnit.getLanguage());
  AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
    AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
  if (DIUnit.isOptimized())
    AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
  if (const char *Flags = DIUnit.getFlags())
    AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
  unsigned RVer = DIUnit.getRunTimeVersion();
  if (RVer)
    AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
            dwarf::DW_FORM_data1, RVer);
  CompileUnit *Unit = new CompileUnit(ID, Die);
Devang Patel's avatar
Devang Patel committed
  if (!ModuleCU && DIUnit.isMain()) {
    // Use first compile unit marked as isMain as the compile unit
    // for this module.
Devang Patel's avatar
Devang Patel committed
    ModuleCU = Unit;
Devang Patel's avatar
Devang Patel committed
  CompileUnitMap[DIUnit.getNode()] = Unit;
  CompileUnits.push_back(Unit);
Devang Patel's avatar
Devang Patel committed
void DwarfDebug::ConstructGlobalVariableDIE(MDNode *N) {
  DIGlobalVariable DI_GV(N);
  // If debug information is malformed then ignore it.
  if (DI_GV.Verify() == false)
    return;
  // Check for pre-existence.
Devang Patel's avatar
Devang Patel committed
  DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getNode());
Devang Patel's avatar
 
Devang Patel committed
    return;
Devang Patel's avatar
Devang Patel committed
  DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
  // Add to map.
  Slot = VariableDie;
  // Add to context owner.
Devang Patel's avatar
Devang Patel committed
  ModuleCU->getDie()->AddChild(VariableDie);
  // Expose as global. FIXME - need to check external flag.
  ModuleCU->AddGlobal(DI_GV.getName(), VariableDie);
Devang Patel's avatar
 
Devang Patel committed
  return;
Devang Patel's avatar
Devang Patel committed
void DwarfDebug::ConstructSubprogram(MDNode *N) {
  DISubprogram SP(N);
  // Check for pre-existence.
Devang Patel's avatar
Devang Patel committed
  DIE *&Slot = ModuleCU->getDieMapSlotFor(N);
Devang Patel's avatar
 
Devang Patel committed
    return;
  if (!SP.isDefinition())
    // This is a method declaration which will be handled while constructing
    // class type.
Devang Patel's avatar
 
Devang Patel committed
    return;
Devang Patel's avatar
Devang Patel committed
  DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
  // Add to map.
  Slot = SubprogramDie;
  // Add to context owner.
Devang Patel's avatar
Devang Patel committed
  ModuleCU->getDie()->AddChild(SubprogramDie);
  // Expose as global.
  ModuleCU->AddGlobal(SP.getName(), SubprogramDie);
Devang Patel's avatar
 
Devang Patel committed
  return;
Daniel Dunbar's avatar
Daniel Dunbar committed
/// BeginModule - Emit all Dwarf sections that should come prior to the
/// content. Create global DIEs and emit initial debug info sections.
/// This is inovked by the target AsmPrinter.
Devang Patel's avatar
Devang Patel committed
void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
  this->M = M;

  if (TimePassesIsEnabled)
    DebugTimer->startTimer();
Devang Patel's avatar
 
Devang Patel committed
  DebugInfoFinder DbgFinder;
  DbgFinder.processModule(*M);
Devang Patel's avatar
 
Devang Patel committed

  // Create all the compile unit DIEs.
Devang Patel's avatar
 
Devang Patel committed
  for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
         E = DbgFinder.compile_unit_end(); I != E; ++I)
Devang Patel's avatar
 
Devang Patel committed
    ConstructCompileUnit(*I);
  if (CompileUnits.empty()) {
    if (TimePassesIsEnabled)
      DebugTimer->stopTimer();
  // If main compile unit for this module is not seen than randomly
  // select first compile unit.
Devang Patel's avatar
Devang Patel committed
  if (!ModuleCU)
    ModuleCU = CompileUnits[0];
Devang Patel's avatar
 
Devang Patel committed
  // Create DIEs for each of the externally visible global variables.
Devang Patel's avatar
 
Devang Patel committed
  for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
         E = DbgFinder.global_variable_end(); I != E; ++I) {
    DIGlobalVariable GV(*I);
    if (GV.getContext().getNode() != GV.getCompileUnit().getNode())
      ScopedGVs.push_back(*I);
    else
      ConstructGlobalVariableDIE(*I);
  }
Devang Patel's avatar
 
Devang Patel committed

  // Create DIEs for each of the externally visible subprograms.
Devang Patel's avatar
 
Devang Patel committed
  for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
         E = DbgFinder.subprogram_end(); I != E; ++I)
Devang Patel's avatar
 
Devang Patel committed
    ConstructSubprogram(*I);

  MMI = mmi;
  shouldEmit = true;
  MMI->setDebugInfoAvailability(true);
  // Prime section data.
  SectionMap.insert(Asm->getObjFileLowering().getTextSection());

  // Print out .file directives to specify files for .loc directives. These are
  // printed out early so that they precede any .loc directives.
  if (MAI->hasDotLocAndDotFile()) {
    for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
      // Remember source id starts at 1.
      std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
      sys::Path FullPath(getSourceDirectoryName(Id.first));
      bool AppendOk =
        FullPath.appendComponent(getSourceFileName(Id.second));
      assert(AppendOk && "Could not append filename to directory!");
      AppendOk = false;
      Asm->EmitFile(i, FullPath.str());
  // Emit initial sections
  EmitInitial();
  if (TimePassesIsEnabled)
    DebugTimer->stopTimer();
}
/// EndModule - Emit all Dwarf sections that should come after the content.
///
void DwarfDebug::EndModule() {
  if (TimePassesIsEnabled)
    DebugTimer->startTimer();
  // Standard sections final addresses.
  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
  EmitLabel("text_end", 0);
  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
  EmitLabel("data_end", 0);
  // End text sections.
  for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
    Asm->OutStreamer.SwitchSection(SectionMap[i]);
    EmitLabel("section_end", i);
  }
  // Emit common frame information.
  EmitCommonDebugFrame();
  // Emit function debug frame information
  for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
         E = DebugFrames.end(); I != E; ++I)
    EmitFunctionDebugFrame(*I);
  // Compute DIE offsets and sizes.
  SizeAndOffsets();
  // Emit all the DIEs into a debug info section
  EmitDebugInfo();
  // Corresponding abbreviations into a abbrev section.
  EmitAbbreviations();
  // Emit source line correspondence into a debug line section.
  EmitDebugLines();
  // Emit info into a debug pubnames section.
  EmitDebugPubNames();
  // Emit info into a debug str section.
  EmitDebugStr();
  // Emit info into a debug loc section.
  EmitDebugLoc();
  // Emit info into a debug aranges section.
  EmitDebugARanges();
  // Emit info into a debug ranges section.
  EmitDebugRanges();
  // Emit info into a debug macinfo section.
  EmitDebugMacInfo();
  // Emit inline info.
  EmitDebugInlineInfo();
  if (TimePassesIsEnabled)
    DebugTimer->stopTimer();
}
/// CollectVariableInfo - Populate DbgScope entries with variables' info.
void DwarfDebug::CollectVariableInfo() {
  if (!MMI) return;
  MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
  for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
         VE = VMap.end(); VI != VE; ++VI) {
    MetadataBase *MB = VI->first;
    MDNode *Var = dyn_cast_or_null<MDNode>(MB);
    DIVariable DV (Var);
    if (DV.isNull()) continue;
    ValueMap<MDNode *, DbgScope *>::iterator DSI = 
      DbgScopeMap.find(DV.getContext().getNode());
    if (DSI != DbgScopeMap.end()) 
      Scope = DSI->second;
    else 
      // There is not any instruction assocated with this scope, so get
      // a new scope.
      Scope = getDbgScope(DV.getContext().getNode(), 
                          NULL /* Not an instruction */,
                          NULL /* Not inlined */);
    assert (Scope && "Unable to find variable scope!");
    Scope->AddVariable(new DbgVariable(DV, VSlot, false));
/// SetDbgScopeBeginLabels - Update DbgScope begin labels for the scopes that
/// start with this machine instruction.
void DwarfDebug::SetDbgScopeBeginLabels(const MachineInstr *MI, unsigned Label) {
  InsnToDbgScopeMapTy::iterator I = DbgScopeBeginMap.find(MI);
  if (I == DbgScopeBeginMap.end())
    return;
  SmallVector<DbgScope *, 2> &SD = I->second;
  for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
       SDI != SDE; ++SDI) 
    (*SDI)->setStartLabelID(Label);
}

/// SetDbgScopeEndLabels - Update DbgScope end labels for the scopes that
/// end with this machine instruction.
void DwarfDebug::SetDbgScopeEndLabels(const MachineInstr *MI, unsigned Label) {
  InsnToDbgScopeMapTy::iterator I = DbgScopeEndMap.find(MI);
Devang Patel's avatar
Devang Patel committed
  if (I == DbgScopeEndMap.end())
    return;
  SmallVector<DbgScope *, 2> &SD = I->second;
  for (SmallVector<DbgScope *, 2>::iterator SDI = SD.begin(), SDE = SD.end();
       SDI != SDE; ++SDI) 
    (*SDI)->setEndLabelID(Label);
}

/// ExtractScopeInformation - Scan machine instructions in this function
/// and collect DbgScopes. Return true, if atleast one scope was found.
bool DwarfDebug::ExtractScopeInformation(MachineFunction *MF) {
  // If scope information was extracted using .dbg intrinsics then there is not
  // any need to extract these information by scanning each instruction.
  if (!DbgScopeMap.empty())
    return false;

  // Scan each instruction and create scopes.
  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
       I != E; ++I) {
    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
         II != IE; ++II) {
      const MachineInstr *MInsn = II;
      DebugLoc DL = MInsn->getDebugLoc();
      if (DL.isUnknown())
        continue;
      DebugLocTuple DLT = MF->getDebugLocTuple(DL);
      if (!DLT.Scope)
        continue;
      // There is no need to create another DIE for compile unit. For all
      // other scopes, create one DbgScope now. This will be translated 
      // into a scope DIE at the end.
      DIDescriptor D(DLT.Scope);
        DbgScope *Scope = getDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc);
        Scope->setLastInsn(MInsn);
      }
    }
  }

  // If a scope's last instruction is not set then use its child scope's
  // last instruction as this scope's last instrunction.
  for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
	 DE = DbgScopeMap.end(); DI != DE; ++DI) {
    assert (DI->second->getFirstInsn() && "Invalid first instruction!");
    DI->second->FixInstructionMarkers();
    assert (DI->second->getLastInsn() && "Invalid last instruction!");
  }

  // Each scope has first instruction and last instruction to mark beginning
  // and end of a scope respectively. Create an inverse map that list scopes
  // starts (and ends) with an instruction. One instruction may start (or end)
  // multiple scopes.
  for (ValueMap<MDNode *, DbgScope *>::iterator DI = DbgScopeMap.begin(),
	 DE = DbgScopeMap.end(); DI != DE; ++DI) {
    DbgScope *S = DI->second;
    const MachineInstr *MI = S->getFirstInsn();
    assert (MI && "DbgScope does not have first instruction!");

    InsnToDbgScopeMapTy::iterator IDI = DbgScopeBeginMap.find(MI);
    if (IDI != DbgScopeBeginMap.end())
      IDI->second.push_back(S);
    else
      DbgScopeBeginMap.insert(std::make_pair(MI, 
                                             SmallVector<DbgScope *, 2>(2, S)));

    MI = S->getLastInsn();
    assert (MI && "DbgScope does not have last instruction!");
    IDI = DbgScopeEndMap.find(MI);
    if (IDI != DbgScopeEndMap.end())
      IDI->second.push_back(S);
    else
      DbgScopeEndMap.insert(std::make_pair(MI,
                                             SmallVector<DbgScope *, 2>(2, S)));
  }

  return !DbgScopeMap.empty();
}

static DISubprogram getDISubprogram(MDNode *N) {

  DIDescriptor D(N);
  if (D.isNull())
    return DISubprogram();

  if (D.isCompileUnit()) 
    return DISubprogram();

  if (D.isSubprogram())
    return DISubprogram(N);

  if (D.isLexicalBlock())
    return getDISubprogram(DILexicalBlock(N).getContext().getNode());

Daniel Dunbar's avatar
Daniel Dunbar committed
  llvm_unreachable("Unexpected Descriptor!");
/// BeginFunction - Gather pre-function debug information.  Assumes being
/// emitted immediately after the function entry point.
void DwarfDebug::BeginFunction(MachineFunction *MF) {
  this->MF = MF;
  if (!ShouldEmitDwarfDebug()) return;
  if (TimePassesIsEnabled)
    DebugTimer->startTimer();
#ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
  if (!ExtractScopeInformation(MF))
    return;
  // Begin accumulating function debug information.
  MMI->BeginFunction(MF);
  // Assumes in correct section after the entry point.
  EmitLabel("func_begin", ++SubprogramCount);

  // Emit label for the implicitly defined dbg.stoppoint at the start of the
  // function.
  DebugLoc FDL = MF->getDefaultDebugLoc();
  if (!FDL.isUnknown()) {
    DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
    unsigned LabelID = 0;
    DISubprogram SP = getDISubprogram(DLT.Scope);
      LabelID = RecordSourceLine(SP.getLineNumber(), 0, DLT.Scope);
      LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.Scope);
  DebugLoc FDL = MF->getDefaultDebugLoc();
  if (!FDL.isUnknown()) {
    DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
    unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col, DLT.Scope);