CodeViewDebug.cpp 84 KB

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