CodeViewDebug.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  1. //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
  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 Microsoft CodeView debug info.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeViewDebug.h"
  14. #include "llvm/ADT/TinyPtrVector.h"
  15. #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
  16. #include "llvm/DebugInfo/CodeView/CodeView.h"
  17. #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
  18. #include "llvm/DebugInfo/CodeView/Line.h"
  19. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  20. #include "llvm/DebugInfo/CodeView/TypeDumper.h"
  21. #include "llvm/DebugInfo/CodeView/TypeIndex.h"
  22. #include "llvm/DebugInfo/CodeView/TypeRecord.h"
  23. #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
  24. #include "llvm/DebugInfo/MSF/ByteStream.h"
  25. #include "llvm/DebugInfo/MSF/StreamReader.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/MC/MCAsmInfo.h"
  28. #include "llvm/MC/MCExpr.h"
  29. #include "llvm/MC/MCSectionCOFF.h"
  30. #include "llvm/MC/MCSymbol.h"
  31. #include "llvm/Support/COFF.h"
  32. #include "llvm/Support/ScopedPrinter.h"
  33. #include "llvm/Target/TargetFrameLowering.h"
  34. #include "llvm/Target/TargetRegisterInfo.h"
  35. #include "llvm/Target/TargetSubtargetInfo.h"
  36. using namespace llvm;
  37. using namespace llvm::codeview;
  38. using namespace llvm::msf;
  39. CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
  40. : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
  41. TypeTable(Allocator), CurFn(nullptr) {
  42. // If module doesn't have named metadata anchors or COFF debug section
  43. // is not available, skip any debug info related stuff.
  44. if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
  45. !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
  46. Asm = nullptr;
  47. return;
  48. }
  49. // Tell MMI that we have debug info.
  50. MMI->setDebugInfoAvailability(true);
  51. }
  52. StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
  53. std::string &Filepath = FileToFilepathMap[File];
  54. if (!Filepath.empty())
  55. return Filepath;
  56. StringRef Dir = File->getDirectory(), Filename = File->getFilename();
  57. // Clang emits directory and relative filename info into the IR, but CodeView
  58. // operates on full paths. We could change Clang to emit full paths too, but
  59. // that would increase the IR size and probably not needed for other users.
  60. // For now, just concatenate and canonicalize the path here.
  61. if (Filename.find(':') == 1)
  62. Filepath = Filename;
  63. else
  64. Filepath = (Dir + "\\" + Filename).str();
  65. // Canonicalize the path. We have to do it textually because we may no longer
  66. // have access the file in the filesystem.
  67. // First, replace all slashes with backslashes.
  68. std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
  69. // Remove all "\.\" with "\".
  70. size_t Cursor = 0;
  71. while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
  72. Filepath.erase(Cursor, 2);
  73. // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
  74. // path should be well-formatted, e.g. start with a drive letter, etc.
  75. Cursor = 0;
  76. while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
  77. // Something's wrong if the path starts with "\..\", abort.
  78. if (Cursor == 0)
  79. break;
  80. size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
  81. if (PrevSlash == std::string::npos)
  82. // Something's wrong, abort.
  83. break;
  84. Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
  85. // The next ".." might be following the one we've just erased.
  86. Cursor = PrevSlash;
  87. }
  88. // Remove all duplicate backslashes.
  89. Cursor = 0;
  90. while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
  91. Filepath.erase(Cursor, 1);
  92. return Filepath;
  93. }
  94. unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
  95. unsigned NextId = FileIdMap.size() + 1;
  96. auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
  97. if (Insertion.second) {
  98. // We have to compute the full filepath and emit a .cv_file directive.
  99. StringRef FullPath = getFullFilepath(F);
  100. bool Success = OS.EmitCVFileDirective(NextId, FullPath);
  101. (void)Success;
  102. assert(Success && ".cv_file directive failed");
  103. }
  104. return Insertion.first->second;
  105. }
  106. CodeViewDebug::InlineSite &
  107. CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
  108. const DISubprogram *Inlinee) {
  109. auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
  110. InlineSite *Site = &SiteInsertion.first->second;
  111. if (SiteInsertion.second) {
  112. unsigned ParentFuncId = CurFn->FuncId;
  113. if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
  114. ParentFuncId =
  115. getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
  116. .SiteFuncId;
  117. Site->SiteFuncId = NextFuncId++;
  118. OS.EmitCVInlineSiteIdDirective(
  119. Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
  120. InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
  121. Site->Inlinee = Inlinee;
  122. InlinedSubprograms.insert(Inlinee);
  123. getFuncIdForSubprogram(Inlinee);
  124. }
  125. return *Site;
  126. }
  127. static StringRef getPrettyScopeName(const DIScope *Scope) {
  128. StringRef ScopeName = Scope->getName();
  129. if (!ScopeName.empty())
  130. return ScopeName;
  131. switch (Scope->getTag()) {
  132. case dwarf::DW_TAG_enumeration_type:
  133. case dwarf::DW_TAG_class_type:
  134. case dwarf::DW_TAG_structure_type:
  135. case dwarf::DW_TAG_union_type:
  136. return "<unnamed-tag>";
  137. case dwarf::DW_TAG_namespace:
  138. return "`anonymous namespace'";
  139. }
  140. return StringRef();
  141. }
  142. static const DISubprogram *getQualifiedNameComponents(
  143. const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
  144. const DISubprogram *ClosestSubprogram = nullptr;
  145. while (Scope != nullptr) {
  146. if (ClosestSubprogram == nullptr)
  147. ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
  148. StringRef ScopeName = getPrettyScopeName(Scope);
  149. if (!ScopeName.empty())
  150. QualifiedNameComponents.push_back(ScopeName);
  151. Scope = Scope->getScope().resolve();
  152. }
  153. return ClosestSubprogram;
  154. }
  155. static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
  156. StringRef TypeName) {
  157. std::string FullyQualifiedName;
  158. for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
  159. FullyQualifiedName.append(QualifiedNameComponent);
  160. FullyQualifiedName.append("::");
  161. }
  162. FullyQualifiedName.append(TypeName);
  163. return FullyQualifiedName;
  164. }
  165. static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
  166. SmallVector<StringRef, 5> QualifiedNameComponents;
  167. getQualifiedNameComponents(Scope, QualifiedNameComponents);
  168. return getQualifiedName(QualifiedNameComponents, Name);
  169. }
  170. struct CodeViewDebug::TypeLoweringScope {
  171. TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
  172. ~TypeLoweringScope() {
  173. // Don't decrement TypeEmissionLevel until after emitting deferred types, so
  174. // inner TypeLoweringScopes don't attempt to emit deferred types.
  175. if (CVD.TypeEmissionLevel == 1)
  176. CVD.emitDeferredCompleteTypes();
  177. --CVD.TypeEmissionLevel;
  178. }
  179. CodeViewDebug &CVD;
  180. };
  181. static std::string getFullyQualifiedName(const DIScope *Ty) {
  182. const DIScope *Scope = Ty->getScope().resolve();
  183. return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
  184. }
  185. TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
  186. // No scope means global scope and that uses the zero index.
  187. if (!Scope || isa<DIFile>(Scope))
  188. return TypeIndex();
  189. assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
  190. // Check if we've already translated this scope.
  191. auto I = TypeIndices.find({Scope, nullptr});
  192. if (I != TypeIndices.end())
  193. return I->second;
  194. // Build the fully qualified name of the scope.
  195. std::string ScopeName = getFullyQualifiedName(Scope);
  196. TypeIndex TI =
  197. TypeTable.writeKnownType(StringIdRecord(TypeIndex(), ScopeName));
  198. return recordTypeIndexForDINode(Scope, TI);
  199. }
  200. TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
  201. assert(SP);
  202. // Check if we've already translated this subprogram.
  203. auto I = TypeIndices.find({SP, nullptr});
  204. if (I != TypeIndices.end())
  205. return I->second;
  206. // The display name includes function template arguments. Drop them to match
  207. // MSVC.
  208. StringRef DisplayName = SP->getDisplayName().split('<').first;
  209. const DIScope *Scope = SP->getScope().resolve();
  210. TypeIndex TI;
  211. if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
  212. // If the scope is a DICompositeType, then this must be a method. Member
  213. // function types take some special handling, and require access to the
  214. // subprogram.
  215. TypeIndex ClassType = getTypeIndex(Class);
  216. MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
  217. DisplayName);
  218. TI = TypeTable.writeKnownType(MFuncId);
  219. } else {
  220. // Otherwise, this must be a free function.
  221. TypeIndex ParentScope = getScopeIndex(Scope);
  222. FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
  223. TI = TypeTable.writeKnownType(FuncId);
  224. }
  225. return recordTypeIndexForDINode(SP, TI);
  226. }
  227. TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
  228. const DICompositeType *Class) {
  229. // Always use the method declaration as the key for the function type. The
  230. // method declaration contains the this adjustment.
  231. if (SP->getDeclaration())
  232. SP = SP->getDeclaration();
  233. assert(!SP->getDeclaration() && "should use declaration as key");
  234. // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
  235. // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
  236. auto I = TypeIndices.find({SP, Class});
  237. if (I != TypeIndices.end())
  238. return I->second;
  239. // Make sure complete type info for the class is emitted *after* the member
  240. // function type, as the complete class type is likely to reference this
  241. // member function type.
  242. TypeLoweringScope S(*this);
  243. TypeIndex TI =
  244. lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
  245. return recordTypeIndexForDINode(SP, TI, Class);
  246. }
  247. TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
  248. TypeIndex TI,
  249. const DIType *ClassTy) {
  250. auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
  251. (void)InsertResult;
  252. assert(InsertResult.second && "DINode was already assigned a type index");
  253. return TI;
  254. }
  255. unsigned CodeViewDebug::getPointerSizeInBytes() {
  256. return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
  257. }
  258. void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
  259. const DILocation *InlinedAt) {
  260. if (InlinedAt) {
  261. // This variable was inlined. Associate it with the InlineSite.
  262. const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
  263. InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
  264. Site.InlinedLocals.emplace_back(Var);
  265. } else {
  266. // This variable goes in the main ProcSym.
  267. CurFn->Locals.emplace_back(Var);
  268. }
  269. }
  270. static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
  271. const DILocation *Loc) {
  272. auto B = Locs.begin(), E = Locs.end();
  273. if (std::find(B, E, Loc) == E)
  274. Locs.push_back(Loc);
  275. }
  276. void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
  277. const MachineFunction *MF) {
  278. // Skip this instruction if it has the same location as the previous one.
  279. if (DL == CurFn->LastLoc)
  280. return;
  281. const DIScope *Scope = DL.get()->getScope();
  282. if (!Scope)
  283. return;
  284. // Skip this line if it is longer than the maximum we can record.
  285. LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
  286. if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
  287. LI.isNeverStepInto())
  288. return;
  289. ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
  290. if (CI.getStartColumn() != DL.getCol())
  291. return;
  292. if (!CurFn->HaveLineInfo)
  293. CurFn->HaveLineInfo = true;
  294. unsigned FileId = 0;
  295. if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
  296. FileId = CurFn->LastFileId;
  297. else
  298. FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
  299. CurFn->LastLoc = DL;
  300. unsigned FuncId = CurFn->FuncId;
  301. if (const DILocation *SiteLoc = DL->getInlinedAt()) {
  302. const DILocation *Loc = DL.get();
  303. // If this location was actually inlined from somewhere else, give it the ID
  304. // of the inline call site.
  305. FuncId =
  306. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
  307. // Ensure we have links in the tree of inline call sites.
  308. bool FirstLoc = true;
  309. while ((SiteLoc = Loc->getInlinedAt())) {
  310. InlineSite &Site =
  311. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
  312. if (!FirstLoc)
  313. addLocIfNotPresent(Site.ChildSites, Loc);
  314. FirstLoc = false;
  315. Loc = SiteLoc;
  316. }
  317. addLocIfNotPresent(CurFn->ChildSites, Loc);
  318. }
  319. OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
  320. /*PrologueEnd=*/false, /*IsStmt=*/false,
  321. DL->getFilename(), SMLoc());
  322. }
  323. void CodeViewDebug::emitCodeViewMagicVersion() {
  324. OS.EmitValueToAlignment(4);
  325. OS.AddComment("Debug section magic");
  326. OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
  327. }
  328. void CodeViewDebug::endModule() {
  329. if (!Asm || !MMI->hasDebugInfo())
  330. return;
  331. assert(Asm != nullptr);
  332. // The COFF .debug$S section consists of several subsections, each starting
  333. // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
  334. // of the payload followed by the payload itself. The subsections are 4-byte
  335. // aligned.
  336. // Use the generic .debug$S section, and make a subsection for all the inlined
  337. // subprograms.
  338. switchToDebugSectionForSymbol(nullptr);
  339. emitInlineeLinesSubsection();
  340. // Emit per-function debug information.
  341. for (auto &P : FnDebugInfo)
  342. if (!P.first->isDeclarationForLinker())
  343. emitDebugInfoForFunction(P.first, P.second);
  344. // Emit global variable debug information.
  345. setCurrentSubprogram(nullptr);
  346. emitDebugInfoForGlobals();
  347. // Emit retained types.
  348. emitDebugInfoForRetainedTypes();
  349. // Switch back to the generic .debug$S section after potentially processing
  350. // comdat symbol sections.
  351. switchToDebugSectionForSymbol(nullptr);
  352. // Emit UDT records for any types used by global variables.
  353. if (!GlobalUDTs.empty()) {
  354. MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
  355. emitDebugInfoForUDTs(GlobalUDTs);
  356. endCVSubsection(SymbolsEnd);
  357. }
  358. // This subsection holds a file index to offset in string table table.
  359. OS.AddComment("File index to string table offset subsection");
  360. OS.EmitCVFileChecksumsDirective();
  361. // This subsection holds the string table.
  362. OS.AddComment("String table");
  363. OS.EmitCVStringTableDirective();
  364. // Emit type information last, so that any types we translate while emitting
  365. // function info are included.
  366. emitTypeInformation();
  367. clear();
  368. }
  369. static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
  370. // Microsoft's linker seems to have trouble with symbol names longer than
  371. // 0xffd8 bytes.
  372. S = S.substr(0, 0xffd8);
  373. SmallString<32> NullTerminatedString(S);
  374. NullTerminatedString.push_back('\0');
  375. OS.EmitBytes(NullTerminatedString);
  376. }
  377. void CodeViewDebug::emitTypeInformation() {
  378. // Do nothing if we have no debug info or if no non-trivial types were emitted
  379. // to TypeTable during codegen.
  380. NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  381. if (!CU_Nodes)
  382. return;
  383. if (TypeTable.empty())
  384. return;
  385. // Start the .debug$T section with 0x4.
  386. OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
  387. emitCodeViewMagicVersion();
  388. SmallString<8> CommentPrefix;
  389. if (OS.isVerboseAsm()) {
  390. CommentPrefix += '\t';
  391. CommentPrefix += Asm->MAI->getCommentString();
  392. CommentPrefix += ' ';
  393. }
  394. CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
  395. TypeTable.ForEachRecord(
  396. [&](TypeIndex Index, StringRef Record) {
  397. if (OS.isVerboseAsm()) {
  398. // Emit a block comment describing the type record for readability.
  399. SmallString<512> CommentBlock;
  400. raw_svector_ostream CommentOS(CommentBlock);
  401. ScopedPrinter SP(CommentOS);
  402. SP.setPrefix(CommentPrefix);
  403. CVTD.setPrinter(&SP);
  404. Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
  405. if (E) {
  406. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  407. llvm_unreachable("produced malformed type record");
  408. }
  409. // emitRawComment will insert its own tab and comment string before
  410. // the first line, so strip off our first one. It also prints its own
  411. // newline.
  412. OS.emitRawComment(
  413. CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
  414. } else {
  415. #ifndef NDEBUG
  416. // Assert that the type data is valid even if we aren't dumping
  417. // comments. The MSVC linker doesn't do much type record validation,
  418. // so the first link of an invalid type record can succeed while
  419. // subsequent links will fail with LNK1285.
  420. ByteStream Stream({Record.bytes_begin(), Record.bytes_end()});
  421. CVTypeArray Types;
  422. StreamReader Reader(Stream);
  423. Error E = Reader.readArray(Types, Reader.getLength());
  424. if (!E) {
  425. TypeVisitorCallbacks C;
  426. E = CVTypeVisitor(C).visitTypeStream(Types);
  427. }
  428. if (E) {
  429. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  430. llvm_unreachable("produced malformed type record");
  431. }
  432. #endif
  433. }
  434. OS.EmitBinaryData(Record);
  435. });
  436. }
  437. void CodeViewDebug::emitInlineeLinesSubsection() {
  438. if (InlinedSubprograms.empty())
  439. return;
  440. OS.AddComment("Inlinee lines subsection");
  441. MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
  442. // We don't provide any extra file info.
  443. // FIXME: Find out if debuggers use this info.
  444. OS.AddComment("Inlinee lines signature");
  445. OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
  446. for (const DISubprogram *SP : InlinedSubprograms) {
  447. assert(TypeIndices.count({SP, nullptr}));
  448. TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
  449. OS.AddBlankLine();
  450. unsigned FileId = maybeRecordFile(SP->getFile());
  451. OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
  452. SP->getFilename() + Twine(':') + Twine(SP->getLine()));
  453. OS.AddBlankLine();
  454. // The filechecksum table uses 8 byte entries for now, and file ids start at
  455. // 1.
  456. unsigned FileOffset = (FileId - 1) * 8;
  457. OS.AddComment("Type index of inlined function");
  458. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  459. OS.AddComment("Offset into filechecksum table");
  460. OS.EmitIntValue(FileOffset, 4);
  461. OS.AddComment("Starting line number");
  462. OS.EmitIntValue(SP->getLine(), 4);
  463. }
  464. endCVSubsection(InlineEnd);
  465. }
  466. void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
  467. const DILocation *InlinedAt,
  468. const InlineSite &Site) {
  469. MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
  470. *InlineEnd = MMI->getContext().createTempSymbol();
  471. assert(TypeIndices.count({Site.Inlinee, nullptr}));
  472. TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
  473. // SymbolRecord
  474. OS.AddComment("Record length");
  475. OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
  476. OS.EmitLabel(InlineBegin);
  477. OS.AddComment("Record kind: S_INLINESITE");
  478. OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
  479. OS.AddComment("PtrParent");
  480. OS.EmitIntValue(0, 4);
  481. OS.AddComment("PtrEnd");
  482. OS.EmitIntValue(0, 4);
  483. OS.AddComment("Inlinee type index");
  484. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  485. unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
  486. unsigned StartLineNum = Site.Inlinee->getLine();
  487. OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
  488. FI.Begin, FI.End);
  489. OS.EmitLabel(InlineEnd);
  490. emitLocalVariableList(Site.InlinedLocals);
  491. // Recurse on child inlined call sites before closing the scope.
  492. for (const DILocation *ChildSite : Site.ChildSites) {
  493. auto I = FI.InlineSites.find(ChildSite);
  494. assert(I != FI.InlineSites.end() &&
  495. "child site not in function inline site map");
  496. emitInlinedCallSite(FI, ChildSite, I->second);
  497. }
  498. // Close the scope.
  499. OS.AddComment("Record length");
  500. OS.EmitIntValue(2, 2); // RecordLength
  501. OS.AddComment("Record kind: S_INLINESITE_END");
  502. OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
  503. }
  504. void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
  505. // If we have a symbol, it may be in a section that is COMDAT. If so, find the
  506. // comdat key. A section may be comdat because of -ffunction-sections or
  507. // because it is comdat in the IR.
  508. MCSectionCOFF *GVSec =
  509. GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
  510. const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
  511. MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
  512. Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
  513. DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
  514. OS.SwitchSection(DebugSec);
  515. // Emit the magic version number if this is the first time we've switched to
  516. // this section.
  517. if (ComdatDebugSections.insert(DebugSec).second)
  518. emitCodeViewMagicVersion();
  519. }
  520. void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
  521. FunctionInfo &FI) {
  522. // For each function there is a separate subsection
  523. // which holds the PC to file:line table.
  524. const MCSymbol *Fn = Asm->getSymbol(GV);
  525. assert(Fn);
  526. // Switch to the to a comdat section, if appropriate.
  527. switchToDebugSectionForSymbol(Fn);
  528. std::string FuncName;
  529. auto *SP = GV->getSubprogram();
  530. assert(SP);
  531. setCurrentSubprogram(SP);
  532. // If we have a display name, build the fully qualified name by walking the
  533. // chain of scopes.
  534. if (!SP->getDisplayName().empty())
  535. FuncName =
  536. getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
  537. // If our DISubprogram name is empty, use the mangled name.
  538. if (FuncName.empty())
  539. FuncName = GlobalValue::getRealLinkageName(GV->getName());
  540. // Emit a symbol subsection, required by VS2012+ to find function boundaries.
  541. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  542. MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
  543. {
  544. MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
  545. *ProcRecordEnd = MMI->getContext().createTempSymbol();
  546. OS.AddComment("Record length");
  547. OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
  548. OS.EmitLabel(ProcRecordBegin);
  549. if (GV->hasLocalLinkage()) {
  550. OS.AddComment("Record kind: S_LPROC32_ID");
  551. OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
  552. } else {
  553. OS.AddComment("Record kind: S_GPROC32_ID");
  554. OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
  555. }
  556. // These fields are filled in by tools like CVPACK which run after the fact.
  557. OS.AddComment("PtrParent");
  558. OS.EmitIntValue(0, 4);
  559. OS.AddComment("PtrEnd");
  560. OS.EmitIntValue(0, 4);
  561. OS.AddComment("PtrNext");
  562. OS.EmitIntValue(0, 4);
  563. // This is the important bit that tells the debugger where the function
  564. // code is located and what's its size:
  565. OS.AddComment("Code size");
  566. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
  567. OS.AddComment("Offset after prologue");
  568. OS.EmitIntValue(0, 4);
  569. OS.AddComment("Offset before epilogue");
  570. OS.EmitIntValue(0, 4);
  571. OS.AddComment("Function type index");
  572. OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
  573. OS.AddComment("Function section relative address");
  574. OS.EmitCOFFSecRel32(Fn);
  575. OS.AddComment("Function section index");
  576. OS.EmitCOFFSectionIndex(Fn);
  577. OS.AddComment("Flags");
  578. OS.EmitIntValue(0, 1);
  579. // Emit the function display name as a null-terminated string.
  580. OS.AddComment("Function name");
  581. // Truncate the name so we won't overflow the record length field.
  582. emitNullTerminatedSymbolName(OS, FuncName);
  583. OS.EmitLabel(ProcRecordEnd);
  584. emitLocalVariableList(FI.Locals);
  585. // Emit inlined call site information. Only emit functions inlined directly
  586. // into the parent function. We'll emit the other sites recursively as part
  587. // of their parent inline site.
  588. for (const DILocation *InlinedAt : FI.ChildSites) {
  589. auto I = FI.InlineSites.find(InlinedAt);
  590. assert(I != FI.InlineSites.end() &&
  591. "child site not in function inline site map");
  592. emitInlinedCallSite(FI, InlinedAt, I->second);
  593. }
  594. if (SP != nullptr)
  595. emitDebugInfoForUDTs(LocalUDTs);
  596. // We're done with this function.
  597. OS.AddComment("Record length");
  598. OS.EmitIntValue(0x0002, 2);
  599. OS.AddComment("Record kind: S_PROC_ID_END");
  600. OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
  601. }
  602. endCVSubsection(SymbolsEnd);
  603. // We have an assembler directive that takes care of the whole line table.
  604. OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
  605. }
  606. CodeViewDebug::LocalVarDefRange
  607. CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
  608. LocalVarDefRange DR;
  609. DR.InMemory = -1;
  610. DR.DataOffset = Offset;
  611. assert(DR.DataOffset == Offset && "truncation");
  612. DR.StructOffset = 0;
  613. DR.CVRegister = CVRegister;
  614. return DR;
  615. }
  616. CodeViewDebug::LocalVarDefRange
  617. CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
  618. LocalVarDefRange DR;
  619. DR.InMemory = 0;
  620. DR.DataOffset = 0;
  621. DR.StructOffset = 0;
  622. DR.CVRegister = CVRegister;
  623. return DR;
  624. }
  625. void CodeViewDebug::collectVariableInfoFromMMITable(
  626. DenseSet<InlinedVariable> &Processed) {
  627. const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
  628. const TargetFrameLowering *TFI = TSI.getFrameLowering();
  629. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  630. for (const MachineModuleInfo::VariableDbgInfo &VI :
  631. MMI->getVariableDbgInfo()) {
  632. if (!VI.Var)
  633. continue;
  634. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  635. "Expected inlined-at fields to agree");
  636. Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
  637. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  638. // If variable scope is not found then skip this variable.
  639. if (!Scope)
  640. continue;
  641. // Get the frame register used and the offset.
  642. unsigned FrameReg = 0;
  643. int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
  644. uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
  645. // Calculate the label ranges.
  646. LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
  647. for (const InsnRange &Range : Scope->getRanges()) {
  648. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  649. const MCSymbol *End = getLabelAfterInsn(Range.second);
  650. End = End ? End : Asm->getFunctionEnd();
  651. DefRange.Ranges.emplace_back(Begin, End);
  652. }
  653. LocalVariable Var;
  654. Var.DIVar = VI.Var;
  655. Var.DefRanges.emplace_back(std::move(DefRange));
  656. recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
  657. }
  658. }
  659. void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
  660. DenseSet<InlinedVariable> Processed;
  661. // Grab the variable info that was squirreled away in the MMI side-table.
  662. collectVariableInfoFromMMITable(Processed);
  663. const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
  664. for (const auto &I : DbgValues) {
  665. InlinedVariable IV = I.first;
  666. if (Processed.count(IV))
  667. continue;
  668. const DILocalVariable *DIVar = IV.first;
  669. const DILocation *InlinedAt = IV.second;
  670. // Instruction ranges, specifying where IV is accessible.
  671. const auto &Ranges = I.second;
  672. LexicalScope *Scope = nullptr;
  673. if (InlinedAt)
  674. Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
  675. else
  676. Scope = LScopes.findLexicalScope(DIVar->getScope());
  677. // If variable scope is not found then skip this variable.
  678. if (!Scope)
  679. continue;
  680. LocalVariable Var;
  681. Var.DIVar = DIVar;
  682. // Calculate the definition ranges.
  683. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  684. const InsnRange &Range = *I;
  685. const MachineInstr *DVInst = Range.first;
  686. assert(DVInst->isDebugValue() && "Invalid History entry");
  687. const DIExpression *DIExpr = DVInst->getDebugExpression();
  688. // Bail if there is a complex DWARF expression for now.
  689. if (DIExpr && DIExpr->getNumElements() > 0)
  690. continue;
  691. // Bail if operand 0 is not a valid register. This means the variable is a
  692. // simple constant, or is described by a complex expression.
  693. // FIXME: Find a way to represent constant variables, since they are
  694. // relatively common.
  695. unsigned Reg =
  696. DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
  697. if (Reg == 0)
  698. continue;
  699. // Handle the two cases we can handle: indirect in memory and in register.
  700. bool IsIndirect = DVInst->getOperand(1).isImm();
  701. unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
  702. {
  703. LocalVarDefRange DefRange;
  704. if (IsIndirect) {
  705. int64_t Offset = DVInst->getOperand(1).getImm();
  706. DefRange = createDefRangeMem(CVReg, Offset);
  707. } else {
  708. DefRange = createDefRangeReg(CVReg);
  709. }
  710. if (Var.DefRanges.empty() ||
  711. Var.DefRanges.back().isDifferentLocation(DefRange)) {
  712. Var.DefRanges.emplace_back(std::move(DefRange));
  713. }
  714. }
  715. // Compute the label range.
  716. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  717. const MCSymbol *End = getLabelAfterInsn(Range.second);
  718. if (!End) {
  719. if (std::next(I) != E)
  720. End = getLabelBeforeInsn(std::next(I)->first);
  721. else
  722. End = Asm->getFunctionEnd();
  723. }
  724. // If the last range end is our begin, just extend the last range.
  725. // Otherwise make a new range.
  726. SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
  727. Var.DefRanges.back().Ranges;
  728. if (!Ranges.empty() && Ranges.back().second == Begin)
  729. Ranges.back().second = End;
  730. else
  731. Ranges.emplace_back(Begin, End);
  732. // FIXME: Do more range combining.
  733. }
  734. recordLocalVariable(std::move(Var), InlinedAt);
  735. }
  736. }
  737. void CodeViewDebug::beginFunction(const MachineFunction *MF) {
  738. assert(!CurFn && "Can't process two functions at once!");
  739. if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
  740. return;
  741. DebugHandlerBase::beginFunction(MF);
  742. const Function *GV = MF->getFunction();
  743. assert(FnDebugInfo.count(GV) == false);
  744. CurFn = &FnDebugInfo[GV];
  745. CurFn->FuncId = NextFuncId++;
  746. CurFn->Begin = Asm->getFunctionBegin();
  747. OS.EmitCVFuncIdDirective(CurFn->FuncId);
  748. // Find the end of the function prolog. First known non-DBG_VALUE and
  749. // non-frame setup location marks the beginning of the function body.
  750. // FIXME: is there a simpler a way to do this? Can we just search
  751. // for the first instruction of the function, not the last of the prolog?
  752. DebugLoc PrologEndLoc;
  753. bool EmptyPrologue = true;
  754. for (const auto &MBB : *MF) {
  755. for (const auto &MI : MBB) {
  756. if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
  757. MI.getDebugLoc()) {
  758. PrologEndLoc = MI.getDebugLoc();
  759. break;
  760. } else if (!MI.isDebugValue()) {
  761. EmptyPrologue = false;
  762. }
  763. }
  764. }
  765. // Record beginning of function if we have a non-empty prologue.
  766. if (PrologEndLoc && !EmptyPrologue) {
  767. DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
  768. maybeRecordLocation(FnStartDL, MF);
  769. }
  770. }
  771. void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
  772. // Don't record empty UDTs.
  773. if (Ty->getName().empty())
  774. return;
  775. SmallVector<StringRef, 5> QualifiedNameComponents;
  776. const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
  777. Ty->getScope().resolve(), QualifiedNameComponents);
  778. std::string FullyQualifiedName =
  779. getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
  780. if (ClosestSubprogram == nullptr)
  781. GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
  782. else if (ClosestSubprogram == CurrentSubprogram)
  783. LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
  784. // TODO: What if the ClosestSubprogram is neither null or the current
  785. // subprogram? Currently, the UDT just gets dropped on the floor.
  786. //
  787. // The current behavior is not desirable. To get maximal fidelity, we would
  788. // need to perform all type translation before beginning emission of .debug$S
  789. // and then make LocalUDTs a member of FunctionInfo
  790. }
  791. TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
  792. // Generic dispatch for lowering an unknown type.
  793. switch (Ty->getTag()) {
  794. case dwarf::DW_TAG_array_type:
  795. return lowerTypeArray(cast<DICompositeType>(Ty));
  796. case dwarf::DW_TAG_typedef:
  797. return lowerTypeAlias(cast<DIDerivedType>(Ty));
  798. case dwarf::DW_TAG_base_type:
  799. return lowerTypeBasic(cast<DIBasicType>(Ty));
  800. case dwarf::DW_TAG_pointer_type:
  801. if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
  802. return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
  803. LLVM_FALLTHROUGH;
  804. case dwarf::DW_TAG_reference_type:
  805. case dwarf::DW_TAG_rvalue_reference_type:
  806. return lowerTypePointer(cast<DIDerivedType>(Ty));
  807. case dwarf::DW_TAG_ptr_to_member_type:
  808. return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
  809. case dwarf::DW_TAG_const_type:
  810. case dwarf::DW_TAG_volatile_type:
  811. return lowerTypeModifier(cast<DIDerivedType>(Ty));
  812. case dwarf::DW_TAG_subroutine_type:
  813. if (ClassTy) {
  814. // The member function type of a member function pointer has no
  815. // ThisAdjustment.
  816. return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
  817. /*ThisAdjustment=*/0);
  818. }
  819. return lowerTypeFunction(cast<DISubroutineType>(Ty));
  820. case dwarf::DW_TAG_enumeration_type:
  821. return lowerTypeEnum(cast<DICompositeType>(Ty));
  822. case dwarf::DW_TAG_class_type:
  823. case dwarf::DW_TAG_structure_type:
  824. return lowerTypeClass(cast<DICompositeType>(Ty));
  825. case dwarf::DW_TAG_union_type:
  826. return lowerTypeUnion(cast<DICompositeType>(Ty));
  827. default:
  828. // Use the null type index.
  829. return TypeIndex();
  830. }
  831. }
  832. TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
  833. DITypeRef UnderlyingTypeRef = Ty->getBaseType();
  834. TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
  835. StringRef TypeName = Ty->getName();
  836. addToUDTs(Ty, UnderlyingTypeIndex);
  837. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
  838. TypeName == "HRESULT")
  839. return TypeIndex(SimpleTypeKind::HResult);
  840. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
  841. TypeName == "wchar_t")
  842. return TypeIndex(SimpleTypeKind::WideCharacter);
  843. return UnderlyingTypeIndex;
  844. }
  845. TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
  846. DITypeRef ElementTypeRef = Ty->getBaseType();
  847. TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
  848. // IndexType is size_t, which depends on the bitness of the target.
  849. TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
  850. ? TypeIndex(SimpleTypeKind::UInt64Quad)
  851. : TypeIndex(SimpleTypeKind::UInt32Long);
  852. uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
  853. // We want to assert that the element type multiplied by the array lengths
  854. // match the size of the overall array. However, if we don't have complete
  855. // type information for the base type, we can't make this assertion. This
  856. // happens if limited debug info is enabled in this case:
  857. // struct VTableOptzn { VTableOptzn(); virtual ~VTableOptzn(); };
  858. // VTableOptzn array[3];
  859. // The DICompositeType of VTableOptzn will have size zero, and the array will
  860. // have size 3 * sizeof(void*), and we should avoid asserting.
  861. //
  862. // There is a related bug in the front-end where an array of a structure,
  863. // which was declared as incomplete structure first, ends up not getting a
  864. // size assigned to it. (PR28303)
  865. // Example:
  866. // struct A(*p)[3];
  867. // struct A { int f; } a[3];
  868. bool PartiallyIncomplete = false;
  869. if (Ty->getSizeInBits() == 0 || ElementSize == 0) {
  870. PartiallyIncomplete = true;
  871. }
  872. // Add subranges to array type.
  873. DINodeArray Elements = Ty->getElements();
  874. for (int i = Elements.size() - 1; i >= 0; --i) {
  875. const DINode *Element = Elements[i];
  876. assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
  877. const DISubrange *Subrange = cast<DISubrange>(Element);
  878. assert(Subrange->getLowerBound() == 0 &&
  879. "codeview doesn't support subranges with lower bounds");
  880. int64_t Count = Subrange->getCount();
  881. // Variable Length Array (VLA) has Count equal to '-1'.
  882. // Replace with Count '1', assume it is the minimum VLA length.
  883. // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
  884. if (Count == -1) {
  885. Count = 1;
  886. PartiallyIncomplete = true;
  887. }
  888. // Update the element size and element type index for subsequent subranges.
  889. ElementSize *= Count;
  890. // If this is the outermost array, use the size from the array. It will be
  891. // more accurate if PartiallyIncomplete is true.
  892. uint64_t ArraySize =
  893. (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
  894. StringRef Name = (i == 0) ? Ty->getName() : "";
  895. ElementTypeIndex = TypeTable.writeKnownType(
  896. ArrayRecord(ElementTypeIndex, IndexType, ArraySize, Name));
  897. }
  898. (void)PartiallyIncomplete;
  899. assert(PartiallyIncomplete || ElementSize == (Ty->getSizeInBits() / 8));
  900. return ElementTypeIndex;
  901. }
  902. TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
  903. TypeIndex Index;
  904. dwarf::TypeKind Kind;
  905. uint32_t ByteSize;
  906. Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
  907. ByteSize = Ty->getSizeInBits() / 8;
  908. SimpleTypeKind STK = SimpleTypeKind::None;
  909. switch (Kind) {
  910. case dwarf::DW_ATE_address:
  911. // FIXME: Translate
  912. break;
  913. case dwarf::DW_ATE_boolean:
  914. switch (ByteSize) {
  915. case 1: STK = SimpleTypeKind::Boolean8; break;
  916. case 2: STK = SimpleTypeKind::Boolean16; break;
  917. case 4: STK = SimpleTypeKind::Boolean32; break;
  918. case 8: STK = SimpleTypeKind::Boolean64; break;
  919. case 16: STK = SimpleTypeKind::Boolean128; break;
  920. }
  921. break;
  922. case dwarf::DW_ATE_complex_float:
  923. switch (ByteSize) {
  924. case 2: STK = SimpleTypeKind::Complex16; break;
  925. case 4: STK = SimpleTypeKind::Complex32; break;
  926. case 8: STK = SimpleTypeKind::Complex64; break;
  927. case 10: STK = SimpleTypeKind::Complex80; break;
  928. case 16: STK = SimpleTypeKind::Complex128; break;
  929. }
  930. break;
  931. case dwarf::DW_ATE_float:
  932. switch (ByteSize) {
  933. case 2: STK = SimpleTypeKind::Float16; break;
  934. case 4: STK = SimpleTypeKind::Float32; break;
  935. case 6: STK = SimpleTypeKind::Float48; break;
  936. case 8: STK = SimpleTypeKind::Float64; break;
  937. case 10: STK = SimpleTypeKind::Float80; break;
  938. case 16: STK = SimpleTypeKind::Float128; break;
  939. }
  940. break;
  941. case dwarf::DW_ATE_signed:
  942. switch (ByteSize) {
  943. case 1: STK = SimpleTypeKind::SByte; break;
  944. case 2: STK = SimpleTypeKind::Int16Short; break;
  945. case 4: STK = SimpleTypeKind::Int32; break;
  946. case 8: STK = SimpleTypeKind::Int64Quad; break;
  947. case 16: STK = SimpleTypeKind::Int128Oct; break;
  948. }
  949. break;
  950. case dwarf::DW_ATE_unsigned:
  951. switch (ByteSize) {
  952. case 1: STK = SimpleTypeKind::Byte; break;
  953. case 2: STK = SimpleTypeKind::UInt16Short; break;
  954. case 4: STK = SimpleTypeKind::UInt32; break;
  955. case 8: STK = SimpleTypeKind::UInt64Quad; break;
  956. case 16: STK = SimpleTypeKind::UInt128Oct; break;
  957. }
  958. break;
  959. case dwarf::DW_ATE_UTF:
  960. switch (ByteSize) {
  961. case 2: STK = SimpleTypeKind::Character16; break;
  962. case 4: STK = SimpleTypeKind::Character32; break;
  963. }
  964. break;
  965. case dwarf::DW_ATE_signed_char:
  966. if (ByteSize == 1)
  967. STK = SimpleTypeKind::SignedCharacter;
  968. break;
  969. case dwarf::DW_ATE_unsigned_char:
  970. if (ByteSize == 1)
  971. STK = SimpleTypeKind::UnsignedCharacter;
  972. break;
  973. default:
  974. break;
  975. }
  976. // Apply some fixups based on the source-level type name.
  977. if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
  978. STK = SimpleTypeKind::Int32Long;
  979. if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
  980. STK = SimpleTypeKind::UInt32Long;
  981. if (STK == SimpleTypeKind::UInt16Short &&
  982. (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
  983. STK = SimpleTypeKind::WideCharacter;
  984. if ((STK == SimpleTypeKind::SignedCharacter ||
  985. STK == SimpleTypeKind::UnsignedCharacter) &&
  986. Ty->getName() == "char")
  987. STK = SimpleTypeKind::NarrowCharacter;
  988. return TypeIndex(STK);
  989. }
  990. TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
  991. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
  992. // Pointers to simple types can use SimpleTypeMode, rather than having a
  993. // dedicated pointer type record.
  994. if (PointeeTI.isSimple() &&
  995. PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
  996. Ty->getTag() == dwarf::DW_TAG_pointer_type) {
  997. SimpleTypeMode Mode = Ty->getSizeInBits() == 64
  998. ? SimpleTypeMode::NearPointer64
  999. : SimpleTypeMode::NearPointer32;
  1000. return TypeIndex(PointeeTI.getSimpleKind(), Mode);
  1001. }
  1002. PointerKind PK =
  1003. Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
  1004. PointerMode PM = PointerMode::Pointer;
  1005. switch (Ty->getTag()) {
  1006. default: llvm_unreachable("not a pointer tag type");
  1007. case dwarf::DW_TAG_pointer_type:
  1008. PM = PointerMode::Pointer;
  1009. break;
  1010. case dwarf::DW_TAG_reference_type:
  1011. PM = PointerMode::LValueReference;
  1012. break;
  1013. case dwarf::DW_TAG_rvalue_reference_type:
  1014. PM = PointerMode::RValueReference;
  1015. break;
  1016. }
  1017. // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
  1018. // 'this' pointer, but not normal contexts. Figure out what we're supposed to
  1019. // do.
  1020. PointerOptions PO = PointerOptions::None;
  1021. PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
  1022. return TypeTable.writeKnownType(PR);
  1023. }
  1024. static PointerToMemberRepresentation
  1025. translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
  1026. // SizeInBytes being zero generally implies that the member pointer type was
  1027. // incomplete, which can happen if it is part of a function prototype. In this
  1028. // case, use the unknown model instead of the general model.
  1029. if (IsPMF) {
  1030. switch (Flags & DINode::FlagPtrToMemberRep) {
  1031. case 0:
  1032. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1033. : PointerToMemberRepresentation::GeneralFunction;
  1034. case DINode::FlagSingleInheritance:
  1035. return PointerToMemberRepresentation::SingleInheritanceFunction;
  1036. case DINode::FlagMultipleInheritance:
  1037. return PointerToMemberRepresentation::MultipleInheritanceFunction;
  1038. case DINode::FlagVirtualInheritance:
  1039. return PointerToMemberRepresentation::VirtualInheritanceFunction;
  1040. }
  1041. } else {
  1042. switch (Flags & DINode::FlagPtrToMemberRep) {
  1043. case 0:
  1044. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1045. : PointerToMemberRepresentation::GeneralData;
  1046. case DINode::FlagSingleInheritance:
  1047. return PointerToMemberRepresentation::SingleInheritanceData;
  1048. case DINode::FlagMultipleInheritance:
  1049. return PointerToMemberRepresentation::MultipleInheritanceData;
  1050. case DINode::FlagVirtualInheritance:
  1051. return PointerToMemberRepresentation::VirtualInheritanceData;
  1052. }
  1053. }
  1054. llvm_unreachable("invalid ptr to member representation");
  1055. }
  1056. TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
  1057. assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
  1058. TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
  1059. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
  1060. PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
  1061. : PointerKind::Near32;
  1062. bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
  1063. PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
  1064. : PointerMode::PointerToDataMember;
  1065. PointerOptions PO = PointerOptions::None; // FIXME
  1066. assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
  1067. uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
  1068. MemberPointerInfo MPI(
  1069. ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
  1070. PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
  1071. return TypeTable.writeKnownType(PR);
  1072. }
  1073. /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
  1074. /// have a translation, use the NearC convention.
  1075. static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
  1076. switch (DwarfCC) {
  1077. case dwarf::DW_CC_normal: return CallingConvention::NearC;
  1078. case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
  1079. case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
  1080. case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
  1081. case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
  1082. case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
  1083. }
  1084. return CallingConvention::NearC;
  1085. }
  1086. TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
  1087. ModifierOptions Mods = ModifierOptions::None;
  1088. bool IsModifier = true;
  1089. const DIType *BaseTy = Ty;
  1090. while (IsModifier && BaseTy) {
  1091. // FIXME: Need to add DWARF tag for __unaligned.
  1092. switch (BaseTy->getTag()) {
  1093. case dwarf::DW_TAG_const_type:
  1094. Mods |= ModifierOptions::Const;
  1095. break;
  1096. case dwarf::DW_TAG_volatile_type:
  1097. Mods |= ModifierOptions::Volatile;
  1098. break;
  1099. default:
  1100. IsModifier = false;
  1101. break;
  1102. }
  1103. if (IsModifier)
  1104. BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
  1105. }
  1106. TypeIndex ModifiedTI = getTypeIndex(BaseTy);
  1107. return TypeTable.writeKnownType(ModifierRecord(ModifiedTI, Mods));
  1108. }
  1109. TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
  1110. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1111. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1112. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1113. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1114. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1115. if (!ReturnAndArgTypeIndices.empty()) {
  1116. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1117. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1118. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1119. }
  1120. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1121. TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
  1122. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1123. ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
  1124. ArgTypeIndices.size(), ArgListIndex);
  1125. return TypeTable.writeKnownType(Procedure);
  1126. }
  1127. TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
  1128. const DIType *ClassTy,
  1129. int ThisAdjustment) {
  1130. // Lower the containing class type.
  1131. TypeIndex ClassType = getTypeIndex(ClassTy);
  1132. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1133. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1134. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1135. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1136. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1137. if (!ReturnAndArgTypeIndices.empty()) {
  1138. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1139. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1140. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1141. }
  1142. TypeIndex ThisTypeIndex = TypeIndex::Void();
  1143. if (!ArgTypeIndices.empty()) {
  1144. ThisTypeIndex = ArgTypeIndices.front();
  1145. ArgTypeIndices = ArgTypeIndices.drop_front();
  1146. }
  1147. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1148. TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
  1149. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1150. // TODO: Need to use the correct values for:
  1151. // FunctionOptions
  1152. // ThisPointerAdjustment.
  1153. TypeIndex TI = TypeTable.writeKnownType(MemberFunctionRecord(
  1154. ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
  1155. ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
  1156. return TI;
  1157. }
  1158. TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
  1159. unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
  1160. SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
  1161. return TypeTable.writeKnownType(VFTableShapeRecord(Slots));
  1162. }
  1163. static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
  1164. switch (Flags & DINode::FlagAccessibility) {
  1165. case DINode::FlagPrivate: return MemberAccess::Private;
  1166. case DINode::FlagPublic: return MemberAccess::Public;
  1167. case DINode::FlagProtected: return MemberAccess::Protected;
  1168. case 0:
  1169. // If there was no explicit access control, provide the default for the tag.
  1170. return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
  1171. : MemberAccess::Public;
  1172. }
  1173. llvm_unreachable("access flags are exclusive");
  1174. }
  1175. static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
  1176. if (SP->isArtificial())
  1177. return MethodOptions::CompilerGenerated;
  1178. // FIXME: Handle other MethodOptions.
  1179. return MethodOptions::None;
  1180. }
  1181. static MethodKind translateMethodKindFlags(const DISubprogram *SP,
  1182. bool Introduced) {
  1183. switch (SP->getVirtuality()) {
  1184. case dwarf::DW_VIRTUALITY_none:
  1185. break;
  1186. case dwarf::DW_VIRTUALITY_virtual:
  1187. return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
  1188. case dwarf::DW_VIRTUALITY_pure_virtual:
  1189. return Introduced ? MethodKind::PureIntroducingVirtual
  1190. : MethodKind::PureVirtual;
  1191. default:
  1192. llvm_unreachable("unhandled virtuality case");
  1193. }
  1194. // FIXME: Get Clang to mark DISubprogram as static and do something with it.
  1195. return MethodKind::Vanilla;
  1196. }
  1197. static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
  1198. switch (Ty->getTag()) {
  1199. case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
  1200. case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
  1201. }
  1202. llvm_unreachable("unexpected tag");
  1203. }
  1204. /// Return ClassOptions that should be present on both the forward declaration
  1205. /// and the defintion of a tag type.
  1206. static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
  1207. ClassOptions CO = ClassOptions::None;
  1208. // MSVC always sets this flag, even for local types. Clang doesn't always
  1209. // appear to give every type a linkage name, which may be problematic for us.
  1210. // FIXME: Investigate the consequences of not following them here.
  1211. if (!Ty->getIdentifier().empty())
  1212. CO |= ClassOptions::HasUniqueName;
  1213. // Put the Nested flag on a type if it appears immediately inside a tag type.
  1214. // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
  1215. // here. That flag is only set on definitions, and not forward declarations.
  1216. const DIScope *ImmediateScope = Ty->getScope().resolve();
  1217. if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
  1218. CO |= ClassOptions::Nested;
  1219. // Put the Scoped flag on function-local types.
  1220. for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
  1221. Scope = Scope->getScope().resolve()) {
  1222. if (isa<DISubprogram>(Scope)) {
  1223. CO |= ClassOptions::Scoped;
  1224. break;
  1225. }
  1226. }
  1227. return CO;
  1228. }
  1229. TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
  1230. ClassOptions CO = getCommonClassOptions(Ty);
  1231. TypeIndex FTI;
  1232. unsigned EnumeratorCount = 0;
  1233. if (Ty->isForwardDecl()) {
  1234. CO |= ClassOptions::ForwardReference;
  1235. } else {
  1236. FieldListRecordBuilder Fields;
  1237. for (const DINode *Element : Ty->getElements()) {
  1238. // We assume that the frontend provides all members in source declaration
  1239. // order, which is what MSVC does.
  1240. if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
  1241. Fields.writeMemberType(EnumeratorRecord(
  1242. MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
  1243. Enumerator->getName()));
  1244. EnumeratorCount++;
  1245. }
  1246. }
  1247. FTI = TypeTable.writeFieldList(Fields);
  1248. }
  1249. std::string FullName = getFullyQualifiedName(Ty);
  1250. return TypeTable.writeKnownType(EnumRecord(EnumeratorCount, CO, FTI, FullName,
  1251. Ty->getIdentifier(),
  1252. getTypeIndex(Ty->getBaseType())));
  1253. }
  1254. //===----------------------------------------------------------------------===//
  1255. // ClassInfo
  1256. //===----------------------------------------------------------------------===//
  1257. struct llvm::ClassInfo {
  1258. struct MemberInfo {
  1259. const DIDerivedType *MemberTypeNode;
  1260. uint64_t BaseOffset;
  1261. };
  1262. // [MemberInfo]
  1263. typedef std::vector<MemberInfo> MemberList;
  1264. typedef TinyPtrVector<const DISubprogram *> MethodsList;
  1265. // MethodName -> MethodsList
  1266. typedef MapVector<MDString *, MethodsList> MethodsMap;
  1267. /// Base classes.
  1268. std::vector<const DIDerivedType *> Inheritance;
  1269. /// Direct members.
  1270. MemberList Members;
  1271. // Direct overloaded methods gathered by name.
  1272. MethodsMap Methods;
  1273. TypeIndex VShapeTI;
  1274. std::vector<const DICompositeType *> NestedClasses;
  1275. };
  1276. void CodeViewDebug::clear() {
  1277. assert(CurFn == nullptr);
  1278. FileIdMap.clear();
  1279. FnDebugInfo.clear();
  1280. FileToFilepathMap.clear();
  1281. LocalUDTs.clear();
  1282. GlobalUDTs.clear();
  1283. TypeIndices.clear();
  1284. CompleteTypeIndices.clear();
  1285. }
  1286. void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
  1287. const DIDerivedType *DDTy) {
  1288. if (!DDTy->getName().empty()) {
  1289. Info.Members.push_back({DDTy, 0});
  1290. return;
  1291. }
  1292. // An unnamed member must represent a nested struct or union. Add all the
  1293. // indirect fields to the current record.
  1294. assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
  1295. uint64_t Offset = DDTy->getOffsetInBits();
  1296. const DIType *Ty = DDTy->getBaseType().resolve();
  1297. const DICompositeType *DCTy = cast<DICompositeType>(Ty);
  1298. ClassInfo NestedInfo = collectClassInfo(DCTy);
  1299. for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
  1300. Info.Members.push_back(
  1301. {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
  1302. }
  1303. ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
  1304. ClassInfo Info;
  1305. // Add elements to structure type.
  1306. DINodeArray Elements = Ty->getElements();
  1307. for (auto *Element : Elements) {
  1308. // We assume that the frontend provides all members in source declaration
  1309. // order, which is what MSVC does.
  1310. if (!Element)
  1311. continue;
  1312. if (auto *SP = dyn_cast<DISubprogram>(Element)) {
  1313. Info.Methods[SP->getRawName()].push_back(SP);
  1314. } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  1315. if (DDTy->getTag() == dwarf::DW_TAG_member) {
  1316. collectMemberInfo(Info, DDTy);
  1317. } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
  1318. Info.Inheritance.push_back(DDTy);
  1319. } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
  1320. DDTy->getName() == "__vtbl_ptr_type") {
  1321. Info.VShapeTI = getTypeIndex(DDTy);
  1322. } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  1323. // Ignore friend members. It appears that MSVC emitted info about
  1324. // friends in the past, but modern versions do not.
  1325. }
  1326. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  1327. Info.NestedClasses.push_back(Composite);
  1328. }
  1329. // Skip other unrecognized kinds of elements.
  1330. }
  1331. return Info;
  1332. }
  1333. TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
  1334. // First, construct the forward decl. Don't look into Ty to compute the
  1335. // forward decl options, since it might not be available in all TUs.
  1336. TypeRecordKind Kind = getRecordKind(Ty);
  1337. ClassOptions CO =
  1338. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1339. std::string FullName = getFullyQualifiedName(Ty);
  1340. TypeIndex FwdDeclTI = TypeTable.writeKnownType(ClassRecord(
  1341. Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
  1342. TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
  1343. if (!Ty->isForwardDecl())
  1344. DeferredCompleteTypes.push_back(Ty);
  1345. return FwdDeclTI;
  1346. }
  1347. TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
  1348. // Construct the field list and complete type record.
  1349. TypeRecordKind Kind = getRecordKind(Ty);
  1350. ClassOptions CO = getCommonClassOptions(Ty);
  1351. TypeIndex FieldTI;
  1352. TypeIndex VShapeTI;
  1353. unsigned FieldCount;
  1354. bool ContainsNestedClass;
  1355. std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
  1356. lowerRecordFieldList(Ty);
  1357. if (ContainsNestedClass)
  1358. CO |= ClassOptions::ContainsNestedClass;
  1359. std::string FullName = getFullyQualifiedName(Ty);
  1360. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1361. TypeIndex ClassTI = TypeTable.writeKnownType(ClassRecord(
  1362. Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
  1363. TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
  1364. TypeTable.writeKnownType(UdtSourceLineRecord(
  1365. ClassTI, TypeTable.writeKnownType(StringIdRecord(
  1366. TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
  1367. Ty->getLine()));
  1368. addToUDTs(Ty, ClassTI);
  1369. return ClassTI;
  1370. }
  1371. TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
  1372. ClassOptions CO =
  1373. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1374. std::string FullName = getFullyQualifiedName(Ty);
  1375. TypeIndex FwdDeclTI = TypeTable.writeKnownType(UnionRecord(
  1376. 0, CO, HfaKind::None, TypeIndex(), 0, FullName, Ty->getIdentifier()));
  1377. if (!Ty->isForwardDecl())
  1378. DeferredCompleteTypes.push_back(Ty);
  1379. return FwdDeclTI;
  1380. }
  1381. TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
  1382. ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
  1383. TypeIndex FieldTI;
  1384. unsigned FieldCount;
  1385. bool ContainsNestedClass;
  1386. std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
  1387. lowerRecordFieldList(Ty);
  1388. if (ContainsNestedClass)
  1389. CO |= ClassOptions::ContainsNestedClass;
  1390. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1391. std::string FullName = getFullyQualifiedName(Ty);
  1392. TypeIndex UnionTI = TypeTable.writeKnownType(
  1393. UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
  1394. Ty->getIdentifier()));
  1395. TypeTable.writeKnownType(UdtSourceLineRecord(
  1396. UnionTI, TypeTable.writeKnownType(StringIdRecord(
  1397. TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
  1398. Ty->getLine()));
  1399. addToUDTs(Ty, UnionTI);
  1400. return UnionTI;
  1401. }
  1402. std::tuple<TypeIndex, TypeIndex, unsigned, bool>
  1403. CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
  1404. // Manually count members. MSVC appears to count everything that generates a
  1405. // field list record. Each individual overload in a method overload group
  1406. // contributes to this count, even though the overload group is a single field
  1407. // list record.
  1408. unsigned MemberCount = 0;
  1409. ClassInfo Info = collectClassInfo(Ty);
  1410. FieldListRecordBuilder Fields;
  1411. // Create base classes.
  1412. for (const DIDerivedType *I : Info.Inheritance) {
  1413. if (I->getFlags() & DINode::FlagVirtual) {
  1414. // Virtual base.
  1415. // FIXME: Emit VBPtrOffset when the frontend provides it.
  1416. unsigned VBPtrOffset = 0;
  1417. // FIXME: Despite the accessor name, the offset is really in bytes.
  1418. unsigned VBTableIndex = I->getOffsetInBits() / 4;
  1419. Fields.writeMemberType(VirtualBaseClassRecord(
  1420. translateAccessFlags(Ty->getTag(), I->getFlags()),
  1421. getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
  1422. VBTableIndex));
  1423. } else {
  1424. assert(I->getOffsetInBits() % 8 == 0 &&
  1425. "bases must be on byte boundaries");
  1426. Fields.writeMemberType(BaseClassRecord(
  1427. translateAccessFlags(Ty->getTag(), I->getFlags()),
  1428. getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
  1429. }
  1430. }
  1431. // Create members.
  1432. for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
  1433. const DIDerivedType *Member = MemberInfo.MemberTypeNode;
  1434. TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
  1435. StringRef MemberName = Member->getName();
  1436. MemberAccess Access =
  1437. translateAccessFlags(Ty->getTag(), Member->getFlags());
  1438. if (Member->isStaticMember()) {
  1439. Fields.writeMemberType(
  1440. StaticDataMemberRecord(Access, MemberBaseType, MemberName));
  1441. MemberCount++;
  1442. continue;
  1443. }
  1444. // Virtual function pointer member.
  1445. if ((Member->getFlags() & DINode::FlagArtificial) &&
  1446. Member->getName().startswith("_vptr$")) {
  1447. Fields.writeMemberType(VFPtrRecord(getTypeIndex(Member->getBaseType())));
  1448. MemberCount++;
  1449. continue;
  1450. }
  1451. // Data member.
  1452. uint64_t MemberOffsetInBits =
  1453. Member->getOffsetInBits() + MemberInfo.BaseOffset;
  1454. if (Member->isBitField()) {
  1455. uint64_t StartBitOffset = MemberOffsetInBits;
  1456. if (const auto *CI =
  1457. dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
  1458. MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
  1459. }
  1460. StartBitOffset -= MemberOffsetInBits;
  1461. MemberBaseType = TypeTable.writeKnownType(BitFieldRecord(
  1462. MemberBaseType, Member->getSizeInBits(), StartBitOffset));
  1463. }
  1464. uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
  1465. Fields.writeMemberType(DataMemberRecord(Access, MemberBaseType,
  1466. MemberOffsetInBytes, MemberName));
  1467. MemberCount++;
  1468. }
  1469. // Create methods
  1470. for (auto &MethodItr : Info.Methods) {
  1471. StringRef Name = MethodItr.first->getString();
  1472. std::vector<OneMethodRecord> Methods;
  1473. for (const DISubprogram *SP : MethodItr.second) {
  1474. TypeIndex MethodType = getMemberFunctionType(SP, Ty);
  1475. bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
  1476. unsigned VFTableOffset = -1;
  1477. if (Introduced)
  1478. VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
  1479. Methods.push_back(
  1480. OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
  1481. translateMethodOptionFlags(SP),
  1482. translateAccessFlags(Ty->getTag(), SP->getFlags()),
  1483. VFTableOffset, Name));
  1484. MemberCount++;
  1485. }
  1486. assert(Methods.size() > 0 && "Empty methods map entry");
  1487. if (Methods.size() == 1)
  1488. Fields.writeMemberType(Methods[0]);
  1489. else {
  1490. TypeIndex MethodList =
  1491. TypeTable.writeKnownType(MethodOverloadListRecord(Methods));
  1492. Fields.writeMemberType(
  1493. OverloadedMethodRecord(Methods.size(), MethodList, Name));
  1494. }
  1495. }
  1496. // Create nested classes.
  1497. for (const DICompositeType *Nested : Info.NestedClasses) {
  1498. NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
  1499. Fields.writeMemberType(R);
  1500. MemberCount++;
  1501. }
  1502. TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
  1503. return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
  1504. !Info.NestedClasses.empty());
  1505. }
  1506. TypeIndex CodeViewDebug::getVBPTypeIndex() {
  1507. if (!VBPType.getIndex()) {
  1508. // Make a 'const int *' type.
  1509. ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
  1510. TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
  1511. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  1512. : PointerKind::Near32;
  1513. PointerMode PM = PointerMode::Pointer;
  1514. PointerOptions PO = PointerOptions::None;
  1515. PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
  1516. VBPType = TypeTable.writeKnownType(PR);
  1517. }
  1518. return VBPType;
  1519. }
  1520. TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
  1521. const DIType *Ty = TypeRef.resolve();
  1522. const DIType *ClassTy = ClassTyRef.resolve();
  1523. // The null DIType is the void type. Don't try to hash it.
  1524. if (!Ty)
  1525. return TypeIndex::Void();
  1526. // Check if we've already translated this type. Don't try to do a
  1527. // get-or-create style insertion that caches the hash lookup across the
  1528. // lowerType call. It will update the TypeIndices map.
  1529. auto I = TypeIndices.find({Ty, ClassTy});
  1530. if (I != TypeIndices.end())
  1531. return I->second;
  1532. TypeLoweringScope S(*this);
  1533. TypeIndex TI = lowerType(Ty, ClassTy);
  1534. return recordTypeIndexForDINode(Ty, TI, ClassTy);
  1535. }
  1536. TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
  1537. const DIType *Ty = TypeRef.resolve();
  1538. // The null DIType is the void type. Don't try to hash it.
  1539. if (!Ty)
  1540. return TypeIndex::Void();
  1541. // If this is a non-record type, the complete type index is the same as the
  1542. // normal type index. Just call getTypeIndex.
  1543. switch (Ty->getTag()) {
  1544. case dwarf::DW_TAG_class_type:
  1545. case dwarf::DW_TAG_structure_type:
  1546. case dwarf::DW_TAG_union_type:
  1547. break;
  1548. default:
  1549. return getTypeIndex(Ty);
  1550. }
  1551. // Check if we've already translated the complete record type. Lowering a
  1552. // complete type should never trigger lowering another complete type, so we
  1553. // can reuse the hash table lookup result.
  1554. const auto *CTy = cast<DICompositeType>(Ty);
  1555. auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
  1556. if (!InsertResult.second)
  1557. return InsertResult.first->second;
  1558. TypeLoweringScope S(*this);
  1559. // Make sure the forward declaration is emitted first. It's unclear if this
  1560. // is necessary, but MSVC does it, and we should follow suit until we can show
  1561. // otherwise.
  1562. TypeIndex FwdDeclTI = getTypeIndex(CTy);
  1563. // Just use the forward decl if we don't have complete type info. This might
  1564. // happen if the frontend is using modules and expects the complete definition
  1565. // to be emitted elsewhere.
  1566. if (CTy->isForwardDecl())
  1567. return FwdDeclTI;
  1568. TypeIndex TI;
  1569. switch (CTy->getTag()) {
  1570. case dwarf::DW_TAG_class_type:
  1571. case dwarf::DW_TAG_structure_type:
  1572. TI = lowerCompleteTypeClass(CTy);
  1573. break;
  1574. case dwarf::DW_TAG_union_type:
  1575. TI = lowerCompleteTypeUnion(CTy);
  1576. break;
  1577. default:
  1578. llvm_unreachable("not a record");
  1579. }
  1580. InsertResult.first->second = TI;
  1581. return TI;
  1582. }
  1583. /// Emit all the deferred complete record types. Try to do this in FIFO order,
  1584. /// and do this until fixpoint, as each complete record type typically
  1585. /// references
  1586. /// many other record types.
  1587. void CodeViewDebug::emitDeferredCompleteTypes() {
  1588. SmallVector<const DICompositeType *, 4> TypesToEmit;
  1589. while (!DeferredCompleteTypes.empty()) {
  1590. std::swap(DeferredCompleteTypes, TypesToEmit);
  1591. for (const DICompositeType *RecordTy : TypesToEmit)
  1592. getCompleteTypeIndex(RecordTy);
  1593. TypesToEmit.clear();
  1594. }
  1595. }
  1596. void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
  1597. // Get the sorted list of parameters and emit them first.
  1598. SmallVector<const LocalVariable *, 6> Params;
  1599. for (const LocalVariable &L : Locals)
  1600. if (L.DIVar->isParameter())
  1601. Params.push_back(&L);
  1602. std::sort(Params.begin(), Params.end(),
  1603. [](const LocalVariable *L, const LocalVariable *R) {
  1604. return L->DIVar->getArg() < R->DIVar->getArg();
  1605. });
  1606. for (const LocalVariable *L : Params)
  1607. emitLocalVariable(*L);
  1608. // Next emit all non-parameters in the order that we found them.
  1609. for (const LocalVariable &L : Locals)
  1610. if (!L.DIVar->isParameter())
  1611. emitLocalVariable(L);
  1612. }
  1613. void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
  1614. // LocalSym record, see SymbolRecord.h for more info.
  1615. MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
  1616. *LocalEnd = MMI->getContext().createTempSymbol();
  1617. OS.AddComment("Record length");
  1618. OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
  1619. OS.EmitLabel(LocalBegin);
  1620. OS.AddComment("Record kind: S_LOCAL");
  1621. OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
  1622. LocalSymFlags Flags = LocalSymFlags::None;
  1623. if (Var.DIVar->isParameter())
  1624. Flags |= LocalSymFlags::IsParameter;
  1625. if (Var.DefRanges.empty())
  1626. Flags |= LocalSymFlags::IsOptimizedOut;
  1627. OS.AddComment("TypeIndex");
  1628. TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
  1629. OS.EmitIntValue(TI.getIndex(), 4);
  1630. OS.AddComment("Flags");
  1631. OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
  1632. // Truncate the name so we won't overflow the record length field.
  1633. emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
  1634. OS.EmitLabel(LocalEnd);
  1635. // Calculate the on disk prefix of the appropriate def range record. The
  1636. // records and on disk formats are described in SymbolRecords.h. BytePrefix
  1637. // should be big enough to hold all forms without memory allocation.
  1638. SmallString<20> BytePrefix;
  1639. for (const LocalVarDefRange &DefRange : Var.DefRanges) {
  1640. BytePrefix.clear();
  1641. // FIXME: Handle bitpieces.
  1642. if (DefRange.StructOffset != 0)
  1643. continue;
  1644. if (DefRange.InMemory) {
  1645. DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
  1646. 0, 0, ArrayRef<LocalVariableAddrGap>());
  1647. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
  1648. BytePrefix +=
  1649. StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
  1650. BytePrefix +=
  1651. StringRef(reinterpret_cast<const char *>(&Sym.Header),
  1652. sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
  1653. } else {
  1654. assert(DefRange.DataOffset == 0 && "unexpected offset into register");
  1655. // Unclear what matters here.
  1656. DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
  1657. ArrayRef<LocalVariableAddrGap>());
  1658. ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
  1659. BytePrefix +=
  1660. StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
  1661. BytePrefix +=
  1662. StringRef(reinterpret_cast<const char *>(&Sym.Header),
  1663. sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
  1664. }
  1665. OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
  1666. }
  1667. }
  1668. void CodeViewDebug::endFunction(const MachineFunction *MF) {
  1669. if (!Asm || !CurFn) // We haven't created any debug info for this function.
  1670. return;
  1671. const Function *GV = MF->getFunction();
  1672. assert(FnDebugInfo.count(GV));
  1673. assert(CurFn == &FnDebugInfo[GV]);
  1674. collectVariableInfo(GV->getSubprogram());
  1675. DebugHandlerBase::endFunction(MF);
  1676. // Don't emit anything if we don't have any line tables.
  1677. if (!CurFn->HaveLineInfo) {
  1678. FnDebugInfo.erase(GV);
  1679. CurFn = nullptr;
  1680. return;
  1681. }
  1682. CurFn->End = Asm->getFunctionEnd();
  1683. CurFn = nullptr;
  1684. }
  1685. void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
  1686. DebugHandlerBase::beginInstruction(MI);
  1687. // Ignore DBG_VALUE locations and function prologue.
  1688. if (!Asm || !CurFn || MI->isDebugValue() ||
  1689. MI->getFlag(MachineInstr::FrameSetup))
  1690. return;
  1691. DebugLoc DL = MI->getDebugLoc();
  1692. if (DL == PrevInstLoc || !DL)
  1693. return;
  1694. maybeRecordLocation(DL, Asm->MF);
  1695. }
  1696. MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
  1697. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  1698. *EndLabel = MMI->getContext().createTempSymbol();
  1699. OS.EmitIntValue(unsigned(Kind), 4);
  1700. OS.AddComment("Subsection size");
  1701. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
  1702. OS.EmitLabel(BeginLabel);
  1703. return EndLabel;
  1704. }
  1705. void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
  1706. OS.EmitLabel(EndLabel);
  1707. // Every subsection must be aligned to a 4-byte boundary.
  1708. OS.EmitValueToAlignment(4);
  1709. }
  1710. void CodeViewDebug::emitDebugInfoForUDTs(
  1711. ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
  1712. for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
  1713. MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
  1714. *UDTRecordEnd = MMI->getContext().createTempSymbol();
  1715. OS.AddComment("Record length");
  1716. OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
  1717. OS.EmitLabel(UDTRecordBegin);
  1718. OS.AddComment("Record kind: S_UDT");
  1719. OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
  1720. OS.AddComment("Type");
  1721. OS.EmitIntValue(UDT.second.getIndex(), 4);
  1722. emitNullTerminatedSymbolName(OS, UDT.first);
  1723. OS.EmitLabel(UDTRecordEnd);
  1724. }
  1725. }
  1726. void CodeViewDebug::emitDebugInfoForGlobals() {
  1727. DenseMap<const DIGlobalVariable *, const GlobalVariable *> GlobalMap;
  1728. for (const GlobalVariable &GV : MMI->getModule()->globals()) {
  1729. SmallVector<MDNode *, 1> MDs;
  1730. GV.getMetadata(LLVMContext::MD_dbg, MDs);
  1731. for (MDNode *MD : MDs)
  1732. GlobalMap[cast<DIGlobalVariable>(MD)] = &GV;
  1733. }
  1734. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  1735. for (const MDNode *Node : CUs->operands()) {
  1736. const auto *CU = cast<DICompileUnit>(Node);
  1737. // First, emit all globals that are not in a comdat in a single symbol
  1738. // substream. MSVC doesn't like it if the substream is empty, so only open
  1739. // it if we have at least one global to emit.
  1740. switchToDebugSectionForSymbol(nullptr);
  1741. MCSymbol *EndLabel = nullptr;
  1742. for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
  1743. if (const auto *GV = GlobalMap.lookup(G))
  1744. if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
  1745. if (!EndLabel) {
  1746. OS.AddComment("Symbol subsection for globals");
  1747. EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
  1748. }
  1749. emitDebugInfoForGlobal(G, GV, Asm->getSymbol(GV));
  1750. }
  1751. }
  1752. if (EndLabel)
  1753. endCVSubsection(EndLabel);
  1754. // Second, emit each global that is in a comdat into its own .debug$S
  1755. // section along with its own symbol substream.
  1756. for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
  1757. if (const auto *GV = GlobalMap.lookup(G)) {
  1758. if (GV->hasComdat()) {
  1759. MCSymbol *GVSym = Asm->getSymbol(GV);
  1760. OS.AddComment("Symbol subsection for " +
  1761. Twine(GlobalValue::getRealLinkageName(GV->getName())));
  1762. switchToDebugSectionForSymbol(GVSym);
  1763. EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
  1764. emitDebugInfoForGlobal(G, GV, GVSym);
  1765. endCVSubsection(EndLabel);
  1766. }
  1767. }
  1768. }
  1769. }
  1770. }
  1771. void CodeViewDebug::emitDebugInfoForRetainedTypes() {
  1772. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  1773. for (const MDNode *Node : CUs->operands()) {
  1774. for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
  1775. if (DIType *RT = dyn_cast<DIType>(Ty)) {
  1776. getTypeIndex(RT);
  1777. // FIXME: Add to global/local DTU list.
  1778. }
  1779. }
  1780. }
  1781. }
  1782. void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
  1783. const GlobalVariable *GV,
  1784. MCSymbol *GVSym) {
  1785. // DataSym record, see SymbolRecord.h for more info.
  1786. // FIXME: Thread local data, etc
  1787. MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
  1788. *DataEnd = MMI->getContext().createTempSymbol();
  1789. OS.AddComment("Record length");
  1790. OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
  1791. OS.EmitLabel(DataBegin);
  1792. if (DIGV->isLocalToUnit()) {
  1793. if (GV->isThreadLocal()) {
  1794. OS.AddComment("Record kind: S_LTHREAD32");
  1795. OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
  1796. } else {
  1797. OS.AddComment("Record kind: S_LDATA32");
  1798. OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
  1799. }
  1800. } else {
  1801. if (GV->isThreadLocal()) {
  1802. OS.AddComment("Record kind: S_GTHREAD32");
  1803. OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
  1804. } else {
  1805. OS.AddComment("Record kind: S_GDATA32");
  1806. OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
  1807. }
  1808. }
  1809. OS.AddComment("Type");
  1810. OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
  1811. OS.AddComment("DataOffset");
  1812. OS.EmitCOFFSecRel32(GVSym);
  1813. OS.AddComment("Segment");
  1814. OS.EmitCOFFSectionIndex(GVSym);
  1815. OS.AddComment("Name");
  1816. emitNullTerminatedSymbolName(OS, DIGV->getName());
  1817. OS.EmitLabel(DataEnd);
  1818. }