CodeViewDebug.cpp 89 KB

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