DwarfDebug.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  1. //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains support for writing dwarf debug info into asm files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ByteStreamer.h"
  14. #include "DwarfDebug.h"
  15. #include "DIE.h"
  16. #include "DIEHash.h"
  17. #include "DwarfUnit.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/Triple.h"
  22. #include "llvm/CodeGen/MachineFunction.h"
  23. #include "llvm/CodeGen/MachineModuleInfo.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/DIBuilder.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DebugInfo.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/ValueHandle.h"
  31. #include "llvm/MC/MCAsmInfo.h"
  32. #include "llvm/MC/MCSection.h"
  33. #include "llvm/MC/MCStreamer.h"
  34. #include "llvm/MC/MCSymbol.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/Dwarf.h"
  38. #include "llvm/Support/Endian.h"
  39. #include "llvm/Support/ErrorHandling.h"
  40. #include "llvm/Support/FormattedStream.h"
  41. #include "llvm/Support/LEB128.h"
  42. #include "llvm/Support/MD5.h"
  43. #include "llvm/Support/Path.h"
  44. #include "llvm/Support/Timer.h"
  45. #include "llvm/Target/TargetFrameLowering.h"
  46. #include "llvm/Target/TargetLoweringObjectFile.h"
  47. #include "llvm/Target/TargetMachine.h"
  48. #include "llvm/Target/TargetOptions.h"
  49. #include "llvm/Target/TargetRegisterInfo.h"
  50. #include "llvm/Target/TargetSubtargetInfo.h"
  51. using namespace llvm;
  52. #define DEBUG_TYPE "dwarfdebug"
  53. static cl::opt<bool>
  54. DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
  55. cl::desc("Disable debug info printing"));
  56. static cl::opt<bool> UnknownLocations(
  57. "use-unknown-locations", cl::Hidden,
  58. cl::desc("Make an absence of debug location information explicit."),
  59. cl::init(false));
  60. static cl::opt<bool>
  61. GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
  62. cl::desc("Generate GNU-style pubnames and pubtypes"),
  63. cl::init(false));
  64. static cl::opt<bool> GenerateARangeSection("generate-arange-section",
  65. cl::Hidden,
  66. cl::desc("Generate dwarf aranges"),
  67. cl::init(false));
  68. namespace {
  69. enum DefaultOnOff { Default, Enable, Disable };
  70. }
  71. static cl::opt<DefaultOnOff>
  72. DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
  73. cl::desc("Output prototype dwarf accelerator tables."),
  74. cl::values(clEnumVal(Default, "Default for platform"),
  75. clEnumVal(Enable, "Enabled"),
  76. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  77. cl::init(Default));
  78. static cl::opt<DefaultOnOff>
  79. SplitDwarf("split-dwarf", cl::Hidden,
  80. cl::desc("Output DWARF5 split debug info."),
  81. cl::values(clEnumVal(Default, "Default for platform"),
  82. clEnumVal(Enable, "Enabled"),
  83. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  84. cl::init(Default));
  85. static cl::opt<DefaultOnOff>
  86. DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
  87. cl::desc("Generate DWARF pubnames and pubtypes sections"),
  88. cl::values(clEnumVal(Default, "Default for platform"),
  89. clEnumVal(Enable, "Enabled"),
  90. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  91. cl::init(Default));
  92. static const char *const DWARFGroupName = "DWARF Emission";
  93. static const char *const DbgTimerName = "DWARF Debug Writer";
  94. //===----------------------------------------------------------------------===//
  95. /// resolve - Look in the DwarfDebug map for the MDNode that
  96. /// corresponds to the reference.
  97. template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
  98. return DD->resolve(Ref);
  99. }
  100. bool DbgVariable::isBlockByrefVariable() const {
  101. assert(Var.isVariable() && "Invalid complex DbgVariable!");
  102. return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
  103. }
  104. DIType DbgVariable::getType() const {
  105. DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
  106. // FIXME: isBlockByrefVariable should be reformulated in terms of complex
  107. // addresses instead.
  108. if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
  109. /* Byref variables, in Blocks, are declared by the programmer as
  110. "SomeType VarName;", but the compiler creates a
  111. __Block_byref_x_VarName struct, and gives the variable VarName
  112. either the struct, or a pointer to the struct, as its type. This
  113. is necessary for various behind-the-scenes things the compiler
  114. needs to do with by-reference variables in blocks.
  115. However, as far as the original *programmer* is concerned, the
  116. variable should still have type 'SomeType', as originally declared.
  117. The following function dives into the __Block_byref_x_VarName
  118. struct to find the original type of the variable. This will be
  119. passed back to the code generating the type for the Debug
  120. Information Entry for the variable 'VarName'. 'VarName' will then
  121. have the original type 'SomeType' in its debug information.
  122. The original type 'SomeType' will be the type of the field named
  123. 'VarName' inside the __Block_byref_x_VarName struct.
  124. NOTE: In order for this to not completely fail on the debugger
  125. side, the Debug Information Entry for the variable VarName needs to
  126. have a DW_AT_location that tells the debugger how to unwind through
  127. the pointers and __Block_byref_x_VarName struct to find the actual
  128. value of the variable. The function addBlockByrefType does this. */
  129. DIType subType = Ty;
  130. uint16_t tag = Ty.getTag();
  131. if (tag == dwarf::DW_TAG_pointer_type)
  132. subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
  133. DIArray Elements = DICompositeType(subType).getElements();
  134. for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
  135. DIDerivedType DT(Elements.getElement(i));
  136. if (getName() == DT.getName())
  137. return (resolve(DT.getTypeDerivedFrom()));
  138. }
  139. }
  140. return Ty;
  141. }
  142. static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
  143. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
  144. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
  145. DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
  146. DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
  147. : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
  148. GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
  149. UsedNonDefaultText(false),
  150. SkeletonHolder(A, "skel_string", DIEValueAllocator),
  151. AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  152. dwarf::DW_FORM_data4)),
  153. AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  154. dwarf::DW_FORM_data4)),
  155. AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  156. dwarf::DW_FORM_data4)),
  157. AccelTypes(TypeAtoms) {
  158. DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
  159. DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
  160. DwarfLineSectionSym = nullptr;
  161. DwarfAddrSectionSym = nullptr;
  162. DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
  163. FunctionBeginSym = FunctionEndSym = nullptr;
  164. CurFn = nullptr;
  165. CurMI = nullptr;
  166. // Turn on accelerator tables for Darwin by default, pubnames by
  167. // default for non-Darwin, and handle split dwarf.
  168. bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
  169. if (DwarfAccelTables == Default)
  170. HasDwarfAccelTables = IsDarwin;
  171. else
  172. HasDwarfAccelTables = DwarfAccelTables == Enable;
  173. if (SplitDwarf == Default)
  174. HasSplitDwarf = false;
  175. else
  176. HasSplitDwarf = SplitDwarf == Enable;
  177. if (DwarfPubSections == Default)
  178. HasDwarfPubSections = !IsDarwin;
  179. else
  180. HasDwarfPubSections = DwarfPubSections == Enable;
  181. unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
  182. DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
  183. : MMI->getModule()->getDwarfVersion();
  184. Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
  185. {
  186. NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
  187. beginModule();
  188. }
  189. }
  190. // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
  191. DwarfDebug::~DwarfDebug() { }
  192. // Switch to the specified MCSection and emit an assembler
  193. // temporary label to it if SymbolStem is specified.
  194. static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
  195. const char *SymbolStem = nullptr) {
  196. Asm->OutStreamer.SwitchSection(Section);
  197. if (!SymbolStem)
  198. return nullptr;
  199. MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
  200. Asm->OutStreamer.EmitLabel(TmpSym);
  201. return TmpSym;
  202. }
  203. static bool isObjCClass(StringRef Name) {
  204. return Name.startswith("+") || Name.startswith("-");
  205. }
  206. static bool hasObjCCategory(StringRef Name) {
  207. if (!isObjCClass(Name))
  208. return false;
  209. return Name.find(") ") != StringRef::npos;
  210. }
  211. static void getObjCClassCategory(StringRef In, StringRef &Class,
  212. StringRef &Category) {
  213. if (!hasObjCCategory(In)) {
  214. Class = In.slice(In.find('[') + 1, In.find(' '));
  215. Category = "";
  216. return;
  217. }
  218. Class = In.slice(In.find('[') + 1, In.find('('));
  219. Category = In.slice(In.find('[') + 1, In.find(' '));
  220. return;
  221. }
  222. static StringRef getObjCMethodName(StringRef In) {
  223. return In.slice(In.find(' ') + 1, In.find(']'));
  224. }
  225. // Helper for sorting sections into a stable output order.
  226. static bool SectionSort(const MCSection *A, const MCSection *B) {
  227. std::string LA = (A ? A->getLabelBeginName() : "");
  228. std::string LB = (B ? B->getLabelBeginName() : "");
  229. return LA < LB;
  230. }
  231. // Add the various names to the Dwarf accelerator table names.
  232. // TODO: Determine whether or not we should add names for programs
  233. // that do not have a DW_AT_name or DW_AT_linkage_name field - this
  234. // is only slightly different than the lookup of non-standard ObjC names.
  235. void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
  236. if (!SP.isDefinition())
  237. return;
  238. addAccelName(SP.getName(), Die);
  239. // If the linkage name is different than the name, go ahead and output
  240. // that as well into the name table.
  241. if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
  242. addAccelName(SP.getLinkageName(), Die);
  243. // If this is an Objective-C selector name add it to the ObjC accelerator
  244. // too.
  245. if (isObjCClass(SP.getName())) {
  246. StringRef Class, Category;
  247. getObjCClassCategory(SP.getName(), Class, Category);
  248. addAccelObjC(Class, Die);
  249. if (Category != "")
  250. addAccelObjC(Category, Die);
  251. // Also add the base method name to the name table.
  252. addAccelName(getObjCMethodName(SP.getName()), Die);
  253. }
  254. }
  255. /// isSubprogramContext - Return true if Context is either a subprogram
  256. /// or another context nested inside a subprogram.
  257. bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
  258. if (!Context)
  259. return false;
  260. DIDescriptor D(Context);
  261. if (D.isSubprogram())
  262. return true;
  263. if (D.isType())
  264. return isSubprogramContext(resolve(DIType(Context).getContext()));
  265. return false;
  266. }
  267. // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
  268. // and DW_AT_high_pc attributes. If there are global variables in this
  269. // scope then create and insert DIEs for these variables.
  270. DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
  271. DISubprogram SP) {
  272. DIE *SPDie = SPCU.getOrCreateSubprogramDIE(SP);
  273. attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
  274. const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
  275. MachineLocation Location(RI->getFrameRegister(*Asm->MF));
  276. SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
  277. // Add name to the name table, we do this here because we're guaranteed
  278. // to have concrete versions of our DW_TAG_subprogram nodes.
  279. addSubprogramNames(SP, *SPDie);
  280. return *SPDie;
  281. }
  282. /// Check whether we should create a DIE for the given Scope, return true
  283. /// if we don't create a DIE (the corresponding DIE is null).
  284. bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
  285. if (Scope->isAbstractScope())
  286. return false;
  287. // We don't create a DIE if there is no Range.
  288. const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
  289. if (Ranges.empty())
  290. return true;
  291. if (Ranges.size() > 1)
  292. return false;
  293. // We don't create a DIE if we have a single Range and the end label
  294. // is null.
  295. SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
  296. MCSymbol *End = getLabelAfterInsn(RI->second);
  297. return !End;
  298. }
  299. static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
  300. dwarf::Attribute A, const MCSymbol *L,
  301. const MCSymbol *Sec) {
  302. if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
  303. U.addSectionLabel(D, A, L);
  304. else
  305. U.addSectionDelta(D, A, L, Sec);
  306. }
  307. void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
  308. const SmallVectorImpl<InsnRange> &Range) {
  309. // Emit offset in .debug_range as a relocatable label. emitDIE will handle
  310. // emitting it appropriately.
  311. MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
  312. // Under fission, ranges are specified by constant offsets relative to the
  313. // CU's DW_AT_GNU_ranges_base.
  314. if (useSplitDwarf())
  315. TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
  316. DwarfDebugRangeSectionSym);
  317. else
  318. addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
  319. DwarfDebugRangeSectionSym);
  320. RangeSpanList List(RangeSym);
  321. for (const InsnRange &R : Range) {
  322. RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
  323. List.addRange(std::move(Span));
  324. }
  325. // Add the range list to the set of ranges to be emitted.
  326. TheCU.addRangeList(std::move(List));
  327. }
  328. void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
  329. const SmallVectorImpl<InsnRange> &Ranges) {
  330. assert(!Ranges.empty());
  331. if (Ranges.size() == 1)
  332. attachLowHighPC(TheCU, Die, getLabelBeforeInsn(Ranges.front().first),
  333. getLabelAfterInsn(Ranges.front().second));
  334. else
  335. addScopeRangeList(TheCU, Die, Ranges);
  336. }
  337. // Construct new DW_TAG_lexical_block for this scope and attach
  338. // DW_AT_low_pc/DW_AT_high_pc labels.
  339. std::unique_ptr<DIE>
  340. DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
  341. LexicalScope *Scope) {
  342. if (isLexicalScopeDIENull(Scope))
  343. return nullptr;
  344. auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
  345. if (Scope->isAbstractScope())
  346. return ScopeDIE;
  347. attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
  348. return ScopeDIE;
  349. }
  350. // This scope represents inlined body of a function. Construct DIE to
  351. // represent this concrete inlined copy of the function.
  352. std::unique_ptr<DIE>
  353. DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
  354. LexicalScope *Scope) {
  355. assert(Scope->getScopeNode());
  356. DIScope DS(Scope->getScopeNode());
  357. DISubprogram InlinedSP = getDISubprogram(DS);
  358. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  359. // was inlined from another compile unit.
  360. DIE *OriginDIE = AbstractSPDies[InlinedSP];
  361. assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
  362. auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
  363. TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
  364. attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
  365. InlinedSubprogramDIEs.insert(OriginDIE);
  366. // Add the call site information to the DIE.
  367. DILocation DL(Scope->getInlinedAt());
  368. TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
  369. TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
  370. TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
  371. // Add name to the name table, we do this here because we're guaranteed
  372. // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
  373. addSubprogramNames(InlinedSP, *ScopeDIE);
  374. return ScopeDIE;
  375. }
  376. static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
  377. DbgVariable &DV,
  378. const LexicalScope &Scope,
  379. DIE *&ObjectPointer) {
  380. auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
  381. if (DV.isObjectPointer())
  382. ObjectPointer = Var.get();
  383. return Var;
  384. }
  385. DIE *DwarfDebug::createScopeChildrenDIE(
  386. DwarfCompileUnit &TheCU, LexicalScope *Scope,
  387. SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
  388. DIE *ObjectPointer = nullptr;
  389. // Collect arguments for current function.
  390. if (LScopes.isCurrentFunctionScope(Scope)) {
  391. for (DbgVariable *ArgDV : CurrentFnArguments)
  392. if (ArgDV)
  393. Children.push_back(
  394. constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
  395. // If this is a variadic function, add an unspecified parameter.
  396. DISubprogram SP(Scope->getScopeNode());
  397. DITypeArray FnArgs = SP.getType().getTypeArray();
  398. // If we have a single element of null, it is a function that returns void.
  399. // If we have more than one elements and the last one is null, it is a
  400. // variadic function.
  401. if (FnArgs.getNumElements() > 1 &&
  402. !FnArgs.getElement(FnArgs.getNumElements() - 1))
  403. Children.push_back(
  404. make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
  405. }
  406. // Collect lexical scope children first.
  407. for (DbgVariable *DV : ScopeVariables.lookup(Scope))
  408. Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
  409. for (LexicalScope *LS : Scope->getChildren())
  410. if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
  411. Children.push_back(std::move(Nested));
  412. return ObjectPointer;
  413. }
  414. void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
  415. LexicalScope *Scope, DIE &ScopeDIE) {
  416. // We create children when the scope DIE is not null.
  417. SmallVector<std::unique_ptr<DIE>, 8> Children;
  418. if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
  419. TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
  420. // Add children
  421. for (auto &I : Children)
  422. ScopeDIE.addChild(std::move(I));
  423. }
  424. void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
  425. LexicalScope *Scope) {
  426. assert(Scope && Scope->getScopeNode());
  427. assert(Scope->isAbstractScope());
  428. assert(!Scope->getInlinedAt());
  429. DISubprogram SP(Scope->getScopeNode());
  430. ProcessedSPNodes.insert(SP);
  431. DIE *&AbsDef = AbstractSPDies[SP];
  432. if (AbsDef)
  433. return;
  434. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  435. // was inlined from another compile unit.
  436. DwarfCompileUnit &SPCU = *SPMap[SP];
  437. DIE *ContextDIE;
  438. // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
  439. // the important distinction that the DIDescriptor is not associated with the
  440. // DIE (since the DIDescriptor will be associated with the concrete DIE, if
  441. // any). It could be refactored to some common utility function.
  442. if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
  443. ContextDIE = &SPCU.getUnitDie();
  444. SPCU.getOrCreateSubprogramDIE(SPDecl);
  445. } else
  446. ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
  447. // Passing null as the associated DIDescriptor because the abstract definition
  448. // shouldn't be found by lookup.
  449. AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
  450. DIDescriptor());
  451. SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
  452. SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
  453. createAndAddScopeChildren(SPCU, Scope, *AbsDef);
  454. }
  455. DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
  456. LexicalScope *Scope) {
  457. assert(Scope && Scope->getScopeNode());
  458. assert(!Scope->getInlinedAt());
  459. assert(!Scope->isAbstractScope());
  460. DISubprogram Sub(Scope->getScopeNode());
  461. assert(Sub.isSubprogram());
  462. ProcessedSPNodes.insert(Sub);
  463. DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
  464. createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
  465. return ScopeDIE;
  466. }
  467. // Construct a DIE for this scope.
  468. std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
  469. LexicalScope *Scope) {
  470. if (!Scope || !Scope->getScopeNode())
  471. return nullptr;
  472. DIScope DS(Scope->getScopeNode());
  473. assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
  474. "Only handle inlined subprograms here, use "
  475. "constructSubprogramScopeDIE for non-inlined "
  476. "subprograms");
  477. SmallVector<std::unique_ptr<DIE>, 8> Children;
  478. // We try to create the scope DIE first, then the children DIEs. This will
  479. // avoid creating un-used children then removing them later when we find out
  480. // the scope DIE is null.
  481. std::unique_ptr<DIE> ScopeDIE;
  482. if (Scope->getParent() && DS.isSubprogram()) {
  483. ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
  484. if (!ScopeDIE)
  485. return nullptr;
  486. // We create children when the scope DIE is not null.
  487. createScopeChildrenDIE(TheCU, Scope, Children);
  488. } else {
  489. // Early exit when we know the scope DIE is going to be null.
  490. if (isLexicalScopeDIENull(Scope))
  491. return nullptr;
  492. // We create children here when we know the scope DIE is not going to be
  493. // null and the children will be added to the scope DIE.
  494. createScopeChildrenDIE(TheCU, Scope, Children);
  495. // There is no need to emit empty lexical block DIE.
  496. std::pair<ImportedEntityMap::const_iterator,
  497. ImportedEntityMap::const_iterator> Range =
  498. std::equal_range(ScopesWithImportedEntities.begin(),
  499. ScopesWithImportedEntities.end(),
  500. std::pair<const MDNode *, const MDNode *>(DS, nullptr),
  501. less_first());
  502. if (Children.empty() && Range.first == Range.second)
  503. return nullptr;
  504. ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
  505. assert(ScopeDIE && "Scope DIE should not be null.");
  506. for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
  507. ++i)
  508. constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
  509. }
  510. // Add children
  511. for (auto &I : Children)
  512. ScopeDIE->addChild(std::move(I));
  513. return ScopeDIE;
  514. }
  515. void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
  516. if (!GenerateGnuPubSections)
  517. return;
  518. U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
  519. }
  520. // Create new DwarfCompileUnit for the given metadata node with tag
  521. // DW_TAG_compile_unit.
  522. DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
  523. StringRef FN = DIUnit.getFilename();
  524. CompilationDir = DIUnit.getDirectory();
  525. auto OwnedUnit = make_unique<DwarfCompileUnit>(
  526. InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
  527. DwarfCompileUnit &NewCU = *OwnedUnit;
  528. DIE &Die = NewCU.getUnitDie();
  529. InfoHolder.addUnit(std::move(OwnedUnit));
  530. // LTO with assembly output shares a single line table amongst multiple CUs.
  531. // To avoid the compilation directory being ambiguous, let the line table
  532. // explicitly describe the directory of all files, never relying on the
  533. // compilation directory.
  534. if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
  535. Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
  536. NewCU.getUniqueID(), CompilationDir);
  537. NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
  538. NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  539. DIUnit.getLanguage());
  540. NewCU.addString(Die, dwarf::DW_AT_name, FN);
  541. if (!useSplitDwarf()) {
  542. NewCU.initStmtList(DwarfLineSectionSym);
  543. // If we're using split dwarf the compilation dir is going to be in the
  544. // skeleton CU and so we don't need to duplicate it here.
  545. if (!CompilationDir.empty())
  546. NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  547. addGnuPubAttributes(NewCU, Die);
  548. }
  549. if (DIUnit.isOptimized())
  550. NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
  551. StringRef Flags = DIUnit.getFlags();
  552. if (!Flags.empty())
  553. NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  554. if (unsigned RVer = DIUnit.getRunTimeVersion())
  555. NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
  556. dwarf::DW_FORM_data1, RVer);
  557. if (!FirstCU)
  558. FirstCU = &NewCU;
  559. if (useSplitDwarf()) {
  560. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
  561. DwarfInfoDWOSectionSym);
  562. NewCU.setSkeleton(constructSkeletonCU(NewCU));
  563. } else
  564. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
  565. DwarfInfoSectionSym);
  566. CUMap.insert(std::make_pair(DIUnit, &NewCU));
  567. CUDieMap.insert(std::make_pair(&Die, &NewCU));
  568. return NewCU;
  569. }
  570. void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
  571. const MDNode *N) {
  572. DIImportedEntity Module(N);
  573. assert(Module.Verify());
  574. if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
  575. constructImportedEntityDIE(TheCU, Module, *D);
  576. }
  577. void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
  578. const MDNode *N, DIE &Context) {
  579. DIImportedEntity Module(N);
  580. assert(Module.Verify());
  581. return constructImportedEntityDIE(TheCU, Module, Context);
  582. }
  583. void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
  584. const DIImportedEntity &Module,
  585. DIE &Context) {
  586. assert(Module.Verify() &&
  587. "Use one of the MDNode * overloads to handle invalid metadata");
  588. DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
  589. DIE *EntityDie;
  590. DIDescriptor Entity = resolve(Module.getEntity());
  591. if (Entity.isNameSpace())
  592. EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
  593. else if (Entity.isSubprogram())
  594. EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
  595. else if (Entity.isType())
  596. EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
  597. else
  598. EntityDie = TheCU.getDIE(Entity);
  599. TheCU.addSourceLine(IMDie, Module.getLineNumber(),
  600. Module.getContext().getFilename(),
  601. Module.getContext().getDirectory());
  602. TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
  603. StringRef Name = Module.getName();
  604. if (!Name.empty())
  605. TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
  606. }
  607. // Emit all Dwarf sections that should come prior to the content. Create
  608. // global DIEs and emit initial debug info sections. This is invoked by
  609. // the target AsmPrinter.
  610. void DwarfDebug::beginModule() {
  611. if (DisableDebugInfoPrinting)
  612. return;
  613. const Module *M = MMI->getModule();
  614. FunctionDIs = makeSubprogramMap(*M);
  615. // If module has named metadata anchors then use them, otherwise scan the
  616. // module using debug info finder to collect debug info.
  617. NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
  618. if (!CU_Nodes)
  619. return;
  620. TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
  621. // Emit initial sections so we can reference labels later.
  622. emitSectionLabels();
  623. SingleCU = CU_Nodes->getNumOperands() == 1;
  624. for (MDNode *N : CU_Nodes->operands()) {
  625. DICompileUnit CUNode(N);
  626. DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
  627. DIArray ImportedEntities = CUNode.getImportedEntities();
  628. for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
  629. ScopesWithImportedEntities.push_back(std::make_pair(
  630. DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
  631. ImportedEntities.getElement(i)));
  632. std::sort(ScopesWithImportedEntities.begin(),
  633. ScopesWithImportedEntities.end(), less_first());
  634. DIArray GVs = CUNode.getGlobalVariables();
  635. for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
  636. CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
  637. DIArray SPs = CUNode.getSubprograms();
  638. for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
  639. SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
  640. DIArray EnumTypes = CUNode.getEnumTypes();
  641. for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
  642. DIType Ty(EnumTypes.getElement(i));
  643. // The enum types array by design contains pointers to
  644. // MDNodes rather than DIRefs. Unique them here.
  645. DIType UniqueTy(resolve(Ty.getRef()));
  646. CU.getOrCreateTypeDIE(UniqueTy);
  647. }
  648. DIArray RetainedTypes = CUNode.getRetainedTypes();
  649. for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
  650. DIType Ty(RetainedTypes.getElement(i));
  651. // The retained types array by design contains pointers to
  652. // MDNodes rather than DIRefs. Unique them here.
  653. DIType UniqueTy(resolve(Ty.getRef()));
  654. CU.getOrCreateTypeDIE(UniqueTy);
  655. }
  656. // Emit imported_modules last so that the relevant context is already
  657. // available.
  658. for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
  659. constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
  660. }
  661. // Tell MMI that we have debug info.
  662. MMI->setDebugInfoAvailability(true);
  663. // Prime section data.
  664. SectionMap[Asm->getObjFileLowering().getTextSection()];
  665. }
  666. void DwarfDebug::finishVariableDefinitions() {
  667. for (const auto &Var : ConcreteVariables) {
  668. DIE *VariableDie = Var->getDIE();
  669. assert(VariableDie);
  670. // FIXME: Consider the time-space tradeoff of just storing the unit pointer
  671. // in the ConcreteVariables list, rather than looking it up again here.
  672. // DIE::getUnit isn't simple - it walks parent pointers, etc.
  673. DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
  674. assert(Unit);
  675. DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
  676. if (AbsVar && AbsVar->getDIE()) {
  677. Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
  678. *AbsVar->getDIE());
  679. } else
  680. Unit->applyVariableAttributes(*Var, *VariableDie);
  681. }
  682. }
  683. void DwarfDebug::finishSubprogramDefinitions() {
  684. const Module *M = MMI->getModule();
  685. NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
  686. for (MDNode *N : CU_Nodes->operands()) {
  687. DICompileUnit TheCU(N);
  688. // Construct subprogram DIE and add variables DIEs.
  689. DwarfCompileUnit *SPCU =
  690. static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
  691. DIArray Subprograms = TheCU.getSubprograms();
  692. for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
  693. DISubprogram SP(Subprograms.getElement(i));
  694. // Perhaps the subprogram is in another CU (such as due to comdat
  695. // folding, etc), in which case ignore it here.
  696. if (SPMap[SP] != SPCU)
  697. continue;
  698. DIE *D = SPCU->getDIE(SP);
  699. if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
  700. if (D)
  701. // If this subprogram has an abstract definition, reference that
  702. SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
  703. } else {
  704. if (!D)
  705. // Lazily construct the subprogram if we didn't see either concrete or
  706. // inlined versions during codegen.
  707. D = SPCU->getOrCreateSubprogramDIE(SP);
  708. // And attach the attributes
  709. SPCU->applySubprogramAttributesToDefinition(SP, *D);
  710. }
  711. }
  712. }
  713. }
  714. // Collect info for variables that were optimized out.
  715. void DwarfDebug::collectDeadVariables() {
  716. const Module *M = MMI->getModule();
  717. if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
  718. for (MDNode *N : CU_Nodes->operands()) {
  719. DICompileUnit TheCU(N);
  720. // Construct subprogram DIE and add variables DIEs.
  721. DwarfCompileUnit *SPCU =
  722. static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
  723. assert(SPCU && "Unable to find Compile Unit!");
  724. DIArray Subprograms = TheCU.getSubprograms();
  725. for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
  726. DISubprogram SP(Subprograms.getElement(i));
  727. if (ProcessedSPNodes.count(SP) != 0)
  728. continue;
  729. assert(SP.isSubprogram() &&
  730. "CU's subprogram list contains a non-subprogram");
  731. assert(SP.isDefinition() &&
  732. "CU's subprogram list contains a subprogram declaration");
  733. DIArray Variables = SP.getVariables();
  734. if (Variables.getNumElements() == 0)
  735. continue;
  736. DIE *SPDIE = AbstractSPDies.lookup(SP);
  737. if (!SPDIE)
  738. SPDIE = SPCU->getDIE(SP);
  739. assert(SPDIE);
  740. for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
  741. DIVariable DV(Variables.getElement(vi));
  742. assert(DV.isVariable());
  743. DbgVariable NewVar(DV, this);
  744. auto VariableDie = SPCU->constructVariableDIE(NewVar);
  745. SPCU->applyVariableAttributes(NewVar, *VariableDie);
  746. SPDIE->addChild(std::move(VariableDie));
  747. }
  748. }
  749. }
  750. }
  751. }
  752. void DwarfDebug::finalizeModuleInfo() {
  753. finishSubprogramDefinitions();
  754. finishVariableDefinitions();
  755. // Collect info for variables that were optimized out.
  756. collectDeadVariables();
  757. // Handle anything that needs to be done on a per-unit basis after
  758. // all other generation.
  759. for (const auto &TheU : getUnits()) {
  760. // Emit DW_AT_containing_type attribute to connect types with their
  761. // vtable holding type.
  762. TheU->constructContainingTypeDIEs();
  763. // Add CU specific attributes if we need to add any.
  764. if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
  765. // If we're splitting the dwarf out now that we've got the entire
  766. // CU then add the dwo id to it.
  767. DwarfCompileUnit *SkCU =
  768. static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
  769. if (useSplitDwarf()) {
  770. // Emit a unique identifier for this CU.
  771. uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
  772. TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  773. dwarf::DW_FORM_data8, ID);
  774. SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  775. dwarf::DW_FORM_data8, ID);
  776. // We don't keep track of which addresses are used in which CU so this
  777. // is a bit pessimistic under LTO.
  778. if (!AddrPool.isEmpty())
  779. addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
  780. dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
  781. DwarfAddrSectionSym);
  782. if (!TheU->getRangeLists().empty())
  783. addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
  784. dwarf::DW_AT_GNU_ranges_base,
  785. DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
  786. }
  787. // If we have code split among multiple sections or non-contiguous
  788. // ranges of code then emit a DW_AT_ranges attribute on the unit that will
  789. // remain in the .o file, otherwise add a DW_AT_low_pc.
  790. // FIXME: We should use ranges allow reordering of code ala
  791. // .subsections_via_symbols in mach-o. This would mean turning on
  792. // ranges for all subprogram DIEs for mach-o.
  793. DwarfCompileUnit &U =
  794. SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
  795. unsigned NumRanges = TheU->getRanges().size();
  796. if (NumRanges) {
  797. if (NumRanges > 1) {
  798. addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
  799. Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
  800. DwarfDebugRangeSectionSym);
  801. // A DW_AT_low_pc attribute may also be specified in combination with
  802. // DW_AT_ranges to specify the default base address for use in
  803. // location lists (see Section 2.6.2) and range lists (see Section
  804. // 2.17.3).
  805. U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
  806. 0);
  807. } else {
  808. RangeSpan &Range = TheU->getRanges().back();
  809. U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
  810. Range.getStart());
  811. U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
  812. Range.getStart());
  813. }
  814. }
  815. }
  816. }
  817. // Compute DIE offsets and sizes.
  818. InfoHolder.computeSizeAndOffsets();
  819. if (useSplitDwarf())
  820. SkeletonHolder.computeSizeAndOffsets();
  821. }
  822. void DwarfDebug::endSections() {
  823. // Filter labels by section.
  824. for (const SymbolCU &SCU : ArangeLabels) {
  825. if (SCU.Sym->isInSection()) {
  826. // Make a note of this symbol and it's section.
  827. const MCSection *Section = &SCU.Sym->getSection();
  828. if (!Section->getKind().isMetadata())
  829. SectionMap[Section].push_back(SCU);
  830. } else {
  831. // Some symbols (e.g. common/bss on mach-o) can have no section but still
  832. // appear in the output. This sucks as we rely on sections to build
  833. // arange spans. We can do it without, but it's icky.
  834. SectionMap[nullptr].push_back(SCU);
  835. }
  836. }
  837. // Build a list of sections used.
  838. std::vector<const MCSection *> Sections;
  839. for (const auto &it : SectionMap) {
  840. const MCSection *Section = it.first;
  841. Sections.push_back(Section);
  842. }
  843. // Sort the sections into order.
  844. // This is only done to ensure consistent output order across different runs.
  845. std::sort(Sections.begin(), Sections.end(), SectionSort);
  846. // Add terminating symbols for each section.
  847. for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
  848. const MCSection *Section = Sections[ID];
  849. MCSymbol *Sym = nullptr;
  850. if (Section) {
  851. // We can't call MCSection::getLabelEndName, as it's only safe to do so
  852. // if we know the section name up-front. For user-created sections, the
  853. // resulting label may not be valid to use as a label. (section names can
  854. // use a greater set of characters on some systems)
  855. Sym = Asm->GetTempSymbol("debug_end", ID);
  856. Asm->OutStreamer.SwitchSection(Section);
  857. Asm->OutStreamer.EmitLabel(Sym);
  858. }
  859. // Insert a final terminator.
  860. SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
  861. }
  862. }
  863. // Emit all Dwarf sections that should come after the content.
  864. void DwarfDebug::endModule() {
  865. assert(CurFn == nullptr);
  866. assert(CurMI == nullptr);
  867. if (!FirstCU)
  868. return;
  869. // End any existing sections.
  870. // TODO: Does this need to happen?
  871. endSections();
  872. // Finalize the debug info for the module.
  873. finalizeModuleInfo();
  874. emitDebugStr();
  875. // Emit all the DIEs into a debug info section.
  876. emitDebugInfo();
  877. // Corresponding abbreviations into a abbrev section.
  878. emitAbbreviations();
  879. // Emit info into a debug aranges section.
  880. if (GenerateARangeSection)
  881. emitDebugARanges();
  882. // Emit info into a debug ranges section.
  883. emitDebugRanges();
  884. if (useSplitDwarf()) {
  885. emitDebugStrDWO();
  886. emitDebugInfoDWO();
  887. emitDebugAbbrevDWO();
  888. emitDebugLineDWO();
  889. emitDebugLocDWO();
  890. // Emit DWO addresses.
  891. AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
  892. } else
  893. // Emit info into a debug loc section.
  894. emitDebugLoc();
  895. // Emit info into the dwarf accelerator table sections.
  896. if (useDwarfAccelTables()) {
  897. emitAccelNames();
  898. emitAccelObjC();
  899. emitAccelNamespaces();
  900. emitAccelTypes();
  901. }
  902. // Emit the pubnames and pubtypes sections if requested.
  903. if (HasDwarfPubSections) {
  904. emitDebugPubNames(GenerateGnuPubSections);
  905. emitDebugPubTypes(GenerateGnuPubSections);
  906. }
  907. // clean up.
  908. SPMap.clear();
  909. AbstractVariables.clear();
  910. // Reset these for the next Module if we have one.
  911. FirstCU = nullptr;
  912. }
  913. // Find abstract variable, if any, associated with Var.
  914. DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
  915. DIVariable &Cleansed) {
  916. LLVMContext &Ctx = DV->getContext();
  917. // More then one inlined variable corresponds to one abstract variable.
  918. // FIXME: This duplication of variables when inlining should probably be
  919. // removed. It's done to allow each DIVariable to describe its location
  920. // because the DebugLoc on the dbg.value/declare isn't accurate. We should
  921. // make it accurate then remove this duplication/cleansing stuff.
  922. Cleansed = cleanseInlinedVariable(DV, Ctx);
  923. auto I = AbstractVariables.find(Cleansed);
  924. if (I != AbstractVariables.end())
  925. return I->second.get();
  926. return nullptr;
  927. }
  928. DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
  929. DIVariable Cleansed;
  930. return getExistingAbstractVariable(DV, Cleansed);
  931. }
  932. void DwarfDebug::createAbstractVariable(const DIVariable &Var,
  933. LexicalScope *Scope) {
  934. auto AbsDbgVariable = make_unique<DbgVariable>(Var, this);
  935. addScopeVariable(Scope, AbsDbgVariable.get());
  936. AbstractVariables[Var] = std::move(AbsDbgVariable);
  937. }
  938. void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
  939. const MDNode *ScopeNode) {
  940. DIVariable Cleansed = DV;
  941. if (getExistingAbstractVariable(DV, Cleansed))
  942. return;
  943. createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
  944. }
  945. void
  946. DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
  947. const MDNode *ScopeNode) {
  948. DIVariable Cleansed = DV;
  949. if (getExistingAbstractVariable(DV, Cleansed))
  950. return;
  951. if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
  952. createAbstractVariable(Cleansed, Scope);
  953. }
  954. // If Var is a current function argument then add it to CurrentFnArguments list.
  955. bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
  956. if (!LScopes.isCurrentFunctionScope(Scope))
  957. return false;
  958. DIVariable DV = Var->getVariable();
  959. if (DV.getTag() != dwarf::DW_TAG_arg_variable)
  960. return false;
  961. unsigned ArgNo = DV.getArgNumber();
  962. if (ArgNo == 0)
  963. return false;
  964. size_t Size = CurrentFnArguments.size();
  965. if (Size == 0)
  966. CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
  967. // llvm::Function argument size is not good indicator of how many
  968. // arguments does the function have at source level.
  969. if (ArgNo > Size)
  970. CurrentFnArguments.resize(ArgNo * 2);
  971. assert(!CurrentFnArguments[ArgNo - 1]);
  972. CurrentFnArguments[ArgNo - 1] = Var;
  973. return true;
  974. }
  975. // Collect variable information from side table maintained by MMI.
  976. void DwarfDebug::collectVariableInfoFromMMITable(
  977. SmallPtrSetImpl<const MDNode *> &Processed) {
  978. for (const auto &VI : MMI->getVariableDbgInfo()) {
  979. if (!VI.Var)
  980. continue;
  981. Processed.insert(VI.Var);
  982. DIVariable DV(VI.Var);
  983. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  984. // If variable scope is not found then skip this variable.
  985. if (!Scope)
  986. continue;
  987. ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
  988. ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
  989. DbgVariable *RegVar = ConcreteVariables.back().get();
  990. RegVar->setFrameIndex(VI.Slot);
  991. addScopeVariable(Scope, RegVar);
  992. }
  993. }
  994. // Get .debug_loc entry for the instruction range starting at MI.
  995. static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
  996. const MDNode *Var = MI->getDebugVariable();
  997. assert(MI->getNumOperands() == 3);
  998. if (MI->getOperand(0).isReg()) {
  999. MachineLocation MLoc;
  1000. // If the second operand is an immediate, this is a
  1001. // register-indirect address.
  1002. if (!MI->getOperand(1).isImm())
  1003. MLoc.set(MI->getOperand(0).getReg());
  1004. else
  1005. MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
  1006. return DebugLocEntry::Value(Var, MLoc);
  1007. }
  1008. if (MI->getOperand(0).isImm())
  1009. return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
  1010. if (MI->getOperand(0).isFPImm())
  1011. return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
  1012. if (MI->getOperand(0).isCImm())
  1013. return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
  1014. llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
  1015. }
  1016. /// Determine whether two variable pieces overlap.
  1017. static bool piecesOverlap(DIVariable P1, DIVariable P2) {
  1018. if (!P1.isVariablePiece() || !P2.isVariablePiece())
  1019. return true;
  1020. unsigned l1 = P1.getPieceOffset();
  1021. unsigned l2 = P2.getPieceOffset();
  1022. unsigned r1 = l1 + P1.getPieceSize();
  1023. unsigned r2 = l2 + P2.getPieceSize();
  1024. // True where [l1,r1[ and [r1,r2[ overlap.
  1025. return (l1 < r2) && (l2 < r1);
  1026. }
  1027. /// Build the location list for all DBG_VALUEs in the function that
  1028. /// describe the same variable. If the ranges of several independent
  1029. /// pieces of the same variable overlap partially, split them up and
  1030. /// combine the ranges. The resulting DebugLocEntries are will have
  1031. /// strict monotonically increasing begin addresses and will never
  1032. /// overlap.
  1033. //
  1034. // Input:
  1035. //
  1036. // Ranges History [var, loc, piece ofs size]
  1037. // 0 | [x, (reg0, piece 0, 32)]
  1038. // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
  1039. // 2 | | ...
  1040. // 3 | [clobber reg0]
  1041. // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
  1042. //
  1043. // Output:
  1044. //
  1045. // [0-1] [x, (reg0, piece 0, 32)]
  1046. // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
  1047. // [3-4] [x, (reg1, piece 32, 32)]
  1048. // [4- ] [x, (mem, piece 0, 64)]
  1049. void
  1050. DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  1051. const DbgValueHistoryMap::InstrRanges &Ranges) {
  1052. SmallVector<DebugLocEntry::Value, 4> OpenRanges;
  1053. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  1054. const MachineInstr *Begin = I->first;
  1055. const MachineInstr *End = I->second;
  1056. assert(Begin->isDebugValue() && "Invalid History entry");
  1057. // Check if a variable is inaccessible in this range.
  1058. if (Begin->getNumOperands() > 1 &&
  1059. Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
  1060. OpenRanges.clear();
  1061. continue;
  1062. }
  1063. // If this piece overlaps with any open ranges, truncate them.
  1064. DIVariable DIVar = Begin->getDebugVariable();
  1065. auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
  1066. [&](DebugLocEntry::Value R) {
  1067. return piecesOverlap(DIVar, R.getVariable());
  1068. });
  1069. OpenRanges.erase(Last, OpenRanges.end());
  1070. const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
  1071. assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
  1072. const MCSymbol *EndLabel;
  1073. if (End != nullptr)
  1074. EndLabel = getLabelAfterInsn(End);
  1075. else if (std::next(I) == Ranges.end())
  1076. EndLabel = FunctionEndSym;
  1077. else
  1078. EndLabel = getLabelBeforeInsn(std::next(I)->first);
  1079. assert(EndLabel && "Forgot label after instruction ending a range!");
  1080. DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
  1081. auto Value = getDebugLocValue(Begin);
  1082. DebugLocEntry Loc(StartLabel, EndLabel, Value);
  1083. bool couldMerge = false;
  1084. // If this is a piece, it may belong to the current DebugLocEntry.
  1085. if (DIVar.isVariablePiece()) {
  1086. // Add this value to the list of open ranges.
  1087. OpenRanges.push_back(Value);
  1088. // Attempt to add the piece to the last entry.
  1089. if (!DebugLoc.empty())
  1090. if (DebugLoc.back().MergeValues(Loc))
  1091. couldMerge = true;
  1092. }
  1093. if (!couldMerge) {
  1094. // Need to add a new DebugLocEntry. Add all values from still
  1095. // valid non-overlapping pieces.
  1096. if (OpenRanges.size())
  1097. Loc.addValues(OpenRanges);
  1098. DebugLoc.push_back(std::move(Loc));
  1099. }
  1100. // Attempt to coalesce the ranges of two otherwise identical
  1101. // DebugLocEntries.
  1102. auto CurEntry = DebugLoc.rbegin();
  1103. auto PrevEntry = std::next(CurEntry);
  1104. if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
  1105. DebugLoc.pop_back();
  1106. DEBUG(dbgs() << "Values:\n";
  1107. for (auto Value : CurEntry->getValues())
  1108. Value.getVariable()->dump();
  1109. dbgs() << "-----\n");
  1110. }
  1111. }
  1112. // Find variables for each lexical scope.
  1113. void
  1114. DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
  1115. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1116. DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
  1117. // Grab the variable info that was squirreled away in the MMI side-table.
  1118. collectVariableInfoFromMMITable(Processed);
  1119. for (const auto &I : DbgValues) {
  1120. DIVariable DV(I.first);
  1121. if (Processed.count(DV))
  1122. continue;
  1123. // Instruction ranges, specifying where DV is accessible.
  1124. const auto &Ranges = I.second;
  1125. if (Ranges.empty())
  1126. continue;
  1127. LexicalScope *Scope = nullptr;
  1128. if (MDNode *IA = DV.getInlinedAt()) {
  1129. DebugLoc DL = DebugLoc::getFromDILocation(IA);
  1130. Scope = LScopes.findInlinedScope(DebugLoc::get(
  1131. DL.getLine(), DL.getCol(), DV.getContext(), IA));
  1132. } else
  1133. Scope = LScopes.findLexicalScope(DV.getContext());
  1134. // If variable scope is not found then skip this variable.
  1135. if (!Scope)
  1136. continue;
  1137. Processed.insert(getEntireVariable(DV));
  1138. const MachineInstr *MInsn = Ranges.front().first;
  1139. assert(MInsn->isDebugValue() && "History must begin with debug value");
  1140. ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
  1141. ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
  1142. DbgVariable *RegVar = ConcreteVariables.back().get();
  1143. addScopeVariable(Scope, RegVar);
  1144. // Check if the first DBG_VALUE is valid for the rest of the function.
  1145. if (Ranges.size() == 1 && Ranges.front().second == nullptr)
  1146. continue;
  1147. // Handle multiple DBG_VALUE instructions describing one variable.
  1148. RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
  1149. DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
  1150. DebugLocList &LocList = DotDebugLocEntries.back();
  1151. LocList.CU = TheCU;
  1152. LocList.Label =
  1153. Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
  1154. // Build the location list for this variable.
  1155. buildLocationList(LocList.List, Ranges);
  1156. }
  1157. // Collect info for variables that were optimized out.
  1158. DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
  1159. for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
  1160. DIVariable DV(Variables.getElement(i));
  1161. assert(DV.isVariable());
  1162. if (!Processed.insert(DV))
  1163. continue;
  1164. if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
  1165. ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
  1166. ConcreteVariables.push_back(make_unique<DbgVariable>(DV, this));
  1167. addScopeVariable(Scope, ConcreteVariables.back().get());
  1168. }
  1169. }
  1170. }
  1171. // Return Label preceding the instruction.
  1172. MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
  1173. MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
  1174. assert(Label && "Didn't insert label before instruction");
  1175. return Label;
  1176. }
  1177. // Return Label immediately following the instruction.
  1178. MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
  1179. return LabelsAfterInsn.lookup(MI);
  1180. }
  1181. // Process beginning of an instruction.
  1182. void DwarfDebug::beginInstruction(const MachineInstr *MI) {
  1183. assert(CurMI == nullptr);
  1184. CurMI = MI;
  1185. // Check if source location changes, but ignore DBG_VALUE locations.
  1186. if (!MI->isDebugValue()) {
  1187. DebugLoc DL = MI->getDebugLoc();
  1188. if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
  1189. unsigned Flags = 0;
  1190. PrevInstLoc = DL;
  1191. if (DL == PrologEndLoc) {
  1192. Flags |= DWARF2_FLAG_PROLOGUE_END;
  1193. PrologEndLoc = DebugLoc();
  1194. }
  1195. if (PrologEndLoc.isUnknown())
  1196. Flags |= DWARF2_FLAG_IS_STMT;
  1197. if (!DL.isUnknown()) {
  1198. const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
  1199. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  1200. } else
  1201. recordSourceLine(0, 0, nullptr, 0);
  1202. }
  1203. }
  1204. // Insert labels where requested.
  1205. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  1206. LabelsBeforeInsn.find(MI);
  1207. // No label needed.
  1208. if (I == LabelsBeforeInsn.end())
  1209. return;
  1210. // Label already assigned.
  1211. if (I->second)
  1212. return;
  1213. if (!PrevLabel) {
  1214. PrevLabel = MMI->getContext().CreateTempSymbol();
  1215. Asm->OutStreamer.EmitLabel(PrevLabel);
  1216. }
  1217. I->second = PrevLabel;
  1218. }
  1219. // Process end of an instruction.
  1220. void DwarfDebug::endInstruction() {
  1221. assert(CurMI != nullptr);
  1222. // Don't create a new label after DBG_VALUE instructions.
  1223. // They don't generate code.
  1224. if (!CurMI->isDebugValue())
  1225. PrevLabel = nullptr;
  1226. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  1227. LabelsAfterInsn.find(CurMI);
  1228. CurMI = nullptr;
  1229. // No label needed.
  1230. if (I == LabelsAfterInsn.end())
  1231. return;
  1232. // Label already assigned.
  1233. if (I->second)
  1234. return;
  1235. // We need a label after this instruction.
  1236. if (!PrevLabel) {
  1237. PrevLabel = MMI->getContext().CreateTempSymbol();
  1238. Asm->OutStreamer.EmitLabel(PrevLabel);
  1239. }
  1240. I->second = PrevLabel;
  1241. }
  1242. // Each LexicalScope has first instruction and last instruction to mark
  1243. // beginning and end of a scope respectively. Create an inverse map that list
  1244. // scopes starts (and ends) with an instruction. One instruction may start (or
  1245. // end) multiple scopes. Ignore scopes that are not reachable.
  1246. void DwarfDebug::identifyScopeMarkers() {
  1247. SmallVector<LexicalScope *, 4> WorkList;
  1248. WorkList.push_back(LScopes.getCurrentFunctionScope());
  1249. while (!WorkList.empty()) {
  1250. LexicalScope *S = WorkList.pop_back_val();
  1251. const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
  1252. if (!Children.empty())
  1253. WorkList.append(Children.begin(), Children.end());
  1254. if (S->isAbstractScope())
  1255. continue;
  1256. for (const InsnRange &R : S->getRanges()) {
  1257. assert(R.first && "InsnRange does not have first instruction!");
  1258. assert(R.second && "InsnRange does not have second instruction!");
  1259. requestLabelBeforeInsn(R.first);
  1260. requestLabelAfterInsn(R.second);
  1261. }
  1262. }
  1263. }
  1264. static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
  1265. // First known non-DBG_VALUE and non-frame setup location marks
  1266. // the beginning of the function body.
  1267. for (const auto &MBB : *MF)
  1268. for (const auto &MI : MBB)
  1269. if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1270. !MI.getDebugLoc().isUnknown())
  1271. return MI.getDebugLoc();
  1272. return DebugLoc();
  1273. }
  1274. // Gather pre-function debug information. Assumes being called immediately
  1275. // after the function entry point has been emitted.
  1276. void DwarfDebug::beginFunction(const MachineFunction *MF) {
  1277. CurFn = MF;
  1278. // If there's no debug info for the function we're not going to do anything.
  1279. if (!MMI->hasDebugInfo())
  1280. return;
  1281. auto DI = FunctionDIs.find(MF->getFunction());
  1282. if (DI == FunctionDIs.end())
  1283. return;
  1284. // Grab the lexical scopes for the function, if we don't have any of those
  1285. // then we're not going to be able to do anything.
  1286. LScopes.initialize(*MF);
  1287. if (LScopes.empty())
  1288. return;
  1289. assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
  1290. // Make sure that each lexical scope will have a begin/end label.
  1291. identifyScopeMarkers();
  1292. // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
  1293. // belongs to so that we add to the correct per-cu line table in the
  1294. // non-asm case.
  1295. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1296. // FnScope->getScopeNode() and DI->second should represent the same function,
  1297. // though they may not be the same MDNode due to inline functions merged in
  1298. // LTO where the debug info metadata still differs (either due to distinct
  1299. // written differences - two versions of a linkonce_odr function
  1300. // written/copied into two separate files, or some sub-optimal metadata that
  1301. // isn't structurally identical (see: file path/name info from clang, which
  1302. // includes the directory of the cpp file being built, even when the file name
  1303. // is absolute (such as an <> lookup header)))
  1304. DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
  1305. assert(TheCU && "Unable to find compile unit!");
  1306. if (Asm->OutStreamer.hasRawTextSupport())
  1307. // Use a single line table if we are generating assembly.
  1308. Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
  1309. else
  1310. Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
  1311. // Emit a label for the function so that we have a beginning address.
  1312. FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
  1313. // Assumes in correct section after the entry point.
  1314. Asm->OutStreamer.EmitLabel(FunctionBeginSym);
  1315. // Calculate history for local variables.
  1316. calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
  1317. DbgValues);
  1318. // Request labels for the full history.
  1319. for (const auto &I : DbgValues) {
  1320. const auto &Ranges = I.second;
  1321. if (Ranges.empty())
  1322. continue;
  1323. // The first mention of a function argument gets the FunctionBeginSym
  1324. // label, so arguments are visible when breaking at function entry.
  1325. DIVariable DV(Ranges.front().first->getDebugVariable());
  1326. if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
  1327. getDISubprogram(DV.getContext()).describes(MF->getFunction())) {
  1328. if (!DV.isVariablePiece())
  1329. LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
  1330. else {
  1331. // Mark all non-overlapping initial pieces.
  1332. for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
  1333. DIVariable Piece = I->first->getDebugVariable();
  1334. if (std::all_of(Ranges.begin(), I,
  1335. [&](DbgValueHistoryMap::InstrRange Pred){
  1336. return !piecesOverlap(Piece, Pred.first->getDebugVariable());
  1337. }))
  1338. LabelsBeforeInsn[I->first] = FunctionBeginSym;
  1339. else
  1340. break;
  1341. }
  1342. }
  1343. }
  1344. for (const auto &Range : Ranges) {
  1345. requestLabelBeforeInsn(Range.first);
  1346. if (Range.second)
  1347. requestLabelAfterInsn(Range.second);
  1348. }
  1349. }
  1350. PrevInstLoc = DebugLoc();
  1351. PrevLabel = FunctionBeginSym;
  1352. // Record beginning of function.
  1353. PrologEndLoc = findPrologueEndLoc(MF);
  1354. if (!PrologEndLoc.isUnknown()) {
  1355. DebugLoc FnStartDL =
  1356. PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
  1357. recordSourceLine(
  1358. FnStartDL.getLine(), FnStartDL.getCol(),
  1359. FnStartDL.getScope(MF->getFunction()->getContext()),
  1360. // We'd like to list the prologue as "not statements" but GDB behaves
  1361. // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
  1362. DWARF2_FLAG_IS_STMT);
  1363. }
  1364. }
  1365. void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
  1366. if (addCurrentFnArgument(Var, LS))
  1367. return;
  1368. SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
  1369. DIVariable DV = Var->getVariable();
  1370. // Variables with positive arg numbers are parameters.
  1371. if (unsigned ArgNum = DV.getArgNumber()) {
  1372. // Keep all parameters in order at the start of the variable list to ensure
  1373. // function types are correct (no out-of-order parameters)
  1374. //
  1375. // This could be improved by only doing it for optimized builds (unoptimized
  1376. // builds have the right order to begin with), searching from the back (this
  1377. // would catch the unoptimized case quickly), or doing a binary search
  1378. // rather than linear search.
  1379. SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
  1380. while (I != Vars.end()) {
  1381. unsigned CurNum = (*I)->getVariable().getArgNumber();
  1382. // A local (non-parameter) variable has been found, insert immediately
  1383. // before it.
  1384. if (CurNum == 0)
  1385. break;
  1386. // A later indexed parameter has been found, insert immediately before it.
  1387. if (CurNum > ArgNum)
  1388. break;
  1389. ++I;
  1390. }
  1391. Vars.insert(I, Var);
  1392. return;
  1393. }
  1394. Vars.push_back(Var);
  1395. }
  1396. // Gather and emit post-function debug information.
  1397. void DwarfDebug::endFunction(const MachineFunction *MF) {
  1398. // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
  1399. // though the beginFunction may not be called at all.
  1400. // We should handle both cases.
  1401. if (!CurFn)
  1402. CurFn = MF;
  1403. else
  1404. assert(CurFn == MF);
  1405. assert(CurFn != nullptr);
  1406. if (!MMI->hasDebugInfo() || LScopes.empty() ||
  1407. !FunctionDIs.count(MF->getFunction())) {
  1408. // If we don't have a lexical scope for this function then there will
  1409. // be a hole in the range information. Keep note of this by setting the
  1410. // previously used section to nullptr.
  1411. PrevSection = nullptr;
  1412. PrevCU = nullptr;
  1413. CurFn = nullptr;
  1414. return;
  1415. }
  1416. // Define end label for subprogram.
  1417. FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
  1418. // Assumes in correct section after the entry point.
  1419. Asm->OutStreamer.EmitLabel(FunctionEndSym);
  1420. // Set DwarfDwarfCompileUnitID in MCContext to default value.
  1421. Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
  1422. SmallPtrSet<const MDNode *, 16> ProcessedVars;
  1423. collectVariableInfo(ProcessedVars);
  1424. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1425. DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
  1426. // Construct abstract scopes.
  1427. for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
  1428. DISubprogram SP(AScope->getScopeNode());
  1429. assert(SP.isSubprogram());
  1430. // Collect info for variables that were optimized out.
  1431. DIArray Variables = SP.getVariables();
  1432. for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
  1433. DIVariable DV(Variables.getElement(i));
  1434. assert(DV && DV.isVariable());
  1435. if (!ProcessedVars.insert(DV))
  1436. continue;
  1437. ensureAbstractVariableIsCreated(DV, DV.getContext());
  1438. }
  1439. constructAbstractSubprogramScopeDIE(TheCU, AScope);
  1440. }
  1441. DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
  1442. if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
  1443. TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
  1444. // Add the range of this function to the list of ranges for the CU.
  1445. RangeSpan Span(FunctionBeginSym, FunctionEndSym);
  1446. TheCU.addRange(std::move(Span));
  1447. PrevSection = Asm->getCurrentSection();
  1448. PrevCU = &TheCU;
  1449. // Clear debug info
  1450. // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
  1451. // DbgVariables except those that are also in AbstractVariables (since they
  1452. // can be used cross-function)
  1453. ScopeVariables.clear();
  1454. CurrentFnArguments.clear();
  1455. DbgValues.clear();
  1456. LabelsBeforeInsn.clear();
  1457. LabelsAfterInsn.clear();
  1458. PrevLabel = nullptr;
  1459. CurFn = nullptr;
  1460. }
  1461. // Register a source line with debug info. Returns the unique label that was
  1462. // emitted and which provides correspondence to the source line list.
  1463. void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
  1464. unsigned Flags) {
  1465. StringRef Fn;
  1466. StringRef Dir;
  1467. unsigned Src = 1;
  1468. unsigned Discriminator = 0;
  1469. if (DIScope Scope = DIScope(S)) {
  1470. assert(Scope.isScope());
  1471. Fn = Scope.getFilename();
  1472. Dir = Scope.getDirectory();
  1473. if (Scope.isLexicalBlock())
  1474. Discriminator = DILexicalBlock(S).getDiscriminator();
  1475. unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
  1476. Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
  1477. .getOrCreateSourceID(Fn, Dir);
  1478. }
  1479. Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
  1480. Discriminator, Fn);
  1481. }
  1482. //===----------------------------------------------------------------------===//
  1483. // Emit Methods
  1484. //===----------------------------------------------------------------------===//
  1485. // Emit initial Dwarf sections with a label at the start of each one.
  1486. void DwarfDebug::emitSectionLabels() {
  1487. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1488. // Dwarf sections base addresses.
  1489. DwarfInfoSectionSym =
  1490. emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
  1491. if (useSplitDwarf()) {
  1492. DwarfInfoDWOSectionSym =
  1493. emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
  1494. DwarfTypesDWOSectionSym =
  1495. emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
  1496. }
  1497. DwarfAbbrevSectionSym =
  1498. emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
  1499. if (useSplitDwarf())
  1500. DwarfAbbrevDWOSectionSym = emitSectionSym(
  1501. Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
  1502. if (GenerateARangeSection)
  1503. emitSectionSym(Asm, TLOF.getDwarfARangesSection());
  1504. DwarfLineSectionSym =
  1505. emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
  1506. if (GenerateGnuPubSections) {
  1507. DwarfGnuPubNamesSectionSym =
  1508. emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
  1509. DwarfGnuPubTypesSectionSym =
  1510. emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
  1511. } else if (HasDwarfPubSections) {
  1512. emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
  1513. emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
  1514. }
  1515. DwarfStrSectionSym =
  1516. emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
  1517. if (useSplitDwarf()) {
  1518. DwarfStrDWOSectionSym =
  1519. emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
  1520. DwarfAddrSectionSym =
  1521. emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
  1522. DwarfDebugLocSectionSym =
  1523. emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
  1524. } else
  1525. DwarfDebugLocSectionSym =
  1526. emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
  1527. DwarfDebugRangeSectionSym =
  1528. emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
  1529. }
  1530. // Recursively emits a debug information entry.
  1531. void DwarfDebug::emitDIE(DIE &Die) {
  1532. // Get the abbreviation for this DIE.
  1533. const DIEAbbrev &Abbrev = Die.getAbbrev();
  1534. // Emit the code (index) for the abbreviation.
  1535. if (Asm->isVerbose())
  1536. Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
  1537. "] 0x" + Twine::utohexstr(Die.getOffset()) +
  1538. ":0x" + Twine::utohexstr(Die.getSize()) + " " +
  1539. dwarf::TagString(Abbrev.getTag()));
  1540. Asm->EmitULEB128(Abbrev.getNumber());
  1541. const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
  1542. const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
  1543. // Emit the DIE attribute values.
  1544. for (unsigned i = 0, N = Values.size(); i < N; ++i) {
  1545. dwarf::Attribute Attr = AbbrevData[i].getAttribute();
  1546. dwarf::Form Form = AbbrevData[i].getForm();
  1547. assert(Form && "Too many attributes for DIE (check abbreviation)");
  1548. if (Asm->isVerbose()) {
  1549. Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
  1550. if (Attr == dwarf::DW_AT_accessibility)
  1551. Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
  1552. cast<DIEInteger>(Values[i])->getValue()));
  1553. }
  1554. // Emit an attribute using the defined form.
  1555. Values[i]->EmitValue(Asm, Form);
  1556. }
  1557. // Emit the DIE children if any.
  1558. if (Abbrev.hasChildren()) {
  1559. for (auto &Child : Die.getChildren())
  1560. emitDIE(*Child);
  1561. Asm->OutStreamer.AddComment("End Of Children Mark");
  1562. Asm->EmitInt8(0);
  1563. }
  1564. }
  1565. // Emit the debug info section.
  1566. void DwarfDebug::emitDebugInfo() {
  1567. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1568. Holder.emitUnits(this, DwarfAbbrevSectionSym);
  1569. }
  1570. // Emit the abbreviation section.
  1571. void DwarfDebug::emitAbbreviations() {
  1572. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1573. Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
  1574. }
  1575. // Emit the last address of the section and the end of the line matrix.
  1576. void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
  1577. // Define last address of section.
  1578. Asm->OutStreamer.AddComment("Extended Op");
  1579. Asm->EmitInt8(0);
  1580. Asm->OutStreamer.AddComment("Op size");
  1581. Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
  1582. Asm->OutStreamer.AddComment("DW_LNE_set_address");
  1583. Asm->EmitInt8(dwarf::DW_LNE_set_address);
  1584. Asm->OutStreamer.AddComment("Section end label");
  1585. Asm->OutStreamer.EmitSymbolValue(
  1586. Asm->GetTempSymbol("section_end", SectionEnd),
  1587. Asm->getDataLayout().getPointerSize());
  1588. // Mark end of matrix.
  1589. Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
  1590. Asm->EmitInt8(0);
  1591. Asm->EmitInt8(1);
  1592. Asm->EmitInt8(1);
  1593. }
  1594. // Emit visible names into a hashed accelerator table section.
  1595. void DwarfDebug::emitAccelNames() {
  1596. AccelNames.FinalizeTable(Asm, "Names");
  1597. Asm->OutStreamer.SwitchSection(
  1598. Asm->getObjFileLowering().getDwarfAccelNamesSection());
  1599. MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
  1600. Asm->OutStreamer.EmitLabel(SectionBegin);
  1601. // Emit the full data.
  1602. AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
  1603. }
  1604. // Emit objective C classes and categories into a hashed accelerator table
  1605. // section.
  1606. void DwarfDebug::emitAccelObjC() {
  1607. AccelObjC.FinalizeTable(Asm, "ObjC");
  1608. Asm->OutStreamer.SwitchSection(
  1609. Asm->getObjFileLowering().getDwarfAccelObjCSection());
  1610. MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
  1611. Asm->OutStreamer.EmitLabel(SectionBegin);
  1612. // Emit the full data.
  1613. AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
  1614. }
  1615. // Emit namespace dies into a hashed accelerator table.
  1616. void DwarfDebug::emitAccelNamespaces() {
  1617. AccelNamespace.FinalizeTable(Asm, "namespac");
  1618. Asm->OutStreamer.SwitchSection(
  1619. Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
  1620. MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
  1621. Asm->OutStreamer.EmitLabel(SectionBegin);
  1622. // Emit the full data.
  1623. AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
  1624. }
  1625. // Emit type dies into a hashed accelerator table.
  1626. void DwarfDebug::emitAccelTypes() {
  1627. AccelTypes.FinalizeTable(Asm, "types");
  1628. Asm->OutStreamer.SwitchSection(
  1629. Asm->getObjFileLowering().getDwarfAccelTypesSection());
  1630. MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
  1631. Asm->OutStreamer.EmitLabel(SectionBegin);
  1632. // Emit the full data.
  1633. AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
  1634. }
  1635. // Public name handling.
  1636. // The format for the various pubnames:
  1637. //
  1638. // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
  1639. // for the DIE that is named.
  1640. //
  1641. // gnu pubnames - offset/index value/name tuples where the offset is the offset
  1642. // into the CU and the index value is computed according to the type of value
  1643. // for the DIE that is named.
  1644. //
  1645. // For type units the offset is the offset of the skeleton DIE. For split dwarf
  1646. // it's the offset within the debug_info/debug_types dwo section, however, the
  1647. // reference in the pubname header doesn't change.
  1648. /// computeIndexValue - Compute the gdb index value for the DIE and CU.
  1649. static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
  1650. const DIE *Die) {
  1651. dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
  1652. // We could have a specification DIE that has our most of our knowledge,
  1653. // look for that now.
  1654. DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
  1655. if (SpecVal) {
  1656. DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
  1657. if (SpecDIE.findAttribute(dwarf::DW_AT_external))
  1658. Linkage = dwarf::GIEL_EXTERNAL;
  1659. } else if (Die->findAttribute(dwarf::DW_AT_external))
  1660. Linkage = dwarf::GIEL_EXTERNAL;
  1661. switch (Die->getTag()) {
  1662. case dwarf::DW_TAG_class_type:
  1663. case dwarf::DW_TAG_structure_type:
  1664. case dwarf::DW_TAG_union_type:
  1665. case dwarf::DW_TAG_enumeration_type:
  1666. return dwarf::PubIndexEntryDescriptor(
  1667. dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
  1668. ? dwarf::GIEL_STATIC
  1669. : dwarf::GIEL_EXTERNAL);
  1670. case dwarf::DW_TAG_typedef:
  1671. case dwarf::DW_TAG_base_type:
  1672. case dwarf::DW_TAG_subrange_type:
  1673. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
  1674. case dwarf::DW_TAG_namespace:
  1675. return dwarf::GIEK_TYPE;
  1676. case dwarf::DW_TAG_subprogram:
  1677. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
  1678. case dwarf::DW_TAG_constant:
  1679. case dwarf::DW_TAG_variable:
  1680. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
  1681. case dwarf::DW_TAG_enumerator:
  1682. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
  1683. dwarf::GIEL_STATIC);
  1684. default:
  1685. return dwarf::GIEK_NONE;
  1686. }
  1687. }
  1688. /// emitDebugPubNames - Emit visible names into a debug pubnames section.
  1689. ///
  1690. void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
  1691. const MCSection *PSec =
  1692. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
  1693. : Asm->getObjFileLowering().getDwarfPubNamesSection();
  1694. emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
  1695. }
  1696. void DwarfDebug::emitDebugPubSection(
  1697. bool GnuStyle, const MCSection *PSec, StringRef Name,
  1698. const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
  1699. for (const auto &NU : CUMap) {
  1700. DwarfCompileUnit *TheU = NU.second;
  1701. const auto &Globals = (TheU->*Accessor)();
  1702. if (Globals.empty())
  1703. continue;
  1704. if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
  1705. TheU = Skeleton;
  1706. unsigned ID = TheU->getUniqueID();
  1707. // Start the dwarf pubnames section.
  1708. Asm->OutStreamer.SwitchSection(PSec);
  1709. // Emit the header.
  1710. Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
  1711. MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
  1712. MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
  1713. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
  1714. Asm->OutStreamer.EmitLabel(BeginLabel);
  1715. Asm->OutStreamer.AddComment("DWARF Version");
  1716. Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
  1717. Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
  1718. Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
  1719. Asm->OutStreamer.AddComment("Compilation Unit Length");
  1720. Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
  1721. // Emit the pubnames for this compilation unit.
  1722. for (const auto &GI : Globals) {
  1723. const char *Name = GI.getKeyData();
  1724. const DIE *Entity = GI.second;
  1725. Asm->OutStreamer.AddComment("DIE offset");
  1726. Asm->EmitInt32(Entity->getOffset());
  1727. if (GnuStyle) {
  1728. dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
  1729. Asm->OutStreamer.AddComment(
  1730. Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
  1731. dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
  1732. Asm->EmitInt8(Desc.toBits());
  1733. }
  1734. Asm->OutStreamer.AddComment("External Name");
  1735. Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
  1736. }
  1737. Asm->OutStreamer.AddComment("End Mark");
  1738. Asm->EmitInt32(0);
  1739. Asm->OutStreamer.EmitLabel(EndLabel);
  1740. }
  1741. }
  1742. void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
  1743. const MCSection *PSec =
  1744. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
  1745. : Asm->getObjFileLowering().getDwarfPubTypesSection();
  1746. emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
  1747. }
  1748. // Emit visible names into a debug str section.
  1749. void DwarfDebug::emitDebugStr() {
  1750. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1751. Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
  1752. }
  1753. /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
  1754. void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
  1755. const DITypeIdentifierMap &Map,
  1756. ArrayRef<DebugLocEntry::Value> Values) {
  1757. assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
  1758. return P.isVariablePiece();
  1759. }) && "all values are expected to be pieces");
  1760. assert(std::is_sorted(Values.begin(), Values.end()) &&
  1761. "pieces are expected to be sorted");
  1762. unsigned Offset = 0;
  1763. for (auto Piece : Values) {
  1764. DIVariable Var = Piece.getVariable();
  1765. unsigned PieceOffset = Var.getPieceOffset();
  1766. unsigned PieceSize = Var.getPieceSize();
  1767. assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
  1768. if (Offset < PieceOffset) {
  1769. // The DWARF spec seriously mandates pieces with no locations for gaps.
  1770. Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
  1771. Offset += PieceOffset-Offset;
  1772. }
  1773. Offset += PieceSize;
  1774. const unsigned SizeOfByte = 8;
  1775. assert(!Var.isIndirect() && "indirect address for piece");
  1776. #ifndef NDEBUG
  1777. unsigned VarSize = Var.getSizeInBits(Map);
  1778. assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
  1779. && "piece is larger than or outside of variable");
  1780. assert(PieceSize*SizeOfByte != VarSize
  1781. && "piece covers entire variable");
  1782. #endif
  1783. if (Piece.isLocation() && Piece.getLoc().isReg())
  1784. Asm->EmitDwarfRegOpPiece(Streamer,
  1785. Piece.getLoc(),
  1786. PieceSize*SizeOfByte);
  1787. else {
  1788. emitDebugLocValue(Streamer, Piece);
  1789. Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
  1790. }
  1791. }
  1792. }
  1793. void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
  1794. const DebugLocEntry &Entry) {
  1795. const DebugLocEntry::Value Value = Entry.getValues()[0];
  1796. if (Value.isVariablePiece())
  1797. // Emit all pieces that belong to the same variable and range.
  1798. return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
  1799. assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
  1800. emitDebugLocValue(Streamer, Value);
  1801. }
  1802. void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
  1803. const DebugLocEntry::Value &Value) {
  1804. DIVariable DV = Value.getVariable();
  1805. // Regular entry.
  1806. if (Value.isInt()) {
  1807. DIBasicType BTy(resolve(DV.getType()));
  1808. if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
  1809. BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
  1810. Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
  1811. Streamer.EmitSLEB128(Value.getInt());
  1812. } else {
  1813. Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
  1814. Streamer.EmitULEB128(Value.getInt());
  1815. }
  1816. } else if (Value.isLocation()) {
  1817. MachineLocation Loc = Value.getLoc();
  1818. if (!DV.hasComplexAddress())
  1819. // Regular entry.
  1820. Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
  1821. else {
  1822. // Complex address entry.
  1823. unsigned N = DV.getNumAddrElements();
  1824. unsigned i = 0;
  1825. if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
  1826. if (Loc.getOffset()) {
  1827. i = 2;
  1828. Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
  1829. Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
  1830. Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
  1831. Streamer.EmitSLEB128(DV.getAddrElement(1));
  1832. } else {
  1833. // If first address element is OpPlus then emit
  1834. // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
  1835. MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
  1836. Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
  1837. i = 2;
  1838. }
  1839. } else {
  1840. Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
  1841. }
  1842. // Emit remaining complex address elements.
  1843. for (; i < N; ++i) {
  1844. uint64_t Element = DV.getAddrElement(i);
  1845. if (Element == DIBuilder::OpPlus) {
  1846. Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
  1847. Streamer.EmitULEB128(DV.getAddrElement(++i));
  1848. } else if (Element == DIBuilder::OpDeref) {
  1849. if (!Loc.isReg())
  1850. Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
  1851. } else if (Element == DIBuilder::OpPiece) {
  1852. i += 3;
  1853. // handled in emitDebugLocEntry.
  1854. } else
  1855. llvm_unreachable("unknown Opcode found in complex address");
  1856. }
  1857. }
  1858. }
  1859. // else ... ignore constant fp. There is not any good way to
  1860. // to represent them here in dwarf.
  1861. // FIXME: ^
  1862. }
  1863. void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
  1864. Asm->OutStreamer.AddComment("Loc expr size");
  1865. MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
  1866. MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
  1867. Asm->EmitLabelDifference(end, begin, 2);
  1868. Asm->OutStreamer.EmitLabel(begin);
  1869. // Emit the entry.
  1870. APByteStreamer Streamer(*Asm);
  1871. emitDebugLocEntry(Streamer, Entry);
  1872. // Close the range.
  1873. Asm->OutStreamer.EmitLabel(end);
  1874. }
  1875. // Emit locations into the debug loc section.
  1876. void DwarfDebug::emitDebugLoc() {
  1877. // Start the dwarf loc section.
  1878. Asm->OutStreamer.SwitchSection(
  1879. Asm->getObjFileLowering().getDwarfLocSection());
  1880. unsigned char Size = Asm->getDataLayout().getPointerSize();
  1881. for (const auto &DebugLoc : DotDebugLocEntries) {
  1882. Asm->OutStreamer.EmitLabel(DebugLoc.Label);
  1883. const DwarfCompileUnit *CU = DebugLoc.CU;
  1884. assert(!CU->getRanges().empty());
  1885. for (const auto &Entry : DebugLoc.List) {
  1886. // Set up the range. This range is relative to the entry point of the
  1887. // compile unit. This is a hard coded 0 for low_pc when we're emitting
  1888. // ranges, or the DW_AT_low_pc on the compile unit otherwise.
  1889. if (CU->getRanges().size() == 1) {
  1890. // Grab the begin symbol from the first range as our base.
  1891. const MCSymbol *Base = CU->getRanges()[0].getStart();
  1892. Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
  1893. Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
  1894. } else {
  1895. Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
  1896. Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
  1897. }
  1898. emitDebugLocEntryLocation(Entry);
  1899. }
  1900. Asm->OutStreamer.EmitIntValue(0, Size);
  1901. Asm->OutStreamer.EmitIntValue(0, Size);
  1902. }
  1903. }
  1904. void DwarfDebug::emitDebugLocDWO() {
  1905. Asm->OutStreamer.SwitchSection(
  1906. Asm->getObjFileLowering().getDwarfLocDWOSection());
  1907. for (const auto &DebugLoc : DotDebugLocEntries) {
  1908. Asm->OutStreamer.EmitLabel(DebugLoc.Label);
  1909. for (const auto &Entry : DebugLoc.List) {
  1910. // Just always use start_length for now - at least that's one address
  1911. // rather than two. We could get fancier and try to, say, reuse an
  1912. // address we know we've emitted elsewhere (the start of the function?
  1913. // The start of the CU or CU subrange that encloses this range?)
  1914. Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
  1915. unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
  1916. Asm->EmitULEB128(idx);
  1917. Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
  1918. emitDebugLocEntryLocation(Entry);
  1919. }
  1920. Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
  1921. }
  1922. }
  1923. struct ArangeSpan {
  1924. const MCSymbol *Start, *End;
  1925. };
  1926. // Emit a debug aranges section, containing a CU lookup for any
  1927. // address we can tie back to a CU.
  1928. void DwarfDebug::emitDebugARanges() {
  1929. // Start the dwarf aranges section.
  1930. Asm->OutStreamer.SwitchSection(
  1931. Asm->getObjFileLowering().getDwarfARangesSection());
  1932. typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
  1933. SpansType Spans;
  1934. // Build a list of sections used.
  1935. std::vector<const MCSection *> Sections;
  1936. for (const auto &it : SectionMap) {
  1937. const MCSection *Section = it.first;
  1938. Sections.push_back(Section);
  1939. }
  1940. // Sort the sections into order.
  1941. // This is only done to ensure consistent output order across different runs.
  1942. std::sort(Sections.begin(), Sections.end(), SectionSort);
  1943. // Build a set of address spans, sorted by CU.
  1944. for (const MCSection *Section : Sections) {
  1945. SmallVector<SymbolCU, 8> &List = SectionMap[Section];
  1946. if (List.size() < 2)
  1947. continue;
  1948. // Sort the symbols by offset within the section.
  1949. std::sort(List.begin(), List.end(),
  1950. [&](const SymbolCU &A, const SymbolCU &B) {
  1951. unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
  1952. unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
  1953. // Symbols with no order assigned should be placed at the end.
  1954. // (e.g. section end labels)
  1955. if (IA == 0)
  1956. return false;
  1957. if (IB == 0)
  1958. return true;
  1959. return IA < IB;
  1960. });
  1961. // If we have no section (e.g. common), just write out
  1962. // individual spans for each symbol.
  1963. if (!Section) {
  1964. for (const SymbolCU &Cur : List) {
  1965. ArangeSpan Span;
  1966. Span.Start = Cur.Sym;
  1967. Span.End = nullptr;
  1968. if (Cur.CU)
  1969. Spans[Cur.CU].push_back(Span);
  1970. }
  1971. } else {
  1972. // Build spans between each label.
  1973. const MCSymbol *StartSym = List[0].Sym;
  1974. for (size_t n = 1, e = List.size(); n < e; n++) {
  1975. const SymbolCU &Prev = List[n - 1];
  1976. const SymbolCU &Cur = List[n];
  1977. // Try and build the longest span we can within the same CU.
  1978. if (Cur.CU != Prev.CU) {
  1979. ArangeSpan Span;
  1980. Span.Start = StartSym;
  1981. Span.End = Cur.Sym;
  1982. Spans[Prev.CU].push_back(Span);
  1983. StartSym = Cur.Sym;
  1984. }
  1985. }
  1986. }
  1987. }
  1988. unsigned PtrSize = Asm->getDataLayout().getPointerSize();
  1989. // Build a list of CUs used.
  1990. std::vector<DwarfCompileUnit *> CUs;
  1991. for (const auto &it : Spans) {
  1992. DwarfCompileUnit *CU = it.first;
  1993. CUs.push_back(CU);
  1994. }
  1995. // Sort the CU list (again, to ensure consistent output order).
  1996. std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
  1997. return A->getUniqueID() < B->getUniqueID();
  1998. });
  1999. // Emit an arange table for each CU we used.
  2000. for (DwarfCompileUnit *CU : CUs) {
  2001. std::vector<ArangeSpan> &List = Spans[CU];
  2002. // Emit size of content not including length itself.
  2003. unsigned ContentSize =
  2004. sizeof(int16_t) + // DWARF ARange version number
  2005. sizeof(int32_t) + // Offset of CU in the .debug_info section
  2006. sizeof(int8_t) + // Pointer Size (in bytes)
  2007. sizeof(int8_t); // Segment Size (in bytes)
  2008. unsigned TupleSize = PtrSize * 2;
  2009. // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
  2010. unsigned Padding =
  2011. OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
  2012. ContentSize += Padding;
  2013. ContentSize += (List.size() + 1) * TupleSize;
  2014. // For each compile unit, write the list of spans it covers.
  2015. Asm->OutStreamer.AddComment("Length of ARange Set");
  2016. Asm->EmitInt32(ContentSize);
  2017. Asm->OutStreamer.AddComment("DWARF Arange version number");
  2018. Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
  2019. Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
  2020. Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
  2021. Asm->OutStreamer.AddComment("Address Size (in bytes)");
  2022. Asm->EmitInt8(PtrSize);
  2023. Asm->OutStreamer.AddComment("Segment Size (in bytes)");
  2024. Asm->EmitInt8(0);
  2025. Asm->OutStreamer.EmitFill(Padding, 0xff);
  2026. for (const ArangeSpan &Span : List) {
  2027. Asm->EmitLabelReference(Span.Start, PtrSize);
  2028. // Calculate the size as being from the span start to it's end.
  2029. if (Span.End) {
  2030. Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
  2031. } else {
  2032. // For symbols without an end marker (e.g. common), we
  2033. // write a single arange entry containing just that one symbol.
  2034. uint64_t Size = SymSize[Span.Start];
  2035. if (Size == 0)
  2036. Size = 1;
  2037. Asm->OutStreamer.EmitIntValue(Size, PtrSize);
  2038. }
  2039. }
  2040. Asm->OutStreamer.AddComment("ARange terminator");
  2041. Asm->OutStreamer.EmitIntValue(0, PtrSize);
  2042. Asm->OutStreamer.EmitIntValue(0, PtrSize);
  2043. }
  2044. }
  2045. // Emit visible names into a debug ranges section.
  2046. void DwarfDebug::emitDebugRanges() {
  2047. // Start the dwarf ranges section.
  2048. Asm->OutStreamer.SwitchSection(
  2049. Asm->getObjFileLowering().getDwarfRangesSection());
  2050. // Size for our labels.
  2051. unsigned char Size = Asm->getDataLayout().getPointerSize();
  2052. // Grab the specific ranges for the compile units in the module.
  2053. for (const auto &I : CUMap) {
  2054. DwarfCompileUnit *TheCU = I.second;
  2055. // Iterate over the misc ranges for the compile units in the module.
  2056. for (const RangeSpanList &List : TheCU->getRangeLists()) {
  2057. // Emit our symbol so we can find the beginning of the range.
  2058. Asm->OutStreamer.EmitLabel(List.getSym());
  2059. for (const RangeSpan &Range : List.getRanges()) {
  2060. const MCSymbol *Begin = Range.getStart();
  2061. const MCSymbol *End = Range.getEnd();
  2062. assert(Begin && "Range without a begin symbol?");
  2063. assert(End && "Range without an end symbol?");
  2064. if (TheCU->getRanges().size() == 1) {
  2065. // Grab the begin symbol from the first range as our base.
  2066. const MCSymbol *Base = TheCU->getRanges()[0].getStart();
  2067. Asm->EmitLabelDifference(Begin, Base, Size);
  2068. Asm->EmitLabelDifference(End, Base, Size);
  2069. } else {
  2070. Asm->OutStreamer.EmitSymbolValue(Begin, Size);
  2071. Asm->OutStreamer.EmitSymbolValue(End, Size);
  2072. }
  2073. }
  2074. // And terminate the list with two 0 values.
  2075. Asm->OutStreamer.EmitIntValue(0, Size);
  2076. Asm->OutStreamer.EmitIntValue(0, Size);
  2077. }
  2078. // Now emit a range for the CU itself.
  2079. if (TheCU->getRanges().size() > 1) {
  2080. Asm->OutStreamer.EmitLabel(
  2081. Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
  2082. for (const RangeSpan &Range : TheCU->getRanges()) {
  2083. const MCSymbol *Begin = Range.getStart();
  2084. const MCSymbol *End = Range.getEnd();
  2085. assert(Begin && "Range without a begin symbol?");
  2086. assert(End && "Range without an end symbol?");
  2087. Asm->OutStreamer.EmitSymbolValue(Begin, Size);
  2088. Asm->OutStreamer.EmitSymbolValue(End, Size);
  2089. }
  2090. // And terminate the list with two 0 values.
  2091. Asm->OutStreamer.EmitIntValue(0, Size);
  2092. Asm->OutStreamer.EmitIntValue(0, Size);
  2093. }
  2094. }
  2095. }
  2096. // DWARF5 Experimental Separate Dwarf emitters.
  2097. void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  2098. std::unique_ptr<DwarfUnit> NewU) {
  2099. NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
  2100. U.getCUNode().getSplitDebugFilename());
  2101. if (!CompilationDir.empty())
  2102. NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  2103. addGnuPubAttributes(*NewU, Die);
  2104. SkeletonHolder.addUnit(std::move(NewU));
  2105. }
  2106. // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
  2107. // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
  2108. // DW_AT_addr_base, DW_AT_ranges_base.
  2109. DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
  2110. auto OwnedUnit = make_unique<DwarfCompileUnit>(
  2111. CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
  2112. DwarfCompileUnit &NewCU = *OwnedUnit;
  2113. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
  2114. DwarfInfoSectionSym);
  2115. NewCU.initStmtList(DwarfLineSectionSym);
  2116. initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
  2117. return NewCU;
  2118. }
  2119. // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
  2120. // DW_AT_addr_base.
  2121. DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
  2122. DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
  2123. *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
  2124. auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), CU, Asm, this,
  2125. &SkeletonHolder);
  2126. DwarfTypeUnit &NewTU = *OwnedUnit;
  2127. NewTU.setTypeSignature(TU.getTypeSignature());
  2128. NewTU.setType(nullptr);
  2129. NewTU.initSection(
  2130. Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
  2131. initSkeletonUnit(TU, NewTU.getUnitDie(), std::move(OwnedUnit));
  2132. return NewTU;
  2133. }
  2134. // Emit the .debug_info.dwo section for separated dwarf. This contains the
  2135. // compile units that would normally be in debug_info.
  2136. void DwarfDebug::emitDebugInfoDWO() {
  2137. assert(useSplitDwarf() && "No split dwarf debug info?");
  2138. // Don't pass an abbrev symbol, using a constant zero instead so as not to
  2139. // emit relocations into the dwo file.
  2140. InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
  2141. }
  2142. // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
  2143. // abbreviations for the .debug_info.dwo section.
  2144. void DwarfDebug::emitDebugAbbrevDWO() {
  2145. assert(useSplitDwarf() && "No split dwarf?");
  2146. InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
  2147. }
  2148. void DwarfDebug::emitDebugLineDWO() {
  2149. assert(useSplitDwarf() && "No split dwarf?");
  2150. Asm->OutStreamer.SwitchSection(
  2151. Asm->getObjFileLowering().getDwarfLineDWOSection());
  2152. SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
  2153. }
  2154. // Emit the .debug_str.dwo section for separated dwarf. This contains the
  2155. // string section and is identical in format to traditional .debug_str
  2156. // sections.
  2157. void DwarfDebug::emitDebugStrDWO() {
  2158. assert(useSplitDwarf() && "No split dwarf?");
  2159. const MCSection *OffSec =
  2160. Asm->getObjFileLowering().getDwarfStrOffDWOSection();
  2161. const MCSymbol *StrSym = DwarfStrSectionSym;
  2162. InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
  2163. OffSec, StrSym);
  2164. }
  2165. MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
  2166. if (!useSplitDwarf())
  2167. return nullptr;
  2168. if (SingleCU)
  2169. SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
  2170. return &SplitTypeUnitFileTable;
  2171. }
  2172. static uint64_t makeTypeSignature(StringRef Identifier) {
  2173. MD5 Hash;
  2174. Hash.update(Identifier);
  2175. // ... take the least significant 8 bytes and return those. Our MD5
  2176. // implementation always returns its results in little endian, swap bytes
  2177. // appropriately.
  2178. MD5::MD5Result Result;
  2179. Hash.final(Result);
  2180. return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
  2181. }
  2182. void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
  2183. StringRef Identifier, DIE &RefDie,
  2184. DICompositeType CTy) {
  2185. // Fast path if we're building some type units and one has already used the
  2186. // address pool we know we're going to throw away all this work anyway, so
  2187. // don't bother building dependent types.
  2188. if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
  2189. return;
  2190. const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
  2191. if (TU) {
  2192. CU.addDIETypeSignature(RefDie, *TU);
  2193. return;
  2194. }
  2195. bool TopLevelType = TypeUnitsUnderConstruction.empty();
  2196. AddrPool.resetUsedFlag();
  2197. auto OwnedUnit = make_unique<DwarfTypeUnit>(
  2198. InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
  2199. this, &InfoHolder, getDwoLineTable(CU));
  2200. DwarfTypeUnit &NewTU = *OwnedUnit;
  2201. DIE &UnitDie = NewTU.getUnitDie();
  2202. TU = &NewTU;
  2203. TypeUnitsUnderConstruction.push_back(
  2204. std::make_pair(std::move(OwnedUnit), CTy));
  2205. NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  2206. CU.getLanguage());
  2207. uint64_t Signature = makeTypeSignature(Identifier);
  2208. NewTU.setTypeSignature(Signature);
  2209. if (useSplitDwarf())
  2210. NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
  2211. DwarfTypesDWOSectionSym);
  2212. else {
  2213. CU.applyStmtList(UnitDie);
  2214. NewTU.initSection(
  2215. Asm->getObjFileLowering().getDwarfTypesSection(Signature));
  2216. }
  2217. NewTU.setType(NewTU.createTypeDIE(CTy));
  2218. if (TopLevelType) {
  2219. auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
  2220. TypeUnitsUnderConstruction.clear();
  2221. // Types referencing entries in the address table cannot be placed in type
  2222. // units.
  2223. if (AddrPool.hasBeenUsed()) {
  2224. // Remove all the types built while building this type.
  2225. // This is pessimistic as some of these types might not be dependent on
  2226. // the type that used an address.
  2227. for (const auto &TU : TypeUnitsToAdd)
  2228. DwarfTypeUnits.erase(TU.second);
  2229. // Construct this type in the CU directly.
  2230. // This is inefficient because all the dependent types will be rebuilt
  2231. // from scratch, including building them in type units, discovering that
  2232. // they depend on addresses, throwing them out and rebuilding them.
  2233. CU.constructTypeDIE(RefDie, CTy);
  2234. return;
  2235. }
  2236. // If the type wasn't dependent on fission addresses, finish adding the type
  2237. // and all its dependent types.
  2238. for (auto &TU : TypeUnitsToAdd) {
  2239. if (useSplitDwarf())
  2240. TU.first->setSkeleton(constructSkeletonTU(*TU.first));
  2241. InfoHolder.addUnit(std::move(TU.first));
  2242. }
  2243. }
  2244. CU.addDIETypeSignature(RefDie, NewTU);
  2245. }
  2246. void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
  2247. MCSymbol *Begin, MCSymbol *End) {
  2248. assert(Begin && "Begin label should not be null!");
  2249. assert(End && "End label should not be null!");
  2250. assert(Begin->isDefined() && "Invalid starting label");
  2251. assert(End->isDefined() && "Invalid end label");
  2252. Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
  2253. if (DwarfVersion < 4)
  2254. Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
  2255. else
  2256. Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
  2257. }
  2258. // Accelerator table mutators - add each name along with its companion
  2259. // DIE to the proper table while ensuring that the name that we're going
  2260. // to reference is in the string table. We do this since the names we
  2261. // add may not only be identical to the names in the DIE.
  2262. void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
  2263. if (!useDwarfAccelTables())
  2264. return;
  2265. AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  2266. &Die);
  2267. }
  2268. void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
  2269. if (!useDwarfAccelTables())
  2270. return;
  2271. AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  2272. &Die);
  2273. }
  2274. void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
  2275. if (!useDwarfAccelTables())
  2276. return;
  2277. AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  2278. &Die);
  2279. }
  2280. void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
  2281. if (!useDwarfAccelTables())
  2282. return;
  2283. AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
  2284. &Die);
  2285. }