DwarfDebug.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  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 "DwarfDebug.h"
  14. #include "ByteStreamer.h"
  15. #include "DIEHash.h"
  16. #include "DebugLocEntry.h"
  17. #include "DebugLocStream.h"
  18. #include "DwarfAccelTable.h"
  19. #include "DwarfCompileUnit.h"
  20. #include "DwarfExpression.h"
  21. #include "DwarfFile.h"
  22. #include "DwarfUnit.h"
  23. #include "llvm/ADT/APInt.h"
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/ADT/MapVector.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/ADT/Triple.h"
  31. #include "llvm/ADT/Twine.h"
  32. #include "llvm/BinaryFormat/Dwarf.h"
  33. #include "llvm/CodeGen/AsmPrinter.h"
  34. #include "llvm/CodeGen/DIE.h"
  35. #include "llvm/CodeGen/LexicalScopes.h"
  36. #include "llvm/CodeGen/MachineBasicBlock.h"
  37. #include "llvm/CodeGen/MachineFunction.h"
  38. #include "llvm/CodeGen/MachineInstr.h"
  39. #include "llvm/CodeGen/MachineModuleInfo.h"
  40. #include "llvm/CodeGen/MachineOperand.h"
  41. #include "llvm/IR/Constants.h"
  42. #include "llvm/IR/DebugInfoMetadata.h"
  43. #include "llvm/IR/DebugLoc.h"
  44. #include "llvm/IR/Function.h"
  45. #include "llvm/IR/GlobalVariable.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/MC/MCAsmInfo.h"
  48. #include "llvm/MC/MCContext.h"
  49. #include "llvm/MC/MCDwarf.h"
  50. #include "llvm/MC/MCSection.h"
  51. #include "llvm/MC/MCStreamer.h"
  52. #include "llvm/MC/MCSymbol.h"
  53. #include "llvm/MC/MCTargetOptions.h"
  54. #include "llvm/MC/MachineLocation.h"
  55. #include "llvm/MC/SectionKind.h"
  56. #include "llvm/Pass.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Debug.h"
  60. #include "llvm/Support/ErrorHandling.h"
  61. #include "llvm/Support/MD5.h"
  62. #include "llvm/Support/MathExtras.h"
  63. #include "llvm/Support/Timer.h"
  64. #include "llvm/Support/raw_ostream.h"
  65. #include "llvm/Target/TargetLoweringObjectFile.h"
  66. #include "llvm/Target/TargetMachine.h"
  67. #include "llvm/Target/TargetOptions.h"
  68. #include "llvm/Target/TargetRegisterInfo.h"
  69. #include "llvm/Target/TargetSubtargetInfo.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <cstddef>
  73. #include <cstdint>
  74. #include <iterator>
  75. #include <string>
  76. #include <utility>
  77. #include <vector>
  78. using namespace llvm;
  79. #define DEBUG_TYPE "dwarfdebug"
  80. static cl::opt<bool>
  81. DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
  82. cl::desc("Disable debug info printing"));
  83. static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
  84. "use-dwarf-ranges-base-address-specifier", cl::Hidden,
  85. cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
  86. static cl::opt<bool> GenerateARangeSection("generate-arange-section",
  87. cl::Hidden,
  88. cl::desc("Generate dwarf aranges"),
  89. cl::init(false));
  90. static cl::opt<bool> SplitDwarfCrossCuReferences(
  91. "split-dwarf-cross-cu-references", cl::Hidden,
  92. cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
  93. enum DefaultOnOff { Default, Enable, Disable };
  94. static cl::opt<DefaultOnOff> UnknownLocations(
  95. "use-unknown-locations", cl::Hidden,
  96. cl::desc("Make an absence of debug location information explicit."),
  97. cl::values(clEnumVal(Default, "At top of block or after label"),
  98. clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
  99. cl::init(Default));
  100. static cl::opt<DefaultOnOff>
  101. DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
  102. cl::desc("Output prototype dwarf accelerator tables."),
  103. cl::values(clEnumVal(Default, "Default for platform"),
  104. clEnumVal(Enable, "Enabled"),
  105. clEnumVal(Disable, "Disabled")),
  106. cl::init(Default));
  107. enum LinkageNameOption {
  108. DefaultLinkageNames,
  109. AllLinkageNames,
  110. AbstractLinkageNames
  111. };
  112. static cl::opt<LinkageNameOption>
  113. DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
  114. cl::desc("Which DWARF linkage-name attributes to emit."),
  115. cl::values(clEnumValN(DefaultLinkageNames, "Default",
  116. "Default for platform"),
  117. clEnumValN(AllLinkageNames, "All", "All"),
  118. clEnumValN(AbstractLinkageNames, "Abstract",
  119. "Abstract subprograms")),
  120. cl::init(DefaultLinkageNames));
  121. static const char *const DWARFGroupName = "dwarf";
  122. static const char *const DWARFGroupDescription = "DWARF Emission";
  123. static const char *const DbgTimerName = "writer";
  124. static const char *const DbgTimerDescription = "DWARF Debug Writer";
  125. void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
  126. BS.EmitInt8(
  127. Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
  128. : dwarf::OperationEncodingString(Op));
  129. }
  130. void DebugLocDwarfExpression::emitSigned(int64_t Value) {
  131. BS.EmitSLEB128(Value, Twine(Value));
  132. }
  133. void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
  134. BS.EmitULEB128(Value, Twine(Value));
  135. }
  136. bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
  137. unsigned MachineReg) {
  138. // This information is not available while emitting .debug_loc entries.
  139. return false;
  140. }
  141. bool DbgVariable::isBlockByrefVariable() const {
  142. assert(Var && "Invalid complex DbgVariable!");
  143. return Var->getType().resolve()->isBlockByrefStruct();
  144. }
  145. const DIType *DbgVariable::getType() const {
  146. DIType *Ty = Var->getType().resolve();
  147. // FIXME: isBlockByrefVariable should be reformulated in terms of complex
  148. // addresses instead.
  149. if (Ty->isBlockByrefStruct()) {
  150. /* Byref variables, in Blocks, are declared by the programmer as
  151. "SomeType VarName;", but the compiler creates a
  152. __Block_byref_x_VarName struct, and gives the variable VarName
  153. either the struct, or a pointer to the struct, as its type. This
  154. is necessary for various behind-the-scenes things the compiler
  155. needs to do with by-reference variables in blocks.
  156. However, as far as the original *programmer* is concerned, the
  157. variable should still have type 'SomeType', as originally declared.
  158. The following function dives into the __Block_byref_x_VarName
  159. struct to find the original type of the variable. This will be
  160. passed back to the code generating the type for the Debug
  161. Information Entry for the variable 'VarName'. 'VarName' will then
  162. have the original type 'SomeType' in its debug information.
  163. The original type 'SomeType' will be the type of the field named
  164. 'VarName' inside the __Block_byref_x_VarName struct.
  165. NOTE: In order for this to not completely fail on the debugger
  166. side, the Debug Information Entry for the variable VarName needs to
  167. have a DW_AT_location that tells the debugger how to unwind through
  168. the pointers and __Block_byref_x_VarName struct to find the actual
  169. value of the variable. The function addBlockByrefType does this. */
  170. DIType *subType = Ty;
  171. uint16_t tag = Ty->getTag();
  172. if (tag == dwarf::DW_TAG_pointer_type)
  173. subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
  174. auto Elements = cast<DICompositeType>(subType)->getElements();
  175. for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
  176. auto *DT = cast<DIDerivedType>(Elements[i]);
  177. if (getName() == DT->getName())
  178. return resolve(DT->getBaseType());
  179. }
  180. }
  181. return Ty;
  182. }
  183. ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
  184. if (FrameIndexExprs.size() == 1)
  185. return FrameIndexExprs;
  186. assert(llvm::all_of(FrameIndexExprs,
  187. [](const FrameIndexExpr &A) {
  188. return A.Expr->isFragment();
  189. }) &&
  190. "multiple FI expressions without DW_OP_LLVM_fragment");
  191. std::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
  192. [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
  193. return A.Expr->getFragmentInfo()->OffsetInBits <
  194. B.Expr->getFragmentInfo()->OffsetInBits;
  195. });
  196. return FrameIndexExprs;
  197. }
  198. void DbgVariable::addMMIEntry(const DbgVariable &V) {
  199. assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
  200. assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
  201. assert(V.Var == Var && "conflicting variable");
  202. assert(V.IA == IA && "conflicting inlined-at location");
  203. assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
  204. assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
  205. for (const auto &FIE : V.FrameIndexExprs)
  206. // Ignore duplicate entries.
  207. if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
  208. return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
  209. }))
  210. FrameIndexExprs.push_back(FIE);
  211. assert((FrameIndexExprs.size() == 1 ||
  212. llvm::all_of(FrameIndexExprs,
  213. [](FrameIndexExpr &FIE) {
  214. return FIE.Expr && FIE.Expr->isFragment();
  215. })) &&
  216. "conflicting locations for variable");
  217. }
  218. static const DwarfAccelTable::Atom TypeAtoms[] = {
  219. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
  220. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
  221. DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
  222. DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
  223. : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
  224. InfoHolder(A, "info_string", DIEValueAllocator),
  225. SkeletonHolder(A, "skel_string", DIEValueAllocator),
  226. IsDarwin(A->TM.getTargetTriple().isOSDarwin()),
  227. AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  228. dwarf::DW_FORM_data4)),
  229. AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  230. dwarf::DW_FORM_data4)),
  231. AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  232. dwarf::DW_FORM_data4)),
  233. AccelTypes(TypeAtoms) {
  234. const Triple &TT = Asm->TM.getTargetTriple();
  235. // Make sure we know our "debugger tuning." The target option takes
  236. // precedence; fall back to triple-based defaults.
  237. if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
  238. DebuggerTuning = Asm->TM.Options.DebuggerTuning;
  239. else if (IsDarwin)
  240. DebuggerTuning = DebuggerKind::LLDB;
  241. else if (TT.isPS4CPU())
  242. DebuggerTuning = DebuggerKind::SCE;
  243. else
  244. DebuggerTuning = DebuggerKind::GDB;
  245. // Turn on accelerator tables for LLDB by default.
  246. if (DwarfAccelTables == Default)
  247. HasDwarfAccelTables = tuneForLLDB();
  248. else
  249. HasDwarfAccelTables = DwarfAccelTables == Enable;
  250. HasAppleExtensionAttributes = tuneForLLDB();
  251. // Handle split DWARF.
  252. HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
  253. // SCE defaults to linkage names only for abstract subprograms.
  254. if (DwarfLinkageNames == DefaultLinkageNames)
  255. UseAllLinkageNames = !tuneForSCE();
  256. else
  257. UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
  258. unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
  259. unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
  260. : MMI->getModule()->getDwarfVersion();
  261. // Use dwarf 4 by default if nothing is requested.
  262. DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
  263. // Work around a GDB bug. GDB doesn't support the standard opcode;
  264. // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
  265. // is defined as of DWARF 3.
  266. // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
  267. // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
  268. UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
  269. // GDB does not fully support the DWARF 4 representation for bitfields.
  270. UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
  271. Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
  272. }
  273. // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
  274. DwarfDebug::~DwarfDebug() = default;
  275. static bool isObjCClass(StringRef Name) {
  276. return Name.startswith("+") || Name.startswith("-");
  277. }
  278. static bool hasObjCCategory(StringRef Name) {
  279. if (!isObjCClass(Name))
  280. return false;
  281. return Name.find(") ") != StringRef::npos;
  282. }
  283. static void getObjCClassCategory(StringRef In, StringRef &Class,
  284. StringRef &Category) {
  285. if (!hasObjCCategory(In)) {
  286. Class = In.slice(In.find('[') + 1, In.find(' '));
  287. Category = "";
  288. return;
  289. }
  290. Class = In.slice(In.find('[') + 1, In.find('('));
  291. Category = In.slice(In.find('[') + 1, In.find(' '));
  292. }
  293. static StringRef getObjCMethodName(StringRef In) {
  294. return In.slice(In.find(' ') + 1, In.find(']'));
  295. }
  296. // Add the various names to the Dwarf accelerator table names.
  297. // TODO: Determine whether or not we should add names for programs
  298. // that do not have a DW_AT_name or DW_AT_linkage_name field - this
  299. // is only slightly different than the lookup of non-standard ObjC names.
  300. void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
  301. if (!SP->isDefinition())
  302. return;
  303. addAccelName(SP->getName(), Die);
  304. // If the linkage name is different than the name, go ahead and output
  305. // that as well into the name table.
  306. if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
  307. addAccelName(SP->getLinkageName(), Die);
  308. // If this is an Objective-C selector name add it to the ObjC accelerator
  309. // too.
  310. if (isObjCClass(SP->getName())) {
  311. StringRef Class, Category;
  312. getObjCClassCategory(SP->getName(), Class, Category);
  313. addAccelObjC(Class, Die);
  314. if (Category != "")
  315. addAccelObjC(Category, Die);
  316. // Also add the base method name to the name table.
  317. addAccelName(getObjCMethodName(SP->getName()), Die);
  318. }
  319. }
  320. /// Check whether we should create a DIE for the given Scope, return true
  321. /// if we don't create a DIE (the corresponding DIE is null).
  322. bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
  323. if (Scope->isAbstractScope())
  324. return false;
  325. // We don't create a DIE if there is no Range.
  326. const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
  327. if (Ranges.empty())
  328. return true;
  329. if (Ranges.size() > 1)
  330. return false;
  331. // We don't create a DIE if we have a single Range and the end label
  332. // is null.
  333. return !getLabelAfterInsn(Ranges.front().second);
  334. }
  335. template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
  336. F(CU);
  337. if (auto *SkelCU = CU.getSkeleton())
  338. if (CU.getCUNode()->getSplitDebugInlining())
  339. F(*SkelCU);
  340. }
  341. bool DwarfDebug::shareAcrossDWOCUs() const {
  342. return SplitDwarfCrossCuReferences;
  343. }
  344. void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
  345. LexicalScope *Scope) {
  346. assert(Scope && Scope->getScopeNode());
  347. assert(Scope->isAbstractScope());
  348. assert(!Scope->getInlinedAt());
  349. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  350. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  351. // was inlined from another compile unit.
  352. if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
  353. // Avoid building the original CU if it won't be used
  354. SrcCU.constructAbstractSubprogramScopeDIE(Scope);
  355. else {
  356. auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
  357. if (auto *SkelCU = CU.getSkeleton()) {
  358. (shareAcrossDWOCUs() ? CU : SrcCU)
  359. .constructAbstractSubprogramScopeDIE(Scope);
  360. if (CU.getCUNode()->getSplitDebugInlining())
  361. SkelCU->constructAbstractSubprogramScopeDIE(Scope);
  362. } else
  363. CU.constructAbstractSubprogramScopeDIE(Scope);
  364. }
  365. }
  366. void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
  367. if (!U.hasDwarfPubSections())
  368. return;
  369. U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
  370. }
  371. // Create new DwarfCompileUnit for the given metadata node with tag
  372. // DW_TAG_compile_unit.
  373. DwarfCompileUnit &
  374. DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
  375. if (auto *CU = CUMap.lookup(DIUnit))
  376. return *CU;
  377. StringRef FN = DIUnit->getFilename();
  378. CompilationDir = DIUnit->getDirectory();
  379. auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
  380. InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
  381. DwarfCompileUnit &NewCU = *OwnedUnit;
  382. DIE &Die = NewCU.getUnitDie();
  383. InfoHolder.addUnit(std::move(OwnedUnit));
  384. if (useSplitDwarf()) {
  385. NewCU.setSkeleton(constructSkeletonCU(NewCU));
  386. NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
  387. Asm->TM.Options.MCOptions.SplitDwarfFile);
  388. }
  389. for (auto *IE : DIUnit->getImportedEntities())
  390. NewCU.addImportedEntity(IE);
  391. // LTO with assembly output shares a single line table amongst multiple CUs.
  392. // To avoid the compilation directory being ambiguous, let the line table
  393. // explicitly describe the directory of all files, never relying on the
  394. // compilation directory.
  395. if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
  396. Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
  397. NewCU.getUniqueID(), CompilationDir);
  398. StringRef Producer = DIUnit->getProducer();
  399. StringRef Flags = DIUnit->getFlags();
  400. if (!Flags.empty()) {
  401. std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
  402. NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
  403. } else
  404. NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
  405. NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  406. DIUnit->getSourceLanguage());
  407. NewCU.addString(Die, dwarf::DW_AT_name, FN);
  408. if (!useSplitDwarf()) {
  409. NewCU.initStmtList();
  410. // If we're using split dwarf the compilation dir is going to be in the
  411. // skeleton CU and so we don't need to duplicate it here.
  412. if (!CompilationDir.empty())
  413. NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  414. addGnuPubAttributes(NewCU, Die);
  415. }
  416. if (useAppleExtensionAttributes()) {
  417. if (DIUnit->isOptimized())
  418. NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
  419. StringRef Flags = DIUnit->getFlags();
  420. if (!Flags.empty())
  421. NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  422. if (unsigned RVer = DIUnit->getRuntimeVersion())
  423. NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
  424. dwarf::DW_FORM_data1, RVer);
  425. }
  426. if (useSplitDwarf())
  427. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
  428. else
  429. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
  430. if (DIUnit->getDWOId()) {
  431. // This CU is either a clang module DWO or a skeleton CU.
  432. NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
  433. DIUnit->getDWOId());
  434. if (!DIUnit->getSplitDebugFilename().empty())
  435. // This is a prefabricated skeleton CU.
  436. NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
  437. DIUnit->getSplitDebugFilename());
  438. }
  439. CUMap.insert({DIUnit, &NewCU});
  440. CUDieMap.insert({&Die, &NewCU});
  441. return NewCU;
  442. }
  443. void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
  444. const DIImportedEntity *N) {
  445. if (isa<DILocalScope>(N->getScope()))
  446. return;
  447. if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
  448. D->addChild(TheCU.constructImportedEntityDIE(N));
  449. }
  450. /// Sort and unique GVEs by comparing their fragment offset.
  451. static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
  452. sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
  453. std::sort(GVEs.begin(), GVEs.end(),
  454. [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
  455. if (A.Expr != B.Expr && A.Expr && B.Expr) {
  456. auto FragmentA = A.Expr->getFragmentInfo();
  457. auto FragmentB = B.Expr->getFragmentInfo();
  458. if (FragmentA && FragmentB)
  459. return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
  460. }
  461. return false;
  462. });
  463. GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
  464. [](DwarfCompileUnit::GlobalExpr A,
  465. DwarfCompileUnit::GlobalExpr B) {
  466. return A.Expr == B.Expr;
  467. }),
  468. GVEs.end());
  469. return GVEs;
  470. }
  471. // Emit all Dwarf sections that should come prior to the content. Create
  472. // global DIEs and emit initial debug info sections. This is invoked by
  473. // the target AsmPrinter.
  474. void DwarfDebug::beginModule() {
  475. NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
  476. DWARFGroupDescription, TimePassesIsEnabled);
  477. if (DisableDebugInfoPrinting)
  478. return;
  479. const Module *M = MMI->getModule();
  480. unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
  481. M->debug_compile_units_end());
  482. // Tell MMI whether we have debug info.
  483. MMI->setDebugInfoAvailability(NumDebugCUs > 0);
  484. SingleCU = NumDebugCUs == 1;
  485. DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
  486. GVMap;
  487. for (const GlobalVariable &Global : M->globals()) {
  488. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  489. Global.getDebugInfo(GVs);
  490. for (auto *GVE : GVs)
  491. GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
  492. }
  493. for (DICompileUnit *CUNode : M->debug_compile_units()) {
  494. // FIXME: Move local imported entities into a list attached to the
  495. // subprogram, then this search won't be needed and a
  496. // getImportedEntities().empty() test should go below with the rest.
  497. bool HasNonLocalImportedEntities = llvm::any_of(
  498. CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
  499. return !isa<DILocalScope>(IE->getScope());
  500. });
  501. if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
  502. CUNode->getRetainedTypes().empty() &&
  503. CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
  504. continue;
  505. DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
  506. // Global Variables.
  507. for (auto *GVE : CUNode->getGlobalVariables()) {
  508. // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
  509. // already know about the variable and it isn't adding a constant
  510. // expression.
  511. auto &GVMapEntry = GVMap[GVE->getVariable()];
  512. auto *Expr = GVE->getExpression();
  513. if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
  514. GVMapEntry.push_back({nullptr, Expr});
  515. }
  516. DenseSet<DIGlobalVariable *> Processed;
  517. for (auto *GVE : CUNode->getGlobalVariables()) {
  518. DIGlobalVariable *GV = GVE->getVariable();
  519. if (Processed.insert(GV).second)
  520. CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
  521. }
  522. for (auto *Ty : CUNode->getEnumTypes()) {
  523. // The enum types array by design contains pointers to
  524. // MDNodes rather than DIRefs. Unique them here.
  525. CU.getOrCreateTypeDIE(cast<DIType>(Ty));
  526. }
  527. for (auto *Ty : CUNode->getRetainedTypes()) {
  528. // The retained types array by design contains pointers to
  529. // MDNodes rather than DIRefs. Unique them here.
  530. if (DIType *RT = dyn_cast<DIType>(Ty))
  531. // There is no point in force-emitting a forward declaration.
  532. CU.getOrCreateTypeDIE(RT);
  533. }
  534. // Emit imported_modules last so that the relevant context is already
  535. // available.
  536. for (auto *IE : CUNode->getImportedEntities())
  537. constructAndAddImportedEntityDIE(CU, IE);
  538. }
  539. }
  540. void DwarfDebug::finishVariableDefinitions() {
  541. for (const auto &Var : ConcreteVariables) {
  542. DIE *VariableDie = Var->getDIE();
  543. assert(VariableDie);
  544. // FIXME: Consider the time-space tradeoff of just storing the unit pointer
  545. // in the ConcreteVariables list, rather than looking it up again here.
  546. // DIE::getUnit isn't simple - it walks parent pointers, etc.
  547. DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
  548. assert(Unit);
  549. Unit->finishVariableDefinition(*Var);
  550. }
  551. }
  552. void DwarfDebug::finishSubprogramDefinitions() {
  553. for (const DISubprogram *SP : ProcessedSPNodes) {
  554. assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
  555. forBothCUs(
  556. getOrCreateDwarfCompileUnit(SP->getUnit()),
  557. [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
  558. }
  559. }
  560. void DwarfDebug::finalizeModuleInfo() {
  561. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  562. finishSubprogramDefinitions();
  563. finishVariableDefinitions();
  564. // Include the DWO file name in the hash if there's more than one CU.
  565. // This handles ThinLTO's situation where imported CUs may very easily be
  566. // duplicate with the same CU partially imported into another ThinLTO unit.
  567. StringRef DWOName;
  568. if (CUMap.size() > 1)
  569. DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
  570. // Handle anything that needs to be done on a per-unit basis after
  571. // all other generation.
  572. for (const auto &P : CUMap) {
  573. auto &TheCU = *P.second;
  574. // Emit DW_AT_containing_type attribute to connect types with their
  575. // vtable holding type.
  576. TheCU.constructContainingTypeDIEs();
  577. // Add CU specific attributes if we need to add any.
  578. // If we're splitting the dwarf out now that we've got the entire
  579. // CU then add the dwo id to it.
  580. auto *SkCU = TheCU.getSkeleton();
  581. if (useSplitDwarf()) {
  582. // Emit a unique identifier for this CU.
  583. uint64_t ID =
  584. DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
  585. TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  586. dwarf::DW_FORM_data8, ID);
  587. SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  588. dwarf::DW_FORM_data8, ID);
  589. // We don't keep track of which addresses are used in which CU so this
  590. // is a bit pessimistic under LTO.
  591. if (!AddrPool.isEmpty()) {
  592. const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
  593. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
  594. Sym, Sym);
  595. }
  596. if (!SkCU->getRangeLists().empty()) {
  597. const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
  598. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
  599. Sym, Sym);
  600. }
  601. }
  602. // If we have code split among multiple sections or non-contiguous
  603. // ranges of code then emit a DW_AT_ranges attribute on the unit that will
  604. // remain in the .o file, otherwise add a DW_AT_low_pc.
  605. // FIXME: We should use ranges allow reordering of code ala
  606. // .subsections_via_symbols in mach-o. This would mean turning on
  607. // ranges for all subprogram DIEs for mach-o.
  608. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  609. if (unsigned NumRanges = TheCU.getRanges().size()) {
  610. if (NumRanges > 1)
  611. // A DW_AT_low_pc attribute may also be specified in combination with
  612. // DW_AT_ranges to specify the default base address for use in
  613. // location lists (see Section 2.6.2) and range lists (see Section
  614. // 2.17.3).
  615. U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
  616. else
  617. U.setBaseAddress(TheCU.getRanges().front().getStart());
  618. U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
  619. }
  620. auto *CUNode = cast<DICompileUnit>(P.first);
  621. // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
  622. if (CUNode->getMacros())
  623. U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
  624. U.getMacroLabelBegin(),
  625. TLOF.getDwarfMacinfoSection()->getBeginSymbol());
  626. }
  627. // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
  628. for (auto *CUNode : MMI->getModule()->debug_compile_units())
  629. if (CUNode->getDWOId())
  630. getOrCreateDwarfCompileUnit(CUNode);
  631. // Compute DIE offsets and sizes.
  632. InfoHolder.computeSizeAndOffsets();
  633. if (useSplitDwarf())
  634. SkeletonHolder.computeSizeAndOffsets();
  635. }
  636. // Emit all Dwarf sections that should come after the content.
  637. void DwarfDebug::endModule() {
  638. assert(CurFn == nullptr);
  639. assert(CurMI == nullptr);
  640. // If we aren't actually generating debug info (check beginModule -
  641. // conditionalized on !DisableDebugInfoPrinting and the presence of the
  642. // llvm.dbg.cu metadata node)
  643. if (!MMI->hasDebugInfo())
  644. return;
  645. // Finalize the debug info for the module.
  646. finalizeModuleInfo();
  647. emitDebugStr();
  648. if (useSplitDwarf())
  649. emitDebugLocDWO();
  650. else
  651. // Emit info into a debug loc section.
  652. emitDebugLoc();
  653. // Corresponding abbreviations into a abbrev section.
  654. emitAbbreviations();
  655. // Emit all the DIEs into a debug info section.
  656. emitDebugInfo();
  657. // Emit info into a debug aranges section.
  658. if (GenerateARangeSection)
  659. emitDebugARanges();
  660. // Emit info into a debug ranges section.
  661. emitDebugRanges();
  662. // Emit info into a debug macinfo section.
  663. emitDebugMacinfo();
  664. if (useSplitDwarf()) {
  665. emitDebugStrDWO();
  666. emitDebugInfoDWO();
  667. emitDebugAbbrevDWO();
  668. emitDebugLineDWO();
  669. // Emit DWO addresses.
  670. AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
  671. }
  672. // Emit info into the dwarf accelerator table sections.
  673. if (useDwarfAccelTables()) {
  674. emitAccelNames();
  675. emitAccelObjC();
  676. emitAccelNamespaces();
  677. emitAccelTypes();
  678. }
  679. // Emit the pubnames and pubtypes sections if requested.
  680. emitDebugPubSections();
  681. // clean up.
  682. // FIXME: AbstractVariables.clear();
  683. }
  684. void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
  685. const MDNode *ScopeNode) {
  686. const DILocalVariable *Cleansed = nullptr;
  687. if (CU.getExistingAbstractVariable(IV, Cleansed))
  688. return;
  689. CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
  690. cast<DILocalScope>(ScopeNode)));
  691. }
  692. void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU,
  693. InlinedVariable IV, const MDNode *ScopeNode) {
  694. const DILocalVariable *Cleansed = nullptr;
  695. if (CU.getExistingAbstractVariable(IV, Cleansed))
  696. return;
  697. if (LexicalScope *Scope =
  698. LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
  699. CU.createAbstractVariable(Cleansed, Scope);
  700. }
  701. // Collect variable information from side table maintained by MF.
  702. void DwarfDebug::collectVariableInfoFromMFTable(
  703. DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
  704. SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
  705. for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
  706. if (!VI.Var)
  707. continue;
  708. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  709. "Expected inlined-at fields to agree");
  710. InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
  711. Processed.insert(Var);
  712. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  713. // If variable scope is not found then skip this variable.
  714. if (!Scope)
  715. continue;
  716. ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode());
  717. auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
  718. RegVar->initializeMMI(VI.Expr, VI.Slot);
  719. if (DbgVariable *DbgVar = MFVars.lookup(Var))
  720. DbgVar->addMMIEntry(*RegVar);
  721. else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
  722. MFVars.insert({Var, RegVar.get()});
  723. ConcreteVariables.push_back(std::move(RegVar));
  724. }
  725. }
  726. }
  727. // Get .debug_loc entry for the instruction range starting at MI.
  728. static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
  729. const DIExpression *Expr = MI->getDebugExpression();
  730. assert(MI->getNumOperands() == 4);
  731. if (MI->getOperand(0).isReg()) {
  732. auto RegOp = MI->getOperand(0);
  733. auto Op1 = MI->getOperand(1);
  734. // If the second operand is an immediate, this is a
  735. // register-indirect address.
  736. assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
  737. MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
  738. return DebugLocEntry::Value(Expr, MLoc);
  739. }
  740. if (MI->getOperand(0).isImm())
  741. return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
  742. if (MI->getOperand(0).isFPImm())
  743. return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
  744. if (MI->getOperand(0).isCImm())
  745. return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
  746. llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
  747. }
  748. /// \brief If this and Next are describing different fragments of the same
  749. /// variable, merge them by appending Next's values to the current
  750. /// list of values.
  751. /// Return true if the merge was successful.
  752. bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
  753. if (Begin == Next.Begin) {
  754. auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
  755. auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
  756. if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
  757. return false;
  758. // We can only merge entries if none of the fragments overlap any others.
  759. // In doing so, we can take advantage of the fact that both lists are
  760. // sorted.
  761. for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
  762. for (; j < Next.Values.size(); ++j) {
  763. int res = DebugHandlerBase::fragmentCmp(
  764. cast<DIExpression>(Values[i].Expression),
  765. cast<DIExpression>(Next.Values[j].Expression));
  766. if (res == 0) // The two expressions overlap, we can't merge.
  767. return false;
  768. // Values[i] is entirely before Next.Values[j],
  769. // so go back to the next entry of Values.
  770. else if (res == -1)
  771. break;
  772. // Next.Values[j] is entirely before Values[i], so go on to the
  773. // next entry of Next.Values.
  774. }
  775. }
  776. addValues(Next.Values);
  777. End = Next.End;
  778. return true;
  779. }
  780. return false;
  781. }
  782. /// Build the location list for all DBG_VALUEs in the function that
  783. /// describe the same variable. If the ranges of several independent
  784. /// fragments of the same variable overlap partially, split them up and
  785. /// combine the ranges. The resulting DebugLocEntries are will have
  786. /// strict monotonically increasing begin addresses and will never
  787. /// overlap.
  788. //
  789. // Input:
  790. //
  791. // Ranges History [var, loc, fragment ofs size]
  792. // 0 | [x, (reg0, fragment 0, 32)]
  793. // 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
  794. // 2 | | ...
  795. // 3 | [clobber reg0]
  796. // 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
  797. // x.
  798. //
  799. // Output:
  800. //
  801. // [0-1] [x, (reg0, fragment 0, 32)]
  802. // [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
  803. // [3-4] [x, (reg1, fragment 32, 32)]
  804. // [4- ] [x, (mem, fragment 0, 64)]
  805. void
  806. DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  807. const DbgValueHistoryMap::InstrRanges &Ranges) {
  808. SmallVector<DebugLocEntry::Value, 4> OpenRanges;
  809. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  810. const MachineInstr *Begin = I->first;
  811. const MachineInstr *End = I->second;
  812. assert(Begin->isDebugValue() && "Invalid History entry");
  813. // Check if a variable is inaccessible in this range.
  814. if (Begin->getNumOperands() > 1 &&
  815. Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
  816. OpenRanges.clear();
  817. continue;
  818. }
  819. // If this fragment overlaps with any open ranges, truncate them.
  820. const DIExpression *DIExpr = Begin->getDebugExpression();
  821. auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
  822. return fragmentsOverlap(DIExpr, R.getExpression());
  823. });
  824. OpenRanges.erase(Last, OpenRanges.end());
  825. const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
  826. assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
  827. const MCSymbol *EndLabel;
  828. if (End != nullptr)
  829. EndLabel = getLabelAfterInsn(End);
  830. else if (std::next(I) == Ranges.end())
  831. EndLabel = Asm->getFunctionEnd();
  832. else
  833. EndLabel = getLabelBeforeInsn(std::next(I)->first);
  834. assert(EndLabel && "Forgot label after instruction ending a range!");
  835. DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
  836. auto Value = getDebugLocValue(Begin);
  837. DebugLocEntry Loc(StartLabel, EndLabel, Value);
  838. bool couldMerge = false;
  839. // If this is a fragment, it may belong to the current DebugLocEntry.
  840. if (DIExpr->isFragment()) {
  841. // Add this value to the list of open ranges.
  842. OpenRanges.push_back(Value);
  843. // Attempt to add the fragment to the last entry.
  844. if (!DebugLoc.empty())
  845. if (DebugLoc.back().MergeValues(Loc))
  846. couldMerge = true;
  847. }
  848. if (!couldMerge) {
  849. // Need to add a new DebugLocEntry. Add all values from still
  850. // valid non-overlapping fragments.
  851. if (OpenRanges.size())
  852. Loc.addValues(OpenRanges);
  853. DebugLoc.push_back(std::move(Loc));
  854. }
  855. // Attempt to coalesce the ranges of two otherwise identical
  856. // DebugLocEntries.
  857. auto CurEntry = DebugLoc.rbegin();
  858. DEBUG({
  859. dbgs() << CurEntry->getValues().size() << " Values:\n";
  860. for (auto &Value : CurEntry->getValues())
  861. Value.dump();
  862. dbgs() << "-----\n";
  863. });
  864. auto PrevEntry = std::next(CurEntry);
  865. if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
  866. DebugLoc.pop_back();
  867. }
  868. }
  869. DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU,
  870. LexicalScope &Scope,
  871. InlinedVariable IV) {
  872. ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode());
  873. ConcreteVariables.push_back(
  874. llvm::make_unique<DbgVariable>(IV.first, IV.second));
  875. InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
  876. return ConcreteVariables.back().get();
  877. }
  878. /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
  879. /// enclosing lexical scope. The check ensures there are no other instructions
  880. /// in the same lexical scope preceding the DBG_VALUE and that its range is
  881. /// either open or otherwise rolls off the end of the scope.
  882. static bool validThroughout(LexicalScopes &LScopes,
  883. const MachineInstr *DbgValue,
  884. const MachineInstr *RangeEnd) {
  885. assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
  886. auto MBB = DbgValue->getParent();
  887. auto DL = DbgValue->getDebugLoc();
  888. auto *LScope = LScopes.findLexicalScope(DL);
  889. // Scope doesn't exist; this is a dead DBG_VALUE.
  890. if (!LScope)
  891. return false;
  892. auto &LSRange = LScope->getRanges();
  893. if (LSRange.size() == 0)
  894. return false;
  895. // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
  896. const MachineInstr *LScopeBegin = LSRange.front().first;
  897. // Early exit if the lexical scope begins outside of the current block.
  898. if (LScopeBegin->getParent() != MBB)
  899. return false;
  900. MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
  901. for (++Pred; Pred != MBB->rend(); ++Pred) {
  902. if (Pred->getFlag(MachineInstr::FrameSetup))
  903. break;
  904. auto PredDL = Pred->getDebugLoc();
  905. if (!PredDL || Pred->isMetaInstruction())
  906. continue;
  907. // Check whether the instruction preceding the DBG_VALUE is in the same
  908. // (sub)scope as the DBG_VALUE.
  909. if (DL->getScope() == PredDL->getScope())
  910. return false;
  911. auto *PredScope = LScopes.findLexicalScope(PredDL);
  912. if (!PredScope || LScope->dominates(PredScope))
  913. return false;
  914. }
  915. // If the range of the DBG_VALUE is open-ended, report success.
  916. if (!RangeEnd)
  917. return true;
  918. // Fail if there are instructions belonging to our scope in another block.
  919. const MachineInstr *LScopeEnd = LSRange.back().second;
  920. if (LScopeEnd->getParent() != MBB)
  921. return false;
  922. // Single, constant DBG_VALUEs in the prologue are promoted to be live
  923. // throughout the function. This is a hack, presumably for DWARF v2 and not
  924. // necessarily correct. It would be much better to use a dbg.declare instead
  925. // if we know the constant is live throughout the scope.
  926. if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
  927. return true;
  928. return false;
  929. }
  930. // Find variables for each lexical scope.
  931. void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
  932. const DISubprogram *SP,
  933. DenseSet<InlinedVariable> &Processed) {
  934. // Grab the variable info that was squirreled away in the MMI side-table.
  935. collectVariableInfoFromMFTable(TheCU, Processed);
  936. for (const auto &I : DbgValues) {
  937. InlinedVariable IV = I.first;
  938. if (Processed.count(IV))
  939. continue;
  940. // Instruction ranges, specifying where IV is accessible.
  941. const auto &Ranges = I.second;
  942. if (Ranges.empty())
  943. continue;
  944. LexicalScope *Scope = nullptr;
  945. if (const DILocation *IA = IV.second)
  946. Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
  947. else
  948. Scope = LScopes.findLexicalScope(IV.first->getScope());
  949. // If variable scope is not found then skip this variable.
  950. if (!Scope)
  951. continue;
  952. Processed.insert(IV);
  953. DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV);
  954. const MachineInstr *MInsn = Ranges.front().first;
  955. assert(MInsn->isDebugValue() && "History must begin with debug value");
  956. // Check if there is a single DBG_VALUE, valid throughout the var's scope.
  957. if (Ranges.size() == 1 &&
  958. validThroughout(LScopes, MInsn, Ranges.front().second)) {
  959. RegVar->initializeDbgValue(MInsn);
  960. continue;
  961. }
  962. // Handle multiple DBG_VALUE instructions describing one variable.
  963. DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
  964. // Build the location list for this variable.
  965. SmallVector<DebugLocEntry, 8> Entries;
  966. buildLocationList(Entries, Ranges);
  967. // If the variable has a DIBasicType, extract it. Basic types cannot have
  968. // unique identifiers, so don't bother resolving the type with the
  969. // identifier map.
  970. const DIBasicType *BT = dyn_cast<DIBasicType>(
  971. static_cast<const Metadata *>(IV.first->getType()));
  972. // Finalize the entry by lowering it into a DWARF bytestream.
  973. for (auto &Entry : Entries)
  974. Entry.finalize(*Asm, List, BT);
  975. }
  976. // Collect info for variables that were optimized out.
  977. for (const DILocalVariable *DV : SP->getVariables()) {
  978. if (Processed.insert(InlinedVariable(DV, nullptr)).second)
  979. if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
  980. createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr));
  981. }
  982. }
  983. // Process beginning of an instruction.
  984. void DwarfDebug::beginInstruction(const MachineInstr *MI) {
  985. DebugHandlerBase::beginInstruction(MI);
  986. assert(CurMI);
  987. const auto *SP = MI->getMF()->getFunction()->getSubprogram();
  988. if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
  989. return;
  990. // Check if source location changes, but ignore DBG_VALUE and CFI locations.
  991. if (MI->isMetaInstruction())
  992. return;
  993. const DebugLoc &DL = MI->getDebugLoc();
  994. // When we emit a line-0 record, we don't update PrevInstLoc; so look at
  995. // the last line number actually emitted, to see if it was line 0.
  996. unsigned LastAsmLine =
  997. Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
  998. if (DL == PrevInstLoc) {
  999. // If we have an ongoing unspecified location, nothing to do here.
  1000. if (!DL)
  1001. return;
  1002. // We have an explicit location, same as the previous location.
  1003. // But we might be coming back to it after a line 0 record.
  1004. if (LastAsmLine == 0 && DL.getLine() != 0) {
  1005. // Reinstate the source location but not marked as a statement.
  1006. const MDNode *Scope = DL.getScope();
  1007. recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
  1008. }
  1009. return;
  1010. }
  1011. if (!DL) {
  1012. // We have an unspecified location, which might want to be line 0.
  1013. // If we have already emitted a line-0 record, don't repeat it.
  1014. if (LastAsmLine == 0)
  1015. return;
  1016. // If user said Don't Do That, don't do that.
  1017. if (UnknownLocations == Disable)
  1018. return;
  1019. // See if we have a reason to emit a line-0 record now.
  1020. // Reasons to emit a line-0 record include:
  1021. // - User asked for it (UnknownLocations).
  1022. // - Instruction has a label, so it's referenced from somewhere else,
  1023. // possibly debug information; we want it to have a source location.
  1024. // - Instruction is at the top of a block; we don't want to inherit the
  1025. // location from the physically previous (maybe unrelated) block.
  1026. if (UnknownLocations == Enable || PrevLabel ||
  1027. (PrevInstBB && PrevInstBB != MI->getParent())) {
  1028. // Preserve the file and column numbers, if we can, to save space in
  1029. // the encoded line table.
  1030. // Do not update PrevInstLoc, it remembers the last non-0 line.
  1031. const MDNode *Scope = nullptr;
  1032. unsigned Column = 0;
  1033. if (PrevInstLoc) {
  1034. Scope = PrevInstLoc.getScope();
  1035. Column = PrevInstLoc.getCol();
  1036. }
  1037. recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
  1038. }
  1039. return;
  1040. }
  1041. // We have an explicit location, different from the previous location.
  1042. // Don't repeat a line-0 record, but otherwise emit the new location.
  1043. // (The new location might be an explicit line 0, which we do emit.)
  1044. if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
  1045. return;
  1046. unsigned Flags = 0;
  1047. if (DL == PrologEndLoc) {
  1048. Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
  1049. PrologEndLoc = DebugLoc();
  1050. }
  1051. // If the line changed, we call that a new statement; unless we went to
  1052. // line 0 and came back, in which case it is not a new statement.
  1053. unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
  1054. if (DL.getLine() && DL.getLine() != OldLine)
  1055. Flags |= DWARF2_FLAG_IS_STMT;
  1056. const MDNode *Scope = DL.getScope();
  1057. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  1058. // If we're not at line 0, remember this location.
  1059. if (DL.getLine())
  1060. PrevInstLoc = DL;
  1061. }
  1062. static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
  1063. // First known non-DBG_VALUE and non-frame setup location marks
  1064. // the beginning of the function body.
  1065. for (const auto &MBB : *MF)
  1066. for (const auto &MI : MBB)
  1067. if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1068. MI.getDebugLoc())
  1069. return MI.getDebugLoc();
  1070. return DebugLoc();
  1071. }
  1072. // Gather pre-function debug information. Assumes being called immediately
  1073. // after the function entry point has been emitted.
  1074. void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
  1075. CurFn = MF;
  1076. auto *SP = MF->getFunction()->getSubprogram();
  1077. assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
  1078. if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
  1079. return;
  1080. DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
  1081. // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
  1082. // belongs to so that we add to the correct per-cu line table in the
  1083. // non-asm case.
  1084. if (Asm->OutStreamer->hasRawTextSupport())
  1085. // Use a single line table if we are generating assembly.
  1086. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  1087. else
  1088. Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
  1089. // Record beginning of function.
  1090. PrologEndLoc = findPrologueEndLoc(MF);
  1091. if (PrologEndLoc) {
  1092. // We'd like to list the prologue as "not statements" but GDB behaves
  1093. // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
  1094. auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
  1095. recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
  1096. }
  1097. }
  1098. void DwarfDebug::skippedNonDebugFunction() {
  1099. // If we don't have a subprogram for this function then there will be a hole
  1100. // in the range information. Keep note of this by setting the previously used
  1101. // section to nullptr.
  1102. PrevCU = nullptr;
  1103. CurFn = nullptr;
  1104. }
  1105. // Gather and emit post-function debug information.
  1106. void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
  1107. const DISubprogram *SP = MF->getFunction()->getSubprogram();
  1108. assert(CurFn == MF &&
  1109. "endFunction should be called with the same function as beginFunction");
  1110. // Set DwarfDwarfCompileUnitID in MCContext to default value.
  1111. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  1112. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  1113. assert(!FnScope || SP == FnScope->getScopeNode());
  1114. DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
  1115. DenseSet<InlinedVariable> ProcessedVars;
  1116. collectVariableInfo(TheCU, SP, ProcessedVars);
  1117. // Add the range of this function to the list of ranges for the CU.
  1118. TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
  1119. // Under -gmlt, skip building the subprogram if there are no inlined
  1120. // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
  1121. // is still needed as we need its source location.
  1122. if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
  1123. TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
  1124. LScopes.getAbstractScopesList().empty() && !IsDarwin) {
  1125. assert(InfoHolder.getScopeVariables().empty());
  1126. PrevLabel = nullptr;
  1127. CurFn = nullptr;
  1128. return;
  1129. }
  1130. #ifndef NDEBUG
  1131. size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
  1132. #endif
  1133. // Construct abstract scopes.
  1134. for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
  1135. auto *SP = cast<DISubprogram>(AScope->getScopeNode());
  1136. // Collect info for variables that were optimized out.
  1137. for (const DILocalVariable *DV : SP->getVariables()) {
  1138. if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
  1139. continue;
  1140. ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr),
  1141. DV->getScope());
  1142. assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
  1143. && "ensureAbstractVariableIsCreated inserted abstract scopes");
  1144. }
  1145. constructAbstractSubprogramScopeDIE(TheCU, AScope);
  1146. }
  1147. ProcessedSPNodes.insert(SP);
  1148. TheCU.constructSubprogramScopeDIE(SP, FnScope);
  1149. if (auto *SkelCU = TheCU.getSkeleton())
  1150. if (!LScopes.getAbstractScopesList().empty() &&
  1151. TheCU.getCUNode()->getSplitDebugInlining())
  1152. SkelCU->constructSubprogramScopeDIE(SP, FnScope);
  1153. // Clear debug info
  1154. // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
  1155. // DbgVariables except those that are also in AbstractVariables (since they
  1156. // can be used cross-function)
  1157. InfoHolder.getScopeVariables().clear();
  1158. PrevLabel = nullptr;
  1159. CurFn = nullptr;
  1160. }
  1161. // Register a source line with debug info. Returns the unique label that was
  1162. // emitted and which provides correspondence to the source line list.
  1163. void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
  1164. unsigned Flags) {
  1165. StringRef Fn;
  1166. StringRef Dir;
  1167. unsigned Src = 1;
  1168. unsigned Discriminator = 0;
  1169. if (auto *Scope = cast_or_null<DIScope>(S)) {
  1170. Fn = Scope->getFilename();
  1171. Dir = Scope->getDirectory();
  1172. if (Line != 0 && getDwarfVersion() >= 4)
  1173. if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
  1174. Discriminator = LBF->getDiscriminator();
  1175. unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
  1176. Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
  1177. .getOrCreateSourceID(Fn, Dir);
  1178. }
  1179. Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
  1180. Discriminator, Fn);
  1181. }
  1182. //===----------------------------------------------------------------------===//
  1183. // Emit Methods
  1184. //===----------------------------------------------------------------------===//
  1185. // Emit the debug info section.
  1186. void DwarfDebug::emitDebugInfo() {
  1187. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1188. Holder.emitUnits(/* UseOffsets */ false);
  1189. }
  1190. // Emit the abbreviation section.
  1191. void DwarfDebug::emitAbbreviations() {
  1192. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1193. Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
  1194. }
  1195. void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
  1196. StringRef TableName) {
  1197. Accel.FinalizeTable(Asm, TableName);
  1198. Asm->OutStreamer->SwitchSection(Section);
  1199. // Emit the full data.
  1200. Accel.emit(Asm, Section->getBeginSymbol(), this);
  1201. }
  1202. // Emit visible names into a hashed accelerator table section.
  1203. void DwarfDebug::emitAccelNames() {
  1204. emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
  1205. "Names");
  1206. }
  1207. // Emit objective C classes and categories into a hashed accelerator table
  1208. // section.
  1209. void DwarfDebug::emitAccelObjC() {
  1210. emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
  1211. "ObjC");
  1212. }
  1213. // Emit namespace dies into a hashed accelerator table.
  1214. void DwarfDebug::emitAccelNamespaces() {
  1215. emitAccel(AccelNamespace,
  1216. Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
  1217. "namespac");
  1218. }
  1219. // Emit type dies into a hashed accelerator table.
  1220. void DwarfDebug::emitAccelTypes() {
  1221. emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
  1222. "types");
  1223. }
  1224. // Public name handling.
  1225. // The format for the various pubnames:
  1226. //
  1227. // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
  1228. // for the DIE that is named.
  1229. //
  1230. // gnu pubnames - offset/index value/name tuples where the offset is the offset
  1231. // into the CU and the index value is computed according to the type of value
  1232. // for the DIE that is named.
  1233. //
  1234. // For type units the offset is the offset of the skeleton DIE. For split dwarf
  1235. // it's the offset within the debug_info/debug_types dwo section, however, the
  1236. // reference in the pubname header doesn't change.
  1237. /// computeIndexValue - Compute the gdb index value for the DIE and CU.
  1238. static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
  1239. const DIE *Die) {
  1240. // Entities that ended up only in a Type Unit reference the CU instead (since
  1241. // the pub entry has offsets within the CU there's no real offset that can be
  1242. // provided anyway). As it happens all such entities (namespaces and types,
  1243. // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
  1244. // not to be true it would be necessary to persist this information from the
  1245. // point at which the entry is added to the index data structure - since by
  1246. // the time the index is built from that, the original type/namespace DIE in a
  1247. // type unit has already been destroyed so it can't be queried for properties
  1248. // like tag, etc.
  1249. if (Die->getTag() == dwarf::DW_TAG_compile_unit)
  1250. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
  1251. dwarf::GIEL_EXTERNAL);
  1252. dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
  1253. // We could have a specification DIE that has our most of our knowledge,
  1254. // look for that now.
  1255. if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
  1256. DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
  1257. if (SpecDIE.findAttribute(dwarf::DW_AT_external))
  1258. Linkage = dwarf::GIEL_EXTERNAL;
  1259. } else if (Die->findAttribute(dwarf::DW_AT_external))
  1260. Linkage = dwarf::GIEL_EXTERNAL;
  1261. switch (Die->getTag()) {
  1262. case dwarf::DW_TAG_class_type:
  1263. case dwarf::DW_TAG_structure_type:
  1264. case dwarf::DW_TAG_union_type:
  1265. case dwarf::DW_TAG_enumeration_type:
  1266. return dwarf::PubIndexEntryDescriptor(
  1267. dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
  1268. ? dwarf::GIEL_STATIC
  1269. : dwarf::GIEL_EXTERNAL);
  1270. case dwarf::DW_TAG_typedef:
  1271. case dwarf::DW_TAG_base_type:
  1272. case dwarf::DW_TAG_subrange_type:
  1273. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
  1274. case dwarf::DW_TAG_namespace:
  1275. return dwarf::GIEK_TYPE;
  1276. case dwarf::DW_TAG_subprogram:
  1277. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
  1278. case dwarf::DW_TAG_variable:
  1279. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
  1280. case dwarf::DW_TAG_enumerator:
  1281. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
  1282. dwarf::GIEL_STATIC);
  1283. default:
  1284. return dwarf::GIEK_NONE;
  1285. }
  1286. }
  1287. /// emitDebugPubSections - Emit visible names and types into debug pubnames and
  1288. /// pubtypes sections.
  1289. void DwarfDebug::emitDebugPubSections() {
  1290. for (const auto &NU : CUMap) {
  1291. DwarfCompileUnit *TheU = NU.second;
  1292. if (!TheU->hasDwarfPubSections())
  1293. continue;
  1294. bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
  1295. Asm->OutStreamer->SwitchSection(
  1296. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
  1297. : Asm->getObjFileLowering().getDwarfPubNamesSection());
  1298. emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
  1299. Asm->OutStreamer->SwitchSection(
  1300. GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
  1301. : Asm->getObjFileLowering().getDwarfPubTypesSection());
  1302. emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
  1303. }
  1304. }
  1305. void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
  1306. DwarfCompileUnit *TheU,
  1307. const StringMap<const DIE *> &Globals) {
  1308. if (auto *Skeleton = TheU->getSkeleton())
  1309. TheU = Skeleton;
  1310. // Emit the header.
  1311. Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
  1312. MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
  1313. MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
  1314. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
  1315. Asm->OutStreamer->EmitLabel(BeginLabel);
  1316. Asm->OutStreamer->AddComment("DWARF Version");
  1317. Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
  1318. Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
  1319. Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
  1320. Asm->OutStreamer->AddComment("Compilation Unit Length");
  1321. Asm->EmitInt32(TheU->getLength());
  1322. // Emit the pubnames for this compilation unit.
  1323. for (const auto &GI : Globals) {
  1324. const char *Name = GI.getKeyData();
  1325. const DIE *Entity = GI.second;
  1326. Asm->OutStreamer->AddComment("DIE offset");
  1327. Asm->EmitInt32(Entity->getOffset());
  1328. if (GnuStyle) {
  1329. dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
  1330. Asm->OutStreamer->AddComment(
  1331. Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
  1332. dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
  1333. Asm->EmitInt8(Desc.toBits());
  1334. }
  1335. Asm->OutStreamer->AddComment("External Name");
  1336. Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
  1337. }
  1338. Asm->OutStreamer->AddComment("End Mark");
  1339. Asm->EmitInt32(0);
  1340. Asm->OutStreamer->EmitLabel(EndLabel);
  1341. }
  1342. /// Emit null-terminated strings into a debug str section.
  1343. void DwarfDebug::emitDebugStr() {
  1344. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1345. Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
  1346. }
  1347. void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
  1348. const DebugLocStream::Entry &Entry) {
  1349. auto &&Comments = DebugLocs.getComments(Entry);
  1350. auto Comment = Comments.begin();
  1351. auto End = Comments.end();
  1352. for (uint8_t Byte : DebugLocs.getBytes(Entry))
  1353. Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
  1354. }
  1355. static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
  1356. ByteStreamer &Streamer,
  1357. const DebugLocEntry::Value &Value,
  1358. DwarfExpression &DwarfExpr) {
  1359. auto *DIExpr = Value.getExpression();
  1360. DIExpressionCursor ExprCursor(DIExpr);
  1361. DwarfExpr.addFragmentOffset(DIExpr);
  1362. // Regular entry.
  1363. if (Value.isInt()) {
  1364. if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
  1365. BT->getEncoding() == dwarf::DW_ATE_signed_char))
  1366. DwarfExpr.addSignedConstant(Value.getInt());
  1367. else
  1368. DwarfExpr.addUnsignedConstant(Value.getInt());
  1369. } else if (Value.isLocation()) {
  1370. MachineLocation Location = Value.getLoc();
  1371. if (Location.isIndirect())
  1372. DwarfExpr.setMemoryLocationKind();
  1373. DIExpressionCursor Cursor(DIExpr);
  1374. const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
  1375. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  1376. return;
  1377. return DwarfExpr.addExpression(std::move(Cursor));
  1378. } else if (Value.isConstantFP()) {
  1379. APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
  1380. DwarfExpr.addUnsignedConstant(RawBytes);
  1381. }
  1382. DwarfExpr.addExpression(std::move(ExprCursor));
  1383. }
  1384. void DebugLocEntry::finalize(const AsmPrinter &AP,
  1385. DebugLocStream::ListBuilder &List,
  1386. const DIBasicType *BT) {
  1387. DebugLocStream::EntryBuilder Entry(List, Begin, End);
  1388. BufferByteStreamer Streamer = Entry.getStreamer();
  1389. DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
  1390. const DebugLocEntry::Value &Value = Values[0];
  1391. if (Value.isFragment()) {
  1392. // Emit all fragments that belong to the same variable and range.
  1393. assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
  1394. return P.isFragment();
  1395. }) && "all values are expected to be fragments");
  1396. assert(std::is_sorted(Values.begin(), Values.end()) &&
  1397. "fragments are expected to be sorted");
  1398. for (auto Fragment : Values)
  1399. emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
  1400. } else {
  1401. assert(Values.size() == 1 && "only fragments may have >1 value");
  1402. emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
  1403. }
  1404. DwarfExpr.finalize();
  1405. }
  1406. void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
  1407. // Emit the size.
  1408. Asm->OutStreamer->AddComment("Loc expr size");
  1409. Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
  1410. // Emit the entry.
  1411. APByteStreamer Streamer(*Asm);
  1412. emitDebugLocEntry(Streamer, Entry);
  1413. }
  1414. // Emit locations into the debug loc section.
  1415. void DwarfDebug::emitDebugLoc() {
  1416. if (DebugLocs.getLists().empty())
  1417. return;
  1418. // Start the dwarf loc section.
  1419. Asm->OutStreamer->SwitchSection(
  1420. Asm->getObjFileLowering().getDwarfLocSection());
  1421. unsigned char Size = Asm->MAI->getCodePointerSize();
  1422. for (const auto &List : DebugLocs.getLists()) {
  1423. Asm->OutStreamer->EmitLabel(List.Label);
  1424. const DwarfCompileUnit *CU = List.CU;
  1425. for (const auto &Entry : DebugLocs.getEntries(List)) {
  1426. // Set up the range. This range is relative to the entry point of the
  1427. // compile unit. This is a hard coded 0 for low_pc when we're emitting
  1428. // ranges, or the DW_AT_low_pc on the compile unit otherwise.
  1429. if (auto *Base = CU->getBaseAddress()) {
  1430. Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
  1431. Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
  1432. } else {
  1433. Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
  1434. Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
  1435. }
  1436. emitDebugLocEntryLocation(Entry);
  1437. }
  1438. Asm->OutStreamer->EmitIntValue(0, Size);
  1439. Asm->OutStreamer->EmitIntValue(0, Size);
  1440. }
  1441. }
  1442. void DwarfDebug::emitDebugLocDWO() {
  1443. Asm->OutStreamer->SwitchSection(
  1444. Asm->getObjFileLowering().getDwarfLocDWOSection());
  1445. for (const auto &List : DebugLocs.getLists()) {
  1446. Asm->OutStreamer->EmitLabel(List.Label);
  1447. for (const auto &Entry : DebugLocs.getEntries(List)) {
  1448. // Just always use start_length for now - at least that's one address
  1449. // rather than two. We could get fancier and try to, say, reuse an
  1450. // address we know we've emitted elsewhere (the start of the function?
  1451. // The start of the CU or CU subrange that encloses this range?)
  1452. Asm->EmitInt8(dwarf::DW_LLE_startx_length);
  1453. unsigned idx = AddrPool.getIndex(Entry.BeginSym);
  1454. Asm->EmitULEB128(idx);
  1455. Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
  1456. emitDebugLocEntryLocation(Entry);
  1457. }
  1458. Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
  1459. }
  1460. }
  1461. struct ArangeSpan {
  1462. const MCSymbol *Start, *End;
  1463. };
  1464. // Emit a debug aranges section, containing a CU lookup for any
  1465. // address we can tie back to a CU.
  1466. void DwarfDebug::emitDebugARanges() {
  1467. // Provides a unique id per text section.
  1468. MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
  1469. // Filter labels by section.
  1470. for (const SymbolCU &SCU : ArangeLabels) {
  1471. if (SCU.Sym->isInSection()) {
  1472. // Make a note of this symbol and it's section.
  1473. MCSection *Section = &SCU.Sym->getSection();
  1474. if (!Section->getKind().isMetadata())
  1475. SectionMap[Section].push_back(SCU);
  1476. } else {
  1477. // Some symbols (e.g. common/bss on mach-o) can have no section but still
  1478. // appear in the output. This sucks as we rely on sections to build
  1479. // arange spans. We can do it without, but it's icky.
  1480. SectionMap[nullptr].push_back(SCU);
  1481. }
  1482. }
  1483. DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
  1484. for (auto &I : SectionMap) {
  1485. MCSection *Section = I.first;
  1486. SmallVector<SymbolCU, 8> &List = I.second;
  1487. if (List.size() < 1)
  1488. continue;
  1489. // If we have no section (e.g. common), just write out
  1490. // individual spans for each symbol.
  1491. if (!Section) {
  1492. for (const SymbolCU &Cur : List) {
  1493. ArangeSpan Span;
  1494. Span.Start = Cur.Sym;
  1495. Span.End = nullptr;
  1496. assert(Cur.CU);
  1497. Spans[Cur.CU].push_back(Span);
  1498. }
  1499. continue;
  1500. }
  1501. // Sort the symbols by offset within the section.
  1502. std::sort(
  1503. List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
  1504. unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
  1505. unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
  1506. // Symbols with no order assigned should be placed at the end.
  1507. // (e.g. section end labels)
  1508. if (IA == 0)
  1509. return false;
  1510. if (IB == 0)
  1511. return true;
  1512. return IA < IB;
  1513. });
  1514. // Insert a final terminator.
  1515. List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
  1516. // Build spans between each label.
  1517. const MCSymbol *StartSym = List[0].Sym;
  1518. for (size_t n = 1, e = List.size(); n < e; n++) {
  1519. const SymbolCU &Prev = List[n - 1];
  1520. const SymbolCU &Cur = List[n];
  1521. // Try and build the longest span we can within the same CU.
  1522. if (Cur.CU != Prev.CU) {
  1523. ArangeSpan Span;
  1524. Span.Start = StartSym;
  1525. Span.End = Cur.Sym;
  1526. assert(Prev.CU);
  1527. Spans[Prev.CU].push_back(Span);
  1528. StartSym = Cur.Sym;
  1529. }
  1530. }
  1531. }
  1532. // Start the dwarf aranges section.
  1533. Asm->OutStreamer->SwitchSection(
  1534. Asm->getObjFileLowering().getDwarfARangesSection());
  1535. unsigned PtrSize = Asm->MAI->getCodePointerSize();
  1536. // Build a list of CUs used.
  1537. std::vector<DwarfCompileUnit *> CUs;
  1538. for (const auto &it : Spans) {
  1539. DwarfCompileUnit *CU = it.first;
  1540. CUs.push_back(CU);
  1541. }
  1542. // Sort the CU list (again, to ensure consistent output order).
  1543. std::sort(CUs.begin(), CUs.end(),
  1544. [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
  1545. return A->getUniqueID() < B->getUniqueID();
  1546. });
  1547. // Emit an arange table for each CU we used.
  1548. for (DwarfCompileUnit *CU : CUs) {
  1549. std::vector<ArangeSpan> &List = Spans[CU];
  1550. // Describe the skeleton CU's offset and length, not the dwo file's.
  1551. if (auto *Skel = CU->getSkeleton())
  1552. CU = Skel;
  1553. // Emit size of content not including length itself.
  1554. unsigned ContentSize =
  1555. sizeof(int16_t) + // DWARF ARange version number
  1556. sizeof(int32_t) + // Offset of CU in the .debug_info section
  1557. sizeof(int8_t) + // Pointer Size (in bytes)
  1558. sizeof(int8_t); // Segment Size (in bytes)
  1559. unsigned TupleSize = PtrSize * 2;
  1560. // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
  1561. unsigned Padding =
  1562. OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
  1563. ContentSize += Padding;
  1564. ContentSize += (List.size() + 1) * TupleSize;
  1565. // For each compile unit, write the list of spans it covers.
  1566. Asm->OutStreamer->AddComment("Length of ARange Set");
  1567. Asm->EmitInt32(ContentSize);
  1568. Asm->OutStreamer->AddComment("DWARF Arange version number");
  1569. Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
  1570. Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
  1571. Asm->emitDwarfSymbolReference(CU->getLabelBegin());
  1572. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1573. Asm->EmitInt8(PtrSize);
  1574. Asm->OutStreamer->AddComment("Segment Size (in bytes)");
  1575. Asm->EmitInt8(0);
  1576. Asm->OutStreamer->emitFill(Padding, 0xff);
  1577. for (const ArangeSpan &Span : List) {
  1578. Asm->EmitLabelReference(Span.Start, PtrSize);
  1579. // Calculate the size as being from the span start to it's end.
  1580. if (Span.End) {
  1581. Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
  1582. } else {
  1583. // For symbols without an end marker (e.g. common), we
  1584. // write a single arange entry containing just that one symbol.
  1585. uint64_t Size = SymSize[Span.Start];
  1586. if (Size == 0)
  1587. Size = 1;
  1588. Asm->OutStreamer->EmitIntValue(Size, PtrSize);
  1589. }
  1590. }
  1591. Asm->OutStreamer->AddComment("ARange terminator");
  1592. Asm->OutStreamer->EmitIntValue(0, PtrSize);
  1593. Asm->OutStreamer->EmitIntValue(0, PtrSize);
  1594. }
  1595. }
  1596. /// Emit address ranges into a debug ranges section.
  1597. void DwarfDebug::emitDebugRanges() {
  1598. if (CUMap.empty())
  1599. return;
  1600. // Start the dwarf ranges section.
  1601. Asm->OutStreamer->SwitchSection(
  1602. Asm->getObjFileLowering().getDwarfRangesSection());
  1603. // Size for our labels.
  1604. unsigned char Size = Asm->MAI->getCodePointerSize();
  1605. // Grab the specific ranges for the compile units in the module.
  1606. for (const auto &I : CUMap) {
  1607. DwarfCompileUnit *TheCU = I.second;
  1608. if (auto *Skel = TheCU->getSkeleton())
  1609. TheCU = Skel;
  1610. // Iterate over the misc ranges for the compile units in the module.
  1611. for (const RangeSpanList &List : TheCU->getRangeLists()) {
  1612. // Emit our symbol so we can find the beginning of the range.
  1613. Asm->OutStreamer->EmitLabel(List.getSym());
  1614. // Gather all the ranges that apply to the same section so they can share
  1615. // a base address entry.
  1616. MapVector<const MCSection *, std::vector<const RangeSpan *>> MV;
  1617. for (const RangeSpan &Range : List.getRanges()) {
  1618. MV[&Range.getStart()->getSection()].push_back(&Range);
  1619. }
  1620. auto *CUBase = TheCU->getBaseAddress();
  1621. bool BaseIsSet = false;
  1622. for (const auto &P : MV) {
  1623. // Don't bother with a base address entry if there's only one range in
  1624. // this section in this range list - for example ranges for a CU will
  1625. // usually consist of single regions from each of many sections
  1626. // (-ffunction-sections, or just C++ inline functions) except under LTO
  1627. // or optnone where there may be holes in a single CU's section
  1628. // contrubutions.
  1629. auto *Base = CUBase;
  1630. if (!Base && P.second.size() > 1 &&
  1631. UseDwarfRangesBaseAddressSpecifier) {
  1632. BaseIsSet = true;
  1633. // FIXME/use care: This may not be a useful base address if it's not
  1634. // the lowest address/range in this object.
  1635. Base = P.second.front()->getStart();
  1636. Asm->OutStreamer->EmitIntValue(-1, Size);
  1637. Asm->OutStreamer->EmitSymbolValue(Base, Size);
  1638. } else if (BaseIsSet) {
  1639. BaseIsSet = false;
  1640. Asm->OutStreamer->EmitIntValue(-1, Size);
  1641. Asm->OutStreamer->EmitIntValue(0, Size);
  1642. }
  1643. for (const auto *RS : P.second) {
  1644. const MCSymbol *Begin = RS->getStart();
  1645. const MCSymbol *End = RS->getEnd();
  1646. assert(Begin && "Range without a begin symbol?");
  1647. assert(End && "Range without an end symbol?");
  1648. if (Base) {
  1649. Asm->EmitLabelDifference(Begin, Base, Size);
  1650. Asm->EmitLabelDifference(End, Base, Size);
  1651. } else {
  1652. Asm->OutStreamer->EmitSymbolValue(Begin, Size);
  1653. Asm->OutStreamer->EmitSymbolValue(End, Size);
  1654. }
  1655. }
  1656. }
  1657. // And terminate the list with two 0 values.
  1658. Asm->OutStreamer->EmitIntValue(0, Size);
  1659. Asm->OutStreamer->EmitIntValue(0, Size);
  1660. }
  1661. }
  1662. }
  1663. void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
  1664. for (auto *MN : Nodes) {
  1665. if (auto *M = dyn_cast<DIMacro>(MN))
  1666. emitMacro(*M);
  1667. else if (auto *F = dyn_cast<DIMacroFile>(MN))
  1668. emitMacroFile(*F, U);
  1669. else
  1670. llvm_unreachable("Unexpected DI type!");
  1671. }
  1672. }
  1673. void DwarfDebug::emitMacro(DIMacro &M) {
  1674. Asm->EmitULEB128(M.getMacinfoType());
  1675. Asm->EmitULEB128(M.getLine());
  1676. StringRef Name = M.getName();
  1677. StringRef Value = M.getValue();
  1678. Asm->OutStreamer->EmitBytes(Name);
  1679. if (!Value.empty()) {
  1680. // There should be one space between macro name and macro value.
  1681. Asm->EmitInt8(' ');
  1682. Asm->OutStreamer->EmitBytes(Value);
  1683. }
  1684. Asm->EmitInt8('\0');
  1685. }
  1686. void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
  1687. assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
  1688. Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
  1689. Asm->EmitULEB128(F.getLine());
  1690. DIFile *File = F.getFile();
  1691. unsigned FID =
  1692. U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
  1693. Asm->EmitULEB128(FID);
  1694. handleMacroNodes(F.getElements(), U);
  1695. Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
  1696. }
  1697. /// Emit macros into a debug macinfo section.
  1698. void DwarfDebug::emitDebugMacinfo() {
  1699. if (CUMap.empty())
  1700. return;
  1701. // Start the dwarf macinfo section.
  1702. Asm->OutStreamer->SwitchSection(
  1703. Asm->getObjFileLowering().getDwarfMacinfoSection());
  1704. for (const auto &P : CUMap) {
  1705. auto &TheCU = *P.second;
  1706. auto *SkCU = TheCU.getSkeleton();
  1707. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  1708. auto *CUNode = cast<DICompileUnit>(P.first);
  1709. Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
  1710. handleMacroNodes(CUNode->getMacros(), U);
  1711. }
  1712. Asm->OutStreamer->AddComment("End Of Macro List Mark");
  1713. Asm->EmitInt8(0);
  1714. }
  1715. // DWARF5 Experimental Separate Dwarf emitters.
  1716. void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  1717. std::unique_ptr<DwarfCompileUnit> NewU) {
  1718. NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
  1719. Asm->TM.Options.MCOptions.SplitDwarfFile);
  1720. if (!CompilationDir.empty())
  1721. NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  1722. addGnuPubAttributes(*NewU, Die);
  1723. SkeletonHolder.addUnit(std::move(NewU));
  1724. }
  1725. // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
  1726. // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
  1727. // DW_AT_addr_base, DW_AT_ranges_base.
  1728. DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
  1729. auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
  1730. CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
  1731. DwarfCompileUnit &NewCU = *OwnedUnit;
  1732. NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
  1733. NewCU.initStmtList();
  1734. initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
  1735. return NewCU;
  1736. }
  1737. // Emit the .debug_info.dwo section for separated dwarf. This contains the
  1738. // compile units that would normally be in debug_info.
  1739. void DwarfDebug::emitDebugInfoDWO() {
  1740. assert(useSplitDwarf() && "No split dwarf debug info?");
  1741. // Don't emit relocations into the dwo file.
  1742. InfoHolder.emitUnits(/* UseOffsets */ true);
  1743. }
  1744. // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
  1745. // abbreviations for the .debug_info.dwo section.
  1746. void DwarfDebug::emitDebugAbbrevDWO() {
  1747. assert(useSplitDwarf() && "No split dwarf?");
  1748. InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
  1749. }
  1750. void DwarfDebug::emitDebugLineDWO() {
  1751. assert(useSplitDwarf() && "No split dwarf?");
  1752. Asm->OutStreamer->SwitchSection(
  1753. Asm->getObjFileLowering().getDwarfLineDWOSection());
  1754. SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
  1755. }
  1756. // Emit the .debug_str.dwo section for separated dwarf. This contains the
  1757. // string section and is identical in format to traditional .debug_str
  1758. // sections.
  1759. void DwarfDebug::emitDebugStrDWO() {
  1760. assert(useSplitDwarf() && "No split dwarf?");
  1761. MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
  1762. InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
  1763. OffSec);
  1764. }
  1765. MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
  1766. if (!useSplitDwarf())
  1767. return nullptr;
  1768. if (SingleCU)
  1769. SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
  1770. return &SplitTypeUnitFileTable;
  1771. }
  1772. uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
  1773. MD5 Hash;
  1774. Hash.update(Identifier);
  1775. // ... take the least significant 8 bytes and return those. Our MD5
  1776. // implementation always returns its results in little endian, so we actually
  1777. // need the "high" word.
  1778. MD5::MD5Result Result;
  1779. Hash.final(Result);
  1780. return Result.high();
  1781. }
  1782. void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
  1783. StringRef Identifier, DIE &RefDie,
  1784. const DICompositeType *CTy) {
  1785. // Fast path if we're building some type units and one has already used the
  1786. // address pool we know we're going to throw away all this work anyway, so
  1787. // don't bother building dependent types.
  1788. if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
  1789. return;
  1790. auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
  1791. if (!Ins.second) {
  1792. CU.addDIETypeSignature(RefDie, Ins.first->second);
  1793. return;
  1794. }
  1795. bool TopLevelType = TypeUnitsUnderConstruction.empty();
  1796. AddrPool.resetUsedFlag();
  1797. auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
  1798. getDwoLineTable(CU));
  1799. DwarfTypeUnit &NewTU = *OwnedUnit;
  1800. DIE &UnitDie = NewTU.getUnitDie();
  1801. TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
  1802. NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  1803. CU.getLanguage());
  1804. uint64_t Signature = makeTypeSignature(Identifier);
  1805. NewTU.setTypeSignature(Signature);
  1806. Ins.first->second = Signature;
  1807. if (useSplitDwarf())
  1808. NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
  1809. else {
  1810. CU.applyStmtList(UnitDie);
  1811. NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
  1812. }
  1813. NewTU.setType(NewTU.createTypeDIE(CTy));
  1814. if (TopLevelType) {
  1815. auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
  1816. TypeUnitsUnderConstruction.clear();
  1817. // Types referencing entries in the address table cannot be placed in type
  1818. // units.
  1819. if (AddrPool.hasBeenUsed()) {
  1820. // Remove all the types built while building this type.
  1821. // This is pessimistic as some of these types might not be dependent on
  1822. // the type that used an address.
  1823. for (const auto &TU : TypeUnitsToAdd)
  1824. TypeSignatures.erase(TU.second);
  1825. // Construct this type in the CU directly.
  1826. // This is inefficient because all the dependent types will be rebuilt
  1827. // from scratch, including building them in type units, discovering that
  1828. // they depend on addresses, throwing them out and rebuilding them.
  1829. CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
  1830. return;
  1831. }
  1832. // If the type wasn't dependent on fission addresses, finish adding the type
  1833. // and all its dependent types.
  1834. for (auto &TU : TypeUnitsToAdd) {
  1835. InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
  1836. InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
  1837. }
  1838. }
  1839. CU.addDIETypeSignature(RefDie, Signature);
  1840. }
  1841. // Accelerator table mutators - add each name along with its companion
  1842. // DIE to the proper table while ensuring that the name that we're going
  1843. // to reference is in the string table. We do this since the names we
  1844. // add may not only be identical to the names in the DIE.
  1845. void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
  1846. if (!useDwarfAccelTables())
  1847. return;
  1848. AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1849. }
  1850. void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
  1851. if (!useDwarfAccelTables())
  1852. return;
  1853. AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1854. }
  1855. void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
  1856. if (!useDwarfAccelTables())
  1857. return;
  1858. AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1859. }
  1860. void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
  1861. if (!useDwarfAccelTables())
  1862. return;
  1863. AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1864. }
  1865. uint16_t DwarfDebug::getDwarfVersion() const {
  1866. return Asm->OutStreamer->getContext().getDwarfVersion();
  1867. }