LLVM  mainline
DwarfCompileUnit.cpp
Go to the documentation of this file.
00001 #include "DwarfCompileUnit.h"
00002 #include "DwarfExpression.h"
00003 #include "llvm/CodeGen/MachineFunction.h"
00004 #include "llvm/IR/Constants.h"
00005 #include "llvm/IR/DataLayout.h"
00006 #include "llvm/IR/GlobalValue.h"
00007 #include "llvm/IR/GlobalVariable.h"
00008 #include "llvm/IR/Instruction.h"
00009 #include "llvm/MC/MCAsmInfo.h"
00010 #include "llvm/MC/MCStreamer.h"
00011 #include "llvm/Target/TargetFrameLowering.h"
00012 #include "llvm/Target/TargetLoweringObjectFile.h"
00013 #include "llvm/Target/TargetMachine.h"
00014 #include "llvm/Target/TargetRegisterInfo.h"
00015 #include "llvm/Target/TargetSubtargetInfo.h"
00016 
00017 namespace llvm {
00018 
00019 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
00020                                    AsmPrinter *A, DwarfDebug *DW,
00021                                    DwarfFile *DWU)
00022     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU),
00023       Skeleton(nullptr), BaseAddress(nullptr) {
00024   insertDIE(Node, &getUnitDie());
00025 }
00026 
00027 /// addLabelAddress - Add a dwarf label attribute data and value using
00028 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
00029 ///
00030 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
00031                                        const MCSymbol *Label) {
00032 
00033   // Don't use the address pool in non-fission or in the skeleton unit itself.
00034   // FIXME: Once GDB supports this, it's probably worthwhile using the address
00035   // pool from the skeleton - maybe even in non-fission (possibly fewer
00036   // relocations by sharing them in the pool, but we have other ideas about how
00037   // to reduce the number of relocations as well/instead).
00038   if (!DD->useSplitDwarf() || !Skeleton)
00039     return addLocalLabelAddress(Die, Attribute, Label);
00040 
00041   if (Label)
00042     DD->addArangeLabel(SymbolCU(this, Label));
00043 
00044   unsigned idx = DD->getAddressPool().getIndex(Label);
00045   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
00046                DIEInteger(idx));
00047 }
00048 
00049 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
00050                                             dwarf::Attribute Attribute,
00051                                             const MCSymbol *Label) {
00052   if (Label)
00053     DD->addArangeLabel(SymbolCU(this, Label));
00054 
00055   if (Label)
00056     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
00057                  DIELabel(Label));
00058   else
00059     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
00060                  DIEInteger(0));
00061 }
00062 
00063 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
00064                                                StringRef DirName) {
00065   // If we print assembly, we can't separate .file entries according to
00066   // compile units. Thus all files will belong to the default compile unit.
00067 
00068   // FIXME: add a better feature test than hasRawTextSupport. Even better,
00069   // extend .file to support this.
00070   return Asm->OutStreamer->EmitDwarfFileDirective(
00071       0, DirName, FileName,
00072       Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
00073 }
00074 
00075 // Return const expression if value is a GEP to access merged global
00076 // constant. e.g.
00077 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
00078 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
00079   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
00080   if (!CE || CE->getNumOperands() != 3 ||
00081       CE->getOpcode() != Instruction::GetElementPtr)
00082     return nullptr;
00083 
00084   // First operand points to a global struct.
00085   Value *Ptr = CE->getOperand(0);
00086   GlobalValue *GV = dyn_cast<GlobalValue>(Ptr);
00087   if (!GV || !isa<StructType>(GV->getValueType()))
00088     return nullptr;
00089 
00090   // Second operand is zero.
00091   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
00092   if (!CI || !CI->isZero())
00093     return nullptr;
00094 
00095   // Third operand is offset.
00096   if (!isa<ConstantInt>(CE->getOperand(2)))
00097     return nullptr;
00098 
00099   return CE;
00100 }
00101 
00102 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
00103 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
00104     const DIGlobalVariable *GV) {
00105   // Check for pre-existence.
00106   if (DIE *Die = getDIE(GV))
00107     return Die;
00108 
00109   assert(GV);
00110 
00111   auto *GVContext = GV->getScope();
00112   auto *GTy = DD->resolve(GV->getType());
00113 
00114   // Construct the context before querying for the existence of the DIE in
00115   // case such construction creates the DIE.
00116   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
00117 
00118   // Add to map.
00119   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
00120   DIScope *DeclContext;
00121   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
00122     DeclContext = resolve(SDMDecl->getScope());
00123     assert(SDMDecl->isStaticMember() && "Expected static member decl");
00124     assert(GV->isDefinition());
00125     // We need the declaration DIE that is in the static member's class.
00126     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
00127     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
00128   } else {
00129     DeclContext = GV->getScope();
00130     // Add name and type.
00131     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
00132     addType(*VariableDIE, GTy);
00133 
00134     // Add scoping info.
00135     if (!GV->isLocalToUnit())
00136       addFlag(*VariableDIE, dwarf::DW_AT_external);
00137 
00138     // Add line number info.
00139     addSourceLine(*VariableDIE, GV);
00140   }
00141 
00142   if (!GV->isDefinition())
00143     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
00144   else
00145     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
00146 
00147   // Add location.
00148   bool addToAccelTable = false;
00149   if (auto *Global = dyn_cast_or_null<GlobalVariable>(GV->getVariable())) {
00150     addToAccelTable = true;
00151     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
00152     const MCSymbol *Sym = Asm->getSymbol(Global);
00153     if (Global->isThreadLocal()) {
00154       if (Asm->TM.Options.EmulatedTLS) {
00155         // TODO: add debug info for emulated thread local mode.
00156       } else {
00157         // FIXME: Make this work with -gsplit-dwarf.
00158         unsigned PointerSize = Asm->getDataLayout().getPointerSize();
00159         assert((PointerSize == 4 || PointerSize == 8) &&
00160                "Add support for other sizes if necessary");
00161         // Based on GCC's support for TLS:
00162         if (!DD->useSplitDwarf()) {
00163           // 1) Start with a constNu of the appropriate pointer size
00164           addUInt(*Loc, dwarf::DW_FORM_data1, PointerSize == 4
00165                                                   ? dwarf::DW_OP_const4u
00166                                                   : dwarf::DW_OP_const8u);
00167           // 2) containing the (relocated) offset of the TLS variable
00168           //    within the module's TLS block.
00169           addExpr(*Loc, dwarf::DW_FORM_udata,
00170                   Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
00171         } else {
00172           addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
00173           addUInt(*Loc, dwarf::DW_FORM_udata,
00174                   DD->getAddressPool().getIndex(Sym, /* TLS */ true));
00175         }
00176         // 3) followed by an OP to make the debugger do a TLS lookup.
00177         addUInt(*Loc, dwarf::DW_FORM_data1,
00178                 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
00179                                       : dwarf::DW_OP_form_tls_address);
00180       }
00181     } else {
00182       DD->addArangeLabel(SymbolCU(this, Sym));
00183       addOpAddress(*Loc, Sym);
00184     }
00185 
00186     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
00187     addLinkageName(*VariableDIE, GV->getLinkageName());
00188   } else if (const ConstantInt *CI =
00189                  dyn_cast_or_null<ConstantInt>(GV->getVariable())) {
00190     addConstantValue(*VariableDIE, CI, GTy);
00191   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getVariable())) {
00192     addToAccelTable = true;
00193     // GV is a merged global.
00194     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
00195     auto *Ptr = cast<GlobalValue>(CE->getOperand(0));
00196     MCSymbol *Sym = Asm->getSymbol(Ptr);
00197     DD->addArangeLabel(SymbolCU(this, Sym));
00198     addOpAddress(*Loc, Sym);
00199     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
00200     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
00201     addUInt(*Loc, dwarf::DW_FORM_udata,
00202             Asm->getDataLayout().getIndexedOffsetInType(Ptr->getValueType(), Idx));
00203     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
00204     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
00205   }
00206 
00207   if (addToAccelTable) {
00208     DD->addAccelName(GV->getName(), *VariableDIE);
00209 
00210     // If the linkage name is different than the name, go ahead and output
00211     // that as well into the name table.
00212     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
00213       DD->addAccelName(GV->getLinkageName(), *VariableDIE);
00214   }
00215 
00216   return VariableDIE;
00217 }
00218 
00219 void DwarfCompileUnit::addRange(RangeSpan Range) {
00220   bool SameAsPrevCU = this == DD->getPrevCU();
00221   DD->setPrevCU(this);
00222   // If we have no current ranges just add the range and return, otherwise,
00223   // check the current section and CU against the previous section and CU we
00224   // emitted into and the subprogram was contained within. If these are the
00225   // same then extend our current range, otherwise add this as a new range.
00226   if (CURanges.empty() || !SameAsPrevCU ||
00227       (&CURanges.back().getEnd()->getSection() !=
00228        &Range.getEnd()->getSection())) {
00229     CURanges.push_back(Range);
00230     return;
00231   }
00232 
00233   CURanges.back().setEnd(Range.getEnd());
00234 }
00235 
00236 DIE::value_iterator
00237 DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
00238                                   const MCSymbol *Label, const MCSymbol *Sec) {
00239   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
00240     return addLabel(Die, Attribute,
00241                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00242                                                : dwarf::DW_FORM_data4,
00243                     Label);
00244   return addSectionDelta(Die, Attribute, Label, Sec);
00245 }
00246 
00247 void DwarfCompileUnit::initStmtList() {
00248   // Define start line table label for each Compile Unit.
00249   MCSymbol *LineTableStartSym =
00250       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
00251 
00252   // DW_AT_stmt_list is a offset of line number information for this
00253   // compile unit in debug_line section. For split dwarf this is
00254   // left in the skeleton CU and so not included.
00255   // The line table entries are not always emitted in assembly, so it
00256   // is not okay to use line_table_start here.
00257   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
00258   StmtListValue =
00259       addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
00260                       TLOF.getDwarfLineSection()->getBeginSymbol());
00261 }
00262 
00263 void DwarfCompileUnit::applyStmtList(DIE &D) {
00264   D.addValue(DIEValueAllocator, *StmtListValue);
00265 }
00266 
00267 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
00268                                        const MCSymbol *End) {
00269   assert(Begin && "Begin label should not be null!");
00270   assert(End && "End label should not be null!");
00271   assert(Begin->isDefined() && "Invalid starting label");
00272   assert(End->isDefined() && "Invalid end label");
00273 
00274   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
00275   if (DD->getDwarfVersion() < 4)
00276     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
00277   else
00278     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
00279 }
00280 
00281 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
00282 // and DW_AT_high_pc attributes. If there are global variables in this
00283 // scope then create and insert DIEs for these variables.
00284 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
00285   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
00286 
00287   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
00288   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
00289           *DD->getCurrentFunction()))
00290     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
00291 
00292   // Only include DW_AT_frame_base in full debug info
00293   if (!includeMinimalInlineScopes()) {
00294     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
00295     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
00296     if (RI->isPhysicalRegister(Location.getReg()))
00297       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
00298   }
00299 
00300   // Add name to the name table, we do this here because we're guaranteed
00301   // to have concrete versions of our DW_TAG_subprogram nodes.
00302   DD->addSubprogramNames(SP, *SPDie);
00303 
00304   return *SPDie;
00305 }
00306 
00307 // Construct a DIE for this scope.
00308 void DwarfCompileUnit::constructScopeDIE(
00309     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
00310   if (!Scope || !Scope->getScopeNode())
00311     return;
00312 
00313   auto *DS = Scope->getScopeNode();
00314 
00315   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
00316          "Only handle inlined subprograms here, use "
00317          "constructSubprogramScopeDIE for non-inlined "
00318          "subprograms");
00319 
00320   SmallVector<DIE *, 8> Children;
00321 
00322   // We try to create the scope DIE first, then the children DIEs. This will
00323   // avoid creating un-used children then removing them later when we find out
00324   // the scope DIE is null.
00325   DIE *ScopeDIE;
00326   if (Scope->getParent() && isa<DISubprogram>(DS)) {
00327     ScopeDIE = constructInlinedScopeDIE(Scope);
00328     if (!ScopeDIE)
00329       return;
00330     // We create children when the scope DIE is not null.
00331     createScopeChildrenDIE(Scope, Children);
00332   } else {
00333     // Early exit when we know the scope DIE is going to be null.
00334     if (DD->isLexicalScopeDIENull(Scope))
00335       return;
00336 
00337     unsigned ChildScopeCount;
00338 
00339     // We create children here when we know the scope DIE is not going to be
00340     // null and the children will be added to the scope DIE.
00341     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
00342 
00343     // Skip imported directives in gmlt-like data.
00344     if (!includeMinimalInlineScopes()) {
00345       // There is no need to emit empty lexical block DIE.
00346       for (const auto *IE : ImportedEntities[DS])
00347         Children.push_back(
00348             constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
00349     }
00350 
00351     // If there are only other scopes as children, put them directly in the
00352     // parent instead, as this scope would serve no purpose.
00353     if (Children.size() == ChildScopeCount) {
00354       FinalChildren.insert(FinalChildren.end(),
00355                            std::make_move_iterator(Children.begin()),
00356                            std::make_move_iterator(Children.end()));
00357       return;
00358     }
00359     ScopeDIE = constructLexicalScopeDIE(Scope);
00360     assert(ScopeDIE && "Scope DIE should not be null.");
00361   }
00362 
00363   // Add children
00364   for (auto &I : Children)
00365     ScopeDIE->addChild(std::move(I));
00366 
00367   FinalChildren.push_back(std::move(ScopeDIE));
00368 }
00369 
00370 DIE::value_iterator
00371 DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
00372                                   const MCSymbol *Hi, const MCSymbol *Lo) {
00373   return Die.addValue(DIEValueAllocator, Attribute,
00374                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00375                                                  : dwarf::DW_FORM_data4,
00376                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
00377 }
00378 
00379 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
00380                                          SmallVector<RangeSpan, 2> Range) {
00381   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
00382 
00383   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
00384   // emitting it appropriately.
00385   const MCSymbol *RangeSectionSym =
00386       TLOF.getDwarfRangesSection()->getBeginSymbol();
00387 
00388   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
00389 
00390   // Under fission, ranges are specified by constant offsets relative to the
00391   // CU's DW_AT_GNU_ranges_base.
00392   if (isDwoUnit())
00393     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00394                     RangeSectionSym);
00395   else
00396     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00397                     RangeSectionSym);
00398 
00399   // Add the range list to the set of ranges to be emitted.
00400   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
00401 }
00402 
00403 void DwarfCompileUnit::attachRangesOrLowHighPC(
00404     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
00405   if (Ranges.size() == 1) {
00406     const auto &single = Ranges.front();
00407     attachLowHighPC(Die, single.getStart(), single.getEnd());
00408   } else
00409     addScopeRangeList(Die, std::move(Ranges));
00410 }
00411 
00412 void DwarfCompileUnit::attachRangesOrLowHighPC(
00413     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
00414   SmallVector<RangeSpan, 2> List;
00415   List.reserve(Ranges.size());
00416   for (const InsnRange &R : Ranges)
00417     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
00418                              DD->getLabelAfterInsn(R.second)));
00419   attachRangesOrLowHighPC(Die, std::move(List));
00420 }
00421 
00422 // This scope represents inlined body of a function. Construct DIE to
00423 // represent this concrete inlined copy of the function.
00424 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
00425   assert(Scope->getScopeNode());
00426   auto *DS = Scope->getScopeNode();
00427   auto *InlinedSP = getDISubprogram(DS);
00428   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
00429   // was inlined from another compile unit.
00430   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
00431   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
00432 
00433   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
00434   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
00435 
00436   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00437 
00438   // Add the call site information to the DIE.
00439   const DILocation *IA = Scope->getInlinedAt();
00440   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
00441           getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
00442   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
00443   if (IA->getDiscriminator())
00444     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
00445             IA->getDiscriminator());
00446 
00447   // Add name to the name table, we do this here because we're guaranteed
00448   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
00449   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
00450 
00451   return ScopeDIE;
00452 }
00453 
00454 // Construct new DW_TAG_lexical_block for this scope and attach
00455 // DW_AT_low_pc/DW_AT_high_pc labels.
00456 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
00457   if (DD->isLexicalScopeDIENull(Scope))
00458     return nullptr;
00459 
00460   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
00461   if (Scope->isAbstractScope())
00462     return ScopeDIE;
00463 
00464   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00465 
00466   return ScopeDIE;
00467 }
00468 
00469 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
00470 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
00471   auto D = constructVariableDIEImpl(DV, Abstract);
00472   DV.setDIE(*D);
00473   return D;
00474 }
00475 
00476 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
00477                                                 bool Abstract) {
00478   // Define variable debug information entry.
00479   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
00480 
00481   if (Abstract) {
00482     applyVariableAttributes(DV, *VariableDie);
00483     return VariableDie;
00484   }
00485 
00486   // Add variable address.
00487 
00488   unsigned Offset = DV.getDebugLocListIndex();
00489   if (Offset != ~0U) {
00490     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
00491     return VariableDie;
00492   }
00493 
00494   // Check if variable is described by a DBG_VALUE instruction.
00495   if (const MachineInstr *DVInsn = DV.getMInsn()) {
00496     assert(DVInsn->getNumOperands() == 4);
00497     if (DVInsn->getOperand(0).isReg()) {
00498       const MachineOperand RegOp = DVInsn->getOperand(0);
00499       // If the second operand is an immediate, this is an indirect value.
00500       if (DVInsn->getOperand(1).isImm()) {
00501         MachineLocation Location(RegOp.getReg(),
00502                                  DVInsn->getOperand(1).getImm());
00503         addVariableAddress(DV, *VariableDie, Location);
00504       } else if (RegOp.getReg())
00505         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
00506     } else if (DVInsn->getOperand(0).isImm())
00507       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
00508     else if (DVInsn->getOperand(0).isFPImm())
00509       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
00510     else if (DVInsn->getOperand(0).isCImm())
00511       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
00512                        DV.getType());
00513 
00514     return VariableDie;
00515   }
00516 
00517   // .. else use frame index.
00518   if (DV.getFrameIndex().empty())
00519     return VariableDie;
00520 
00521   auto Expr = DV.getExpression().begin();
00522   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
00523   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
00524   for (auto FI : DV.getFrameIndex()) {
00525     unsigned FrameReg = 0;
00526     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
00527     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
00528     assert(Expr != DV.getExpression().end() && "Wrong number of expressions");
00529     DwarfExpr.AddMachineRegIndirect(FrameReg, Offset);
00530     DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end());
00531     ++Expr;
00532   }
00533   addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
00534 
00535   return VariableDie;
00536 }
00537 
00538 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
00539                                             const LexicalScope &Scope,
00540                                             DIE *&ObjectPointer) {
00541   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
00542   if (DV.isObjectPointer())
00543     ObjectPointer = Var;
00544   return Var;
00545 }
00546 
00547 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
00548                                               SmallVectorImpl<DIE *> &Children,
00549                                               unsigned *ChildScopeCount) {
00550   DIE *ObjectPointer = nullptr;
00551 
00552   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
00553     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
00554 
00555   unsigned ChildCountWithoutScopes = Children.size();
00556 
00557   for (LexicalScope *LS : Scope->getChildren())
00558     constructScopeDIE(LS, Children);
00559 
00560   if (ChildScopeCount)
00561     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
00562 
00563   return ObjectPointer;
00564 }
00565 
00566 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
00567   assert(Scope && Scope->getScopeNode());
00568   assert(!Scope->getInlinedAt());
00569   assert(!Scope->isAbstractScope());
00570   auto *Sub = cast<DISubprogram>(Scope->getScopeNode());
00571 
00572   DD->getProcessedSPNodes().insert(Sub);
00573 
00574   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
00575 
00576   // If this is a variadic function, add an unspecified parameter.
00577   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
00578 
00579   // Collect lexical scope children first.
00580   // ObjectPointer might be a local (non-argument) local variable if it's a
00581   // block's synthetic this pointer.
00582   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
00583     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
00584 
00585   // If we have a single element of null, it is a function that returns void.
00586   // If we have more than one elements and the last one is null, it is a
00587   // variadic function.
00588   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
00589       !includeMinimalInlineScopes())
00590     ScopeDIE.addChild(
00591         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
00592 }
00593 
00594 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
00595                                                  DIE &ScopeDIE) {
00596   // We create children when the scope DIE is not null.
00597   SmallVector<DIE *, 8> Children;
00598   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
00599 
00600   // Add children
00601   for (auto &I : Children)
00602     ScopeDIE.addChild(std::move(I));
00603 
00604   return ObjectPointer;
00605 }
00606 
00607 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
00608     LexicalScope *Scope) {
00609   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
00610   if (AbsDef)
00611     return;
00612 
00613   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
00614 
00615   DIE *ContextDIE;
00616 
00617   if (includeMinimalInlineScopes())
00618     ContextDIE = &getUnitDie();
00619   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
00620   // the important distinction that the debug node is not associated with the
00621   // DIE (since the debug node will be associated with the concrete DIE, if
00622   // any). It could be refactored to some common utility function.
00623   else if (auto *SPDecl = SP->getDeclaration()) {
00624     ContextDIE = &getUnitDie();
00625     getOrCreateSubprogramDIE(SPDecl);
00626   } else
00627     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
00628 
00629   // Passing null as the associated node because the abstract definition
00630   // shouldn't be found by lookup.
00631   AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
00632   applySubprogramAttributesToDefinition(SP, *AbsDef);
00633 
00634   if (!includeMinimalInlineScopes())
00635     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
00636   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
00637     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
00638 }
00639 
00640 DIE *DwarfCompileUnit::constructImportedEntityDIE(
00641     const DIImportedEntity *Module) {
00642   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
00643   insertDIE(Module, IMDie);
00644   DIE *EntityDie;
00645   auto *Entity = resolve(Module->getEntity());
00646   if (auto *NS = dyn_cast<DINamespace>(Entity))
00647     EntityDie = getOrCreateNameSpace(NS);
00648   else if (auto *M = dyn_cast<DIModule>(Entity))
00649     EntityDie = getOrCreateModule(M);
00650   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
00651     EntityDie = getOrCreateSubprogramDIE(SP);
00652   else if (auto *T = dyn_cast<DIType>(Entity))
00653     EntityDie = getOrCreateTypeDIE(T);
00654   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
00655     EntityDie = getOrCreateGlobalVariableDIE(GV);
00656   else
00657     EntityDie = getDIE(Entity);
00658   assert(EntityDie);
00659   addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
00660                 Module->getScope()->getDirectory());
00661   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
00662   StringRef Name = Module->getName();
00663   if (!Name.empty())
00664     addString(*IMDie, dwarf::DW_AT_name, Name);
00665 
00666   return IMDie;
00667 }
00668 
00669 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
00670   DIE *D = getDIE(SP);
00671   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
00672     if (D)
00673       // If this subprogram has an abstract definition, reference that
00674       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
00675   } else {
00676     if (!D && !includeMinimalInlineScopes())
00677       // Lazily construct the subprogram if we didn't see either concrete or
00678       // inlined versions during codegen. (except in -gmlt ^ where we want
00679       // to omit these entirely)
00680       D = getOrCreateSubprogramDIE(SP);
00681     if (D)
00682       // And attach the attributes
00683       applySubprogramAttributesToDefinition(SP, *D);
00684   }
00685 }
00686 void DwarfCompileUnit::collectDeadVariables(const DISubprogram *SP) {
00687   assert(SP && "CU's subprogram list contains a non-subprogram");
00688   assert(SP->isDefinition() &&
00689          "CU's subprogram list contains a subprogram declaration");
00690   auto Variables = SP->getVariables();
00691   if (Variables.size() == 0)
00692     return;
00693 
00694   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
00695   if (!SPDIE)
00696     SPDIE = getDIE(SP);
00697   assert(SPDIE);
00698   for (const DILocalVariable *DV : Variables) {
00699     DbgVariable NewVar(DV, /* IA */ nullptr, DD);
00700     auto VariableDie = constructVariableDIE(NewVar);
00701     applyVariableAttributes(NewVar, *VariableDie);
00702     SPDIE->addChild(std::move(VariableDie));
00703   }
00704 }
00705 
00706 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
00707   // Don't bother labeling the .dwo unit, as its offset isn't used.
00708   if (!Skeleton) {
00709     LabelBegin = Asm->createTempSymbol("cu_begin");
00710     Asm->OutStreamer->EmitLabel(LabelBegin);
00711   }
00712 
00713   DwarfUnit::emitHeader(UseOffsets);
00714 }
00715 
00716 /// addGlobalName - Add a new global name to the compile unit.
00717 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
00718                                      const DIScope *Context) {
00719   if (includeMinimalInlineScopes())
00720     return;
00721   std::string FullName = getParentContextString(Context) + Name.str();
00722   GlobalNames[FullName] = &Die;
00723 }
00724 
00725 /// Add a new global type to the unit.
00726 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
00727                                      const DIScope *Context) {
00728   if (includeMinimalInlineScopes())
00729     return;
00730   std::string FullName = getParentContextString(Context) + Ty->getName().str();
00731   GlobalTypes[FullName] = &Die;
00732 }
00733 
00734 /// addVariableAddress - Add DW_AT_location attribute for a
00735 /// DbgVariable based on provided MachineLocation.
00736 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
00737                                           MachineLocation Location) {
00738   if (DV.hasComplexAddress())
00739     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
00740   else if (DV.isBlockByrefVariable())
00741     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
00742   else
00743     addAddress(Die, dwarf::DW_AT_location, Location);
00744 }
00745 
00746 /// Add an address attribute to a die based on the location provided.
00747 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
00748                                   const MachineLocation &Location) {
00749   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
00750 
00751   bool validReg;
00752   if (Location.isReg())
00753     validReg = addRegisterOpPiece(*Loc, Location.getReg());
00754   else
00755     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
00756 
00757   if (!validReg)
00758     return;
00759 
00760   // Now attach the location information to the DIE.
00761   addBlock(Die, Attribute, Loc);
00762 }
00763 
00764 /// Start with the address based on the location provided, and generate the
00765 /// DWARF information necessary to find the actual variable given the extra
00766 /// address information encoded in the DbgVariable, starting from the starting
00767 /// location.  Add the DWARF information to the die.
00768 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
00769                                          dwarf::Attribute Attribute,
00770                                          const MachineLocation &Location) {
00771   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
00772   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
00773   assert(DV.getExpression().size() == 1);
00774   const DIExpression *Expr = DV.getExpression().back();
00775   bool ValidReg;
00776   if (Location.getOffset()) {
00777     ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(),
00778                                                Location.getOffset());
00779     if (ValidReg)
00780       DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
00781   } else
00782     ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg());
00783 
00784   // Now attach the location information to the DIE.
00785   if (ValidReg)
00786     addBlock(Die, Attribute, Loc);
00787 }
00788 
00789 /// Add a Dwarf loclistptr attribute data and value.
00790 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
00791                                        unsigned Index) {
00792   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00793                                                 : dwarf::DW_FORM_data4;
00794   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
00795 }
00796 
00797 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
00798                                                DIE &VariableDie) {
00799   StringRef Name = Var.getName();
00800   if (!Name.empty())
00801     addString(VariableDie, dwarf::DW_AT_name, Name);
00802   addSourceLine(VariableDie, Var.getVariable());
00803   addType(VariableDie, Var.getType());
00804   if (Var.isArtificial())
00805     addFlag(VariableDie, dwarf::DW_AT_artificial);
00806 }
00807 
00808 /// Add a Dwarf expression attribute data and value.
00809 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
00810                                const MCExpr *Expr) {
00811   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
00812 }
00813 
00814 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
00815     const DISubprogram *SP, DIE &SPDie) {
00816   auto *SPDecl = SP->getDeclaration();
00817   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
00818   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
00819   addGlobalName(SP->getName(), SPDie, Context);
00820 }
00821 
00822 bool DwarfCompileUnit::isDwoUnit() const {
00823   return DD->useSplitDwarf() && Skeleton;
00824 }
00825 
00826 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
00827   return getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly ||
00828          (DD->useSplitDwarf() && !Skeleton);
00829 }
00830 } // end llvm namespace