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