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