CodeViewDebug.cpp 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023
  1. //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for writing Microsoft CodeView debug info.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeViewDebug.h"
  13. #include "DwarfExpression.h"
  14. #include "llvm/ADT/APSInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/DenseSet.h"
  18. #include "llvm/ADT/MapVector.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/TinyPtrVector.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/BinaryFormat/COFF.h"
  29. #include "llvm/BinaryFormat/Dwarf.h"
  30. #include "llvm/CodeGen/AsmPrinter.h"
  31. #include "llvm/CodeGen/LexicalScopes.h"
  32. #include "llvm/CodeGen/MachineFrameInfo.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/TargetRegisterInfo.h"
  39. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  40. #include "llvm/Config/llvm-config.h"
  41. #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
  42. #include "llvm/DebugInfo/CodeView/CodeView.h"
  43. #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
  44. #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
  45. #include "llvm/DebugInfo/CodeView/EnumTables.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/Path.h"
  76. #include "llvm/Support/SMLoc.h"
  77. #include "llvm/Support/ScopedPrinter.h"
  78. #include "llvm/Target/TargetLoweringObjectFile.h"
  79. #include "llvm/Target/TargetMachine.h"
  80. #include <algorithm>
  81. #include <cassert>
  82. #include <cctype>
  83. #include <cstddef>
  84. #include <cstdint>
  85. #include <iterator>
  86. #include <limits>
  87. #include <string>
  88. #include <utility>
  89. #include <vector>
  90. using namespace llvm;
  91. using namespace llvm::codeview;
  92. static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
  93. switch (Type) {
  94. case Triple::ArchType::x86:
  95. return CPUType::Pentium3;
  96. case Triple::ArchType::x86_64:
  97. return CPUType::X64;
  98. case Triple::ArchType::thumb:
  99. return CPUType::Thumb;
  100. case Triple::ArchType::aarch64:
  101. return CPUType::ARM64;
  102. default:
  103. report_fatal_error("target architecture doesn't map to a CodeView CPUType");
  104. }
  105. }
  106. CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
  107. : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
  108. // If module doesn't have named metadata anchors or COFF debug section
  109. // is not available, skip any debug info related stuff.
  110. if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
  111. !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
  112. Asm = nullptr;
  113. MMI->setDebugInfoAvailability(false);
  114. return;
  115. }
  116. // Tell MMI that we have debug info.
  117. MMI->setDebugInfoAvailability(true);
  118. TheCPU =
  119. mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
  120. collectGlobalVariableInfo();
  121. // Check if we should emit type record hashes.
  122. ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
  123. MMI->getModule()->getModuleFlag("CodeViewGHash"));
  124. EmitDebugGlobalHashes = GH && !GH->isZero();
  125. }
  126. StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
  127. std::string &Filepath = FileToFilepathMap[File];
  128. if (!Filepath.empty())
  129. return Filepath;
  130. StringRef Dir = File->getDirectory(), Filename = File->getFilename();
  131. // If this is a Unix-style path, just use it as is. Don't try to canonicalize
  132. // it textually because one of the path components could be a symlink.
  133. if (Dir.startswith("/") || Filename.startswith("/")) {
  134. if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
  135. return Filename;
  136. Filepath = Dir;
  137. if (Dir.back() != '/')
  138. Filepath += '/';
  139. Filepath += Filename;
  140. return Filepath;
  141. }
  142. // Clang emits directory and relative filename info into the IR, but CodeView
  143. // operates on full paths. We could change Clang to emit full paths too, but
  144. // that would increase the IR size and probably not needed for other users.
  145. // For now, just concatenate and canonicalize the path here.
  146. if (Filename.find(':') == 1)
  147. Filepath = Filename;
  148. else
  149. Filepath = (Dir + "\\" + Filename).str();
  150. // Canonicalize the path. We have to do it textually because we may no longer
  151. // have access the file in the filesystem.
  152. // First, replace all slashes with backslashes.
  153. std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
  154. // Remove all "\.\" with "\".
  155. size_t Cursor = 0;
  156. while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
  157. Filepath.erase(Cursor, 2);
  158. // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
  159. // path should be well-formatted, e.g. start with a drive letter, etc.
  160. Cursor = 0;
  161. while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
  162. // Something's wrong if the path starts with "\..\", abort.
  163. if (Cursor == 0)
  164. break;
  165. size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
  166. if (PrevSlash == std::string::npos)
  167. // Something's wrong, abort.
  168. break;
  169. Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
  170. // The next ".." might be following the one we've just erased.
  171. Cursor = PrevSlash;
  172. }
  173. // Remove all duplicate backslashes.
  174. Cursor = 0;
  175. while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
  176. Filepath.erase(Cursor, 1);
  177. return Filepath;
  178. }
  179. unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
  180. StringRef FullPath = getFullFilepath(F);
  181. unsigned NextId = FileIdMap.size() + 1;
  182. auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
  183. if (Insertion.second) {
  184. // We have to compute the full filepath and emit a .cv_file directive.
  185. ArrayRef<uint8_t> ChecksumAsBytes;
  186. FileChecksumKind CSKind = FileChecksumKind::None;
  187. if (F->getChecksum()) {
  188. std::string Checksum = fromHex(F->getChecksum()->Value);
  189. void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
  190. memcpy(CKMem, Checksum.data(), Checksum.size());
  191. ChecksumAsBytes = ArrayRef<uint8_t>(
  192. reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
  193. switch (F->getChecksum()->Kind) {
  194. case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
  195. case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
  196. }
  197. }
  198. bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
  199. static_cast<unsigned>(CSKind));
  200. (void)Success;
  201. assert(Success && ".cv_file directive failed");
  202. }
  203. return Insertion.first->second;
  204. }
  205. CodeViewDebug::InlineSite &
  206. CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
  207. const DISubprogram *Inlinee) {
  208. auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
  209. InlineSite *Site = &SiteInsertion.first->second;
  210. if (SiteInsertion.second) {
  211. unsigned ParentFuncId = CurFn->FuncId;
  212. if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
  213. ParentFuncId =
  214. getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
  215. .SiteFuncId;
  216. Site->SiteFuncId = NextFuncId++;
  217. OS.EmitCVInlineSiteIdDirective(
  218. Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
  219. InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
  220. Site->Inlinee = Inlinee;
  221. InlinedSubprograms.insert(Inlinee);
  222. getFuncIdForSubprogram(Inlinee);
  223. }
  224. return *Site;
  225. }
  226. static StringRef getPrettyScopeName(const DIScope *Scope) {
  227. StringRef ScopeName = Scope->getName();
  228. if (!ScopeName.empty())
  229. return ScopeName;
  230. switch (Scope->getTag()) {
  231. case dwarf::DW_TAG_enumeration_type:
  232. case dwarf::DW_TAG_class_type:
  233. case dwarf::DW_TAG_structure_type:
  234. case dwarf::DW_TAG_union_type:
  235. return "<unnamed-tag>";
  236. case dwarf::DW_TAG_namespace:
  237. return "`anonymous namespace'";
  238. }
  239. return StringRef();
  240. }
  241. static const DISubprogram *getQualifiedNameComponents(
  242. const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
  243. const DISubprogram *ClosestSubprogram = nullptr;
  244. while (Scope != nullptr) {
  245. if (ClosestSubprogram == nullptr)
  246. ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
  247. StringRef ScopeName = getPrettyScopeName(Scope);
  248. if (!ScopeName.empty())
  249. QualifiedNameComponents.push_back(ScopeName);
  250. Scope = Scope->getScope().resolve();
  251. }
  252. return ClosestSubprogram;
  253. }
  254. static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
  255. StringRef TypeName) {
  256. std::string FullyQualifiedName;
  257. for (StringRef QualifiedNameComponent :
  258. llvm::reverse(QualifiedNameComponents)) {
  259. FullyQualifiedName.append(QualifiedNameComponent);
  260. FullyQualifiedName.append("::");
  261. }
  262. FullyQualifiedName.append(TypeName);
  263. return FullyQualifiedName;
  264. }
  265. static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
  266. SmallVector<StringRef, 5> QualifiedNameComponents;
  267. getQualifiedNameComponents(Scope, QualifiedNameComponents);
  268. return getQualifiedName(QualifiedNameComponents, Name);
  269. }
  270. struct CodeViewDebug::TypeLoweringScope {
  271. TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
  272. ~TypeLoweringScope() {
  273. // Don't decrement TypeEmissionLevel until after emitting deferred types, so
  274. // inner TypeLoweringScopes don't attempt to emit deferred types.
  275. if (CVD.TypeEmissionLevel == 1)
  276. CVD.emitDeferredCompleteTypes();
  277. --CVD.TypeEmissionLevel;
  278. }
  279. CodeViewDebug &CVD;
  280. };
  281. static std::string getFullyQualifiedName(const DIScope *Ty) {
  282. const DIScope *Scope = Ty->getScope().resolve();
  283. return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
  284. }
  285. TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
  286. // No scope means global scope and that uses the zero index.
  287. if (!Scope || isa<DIFile>(Scope))
  288. return TypeIndex();
  289. assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
  290. // Check if we've already translated this scope.
  291. auto I = TypeIndices.find({Scope, nullptr});
  292. if (I != TypeIndices.end())
  293. return I->second;
  294. // Build the fully qualified name of the scope.
  295. std::string ScopeName = getFullyQualifiedName(Scope);
  296. StringIdRecord SID(TypeIndex(), ScopeName);
  297. auto TI = TypeTable.writeLeafType(SID);
  298. return recordTypeIndexForDINode(Scope, TI);
  299. }
  300. TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
  301. assert(SP);
  302. // Check if we've already translated this subprogram.
  303. auto I = TypeIndices.find({SP, nullptr});
  304. if (I != TypeIndices.end())
  305. return I->second;
  306. // The display name includes function template arguments. Drop them to match
  307. // MSVC.
  308. StringRef DisplayName = SP->getName().split('<').first;
  309. const DIScope *Scope = SP->getScope().resolve();
  310. TypeIndex TI;
  311. if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
  312. // If the scope is a DICompositeType, then this must be a method. Member
  313. // function types take some special handling, and require access to the
  314. // subprogram.
  315. TypeIndex ClassType = getTypeIndex(Class);
  316. MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
  317. DisplayName);
  318. TI = TypeTable.writeLeafType(MFuncId);
  319. } else {
  320. // Otherwise, this must be a free function.
  321. TypeIndex ParentScope = getScopeIndex(Scope);
  322. FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
  323. TI = TypeTable.writeLeafType(FuncId);
  324. }
  325. return recordTypeIndexForDINode(SP, TI);
  326. }
  327. static bool isNonTrivial(const DICompositeType *DCTy) {
  328. return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
  329. }
  330. static FunctionOptions
  331. getFunctionOptions(const DISubroutineType *Ty,
  332. const DICompositeType *ClassTy = nullptr,
  333. StringRef SPName = StringRef("")) {
  334. FunctionOptions FO = FunctionOptions::None;
  335. const DIType *ReturnTy = nullptr;
  336. if (auto TypeArray = Ty->getTypeArray()) {
  337. if (TypeArray.size())
  338. ReturnTy = TypeArray[0].resolve();
  339. }
  340. if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
  341. if (isNonTrivial(ReturnDCTy))
  342. FO |= FunctionOptions::CxxReturnUdt;
  343. }
  344. // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
  345. if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
  346. FO |= FunctionOptions::Constructor;
  347. // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
  348. }
  349. return FO;
  350. }
  351. TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
  352. const DICompositeType *Class) {
  353. // Always use the method declaration as the key for the function type. The
  354. // method declaration contains the this adjustment.
  355. if (SP->getDeclaration())
  356. SP = SP->getDeclaration();
  357. assert(!SP->getDeclaration() && "should use declaration as key");
  358. // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
  359. // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
  360. auto I = TypeIndices.find({SP, Class});
  361. if (I != TypeIndices.end())
  362. return I->second;
  363. // Make sure complete type info for the class is emitted *after* the member
  364. // function type, as the complete class type is likely to reference this
  365. // member function type.
  366. TypeLoweringScope S(*this);
  367. const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
  368. FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
  369. TypeIndex TI = lowerTypeMemberFunction(
  370. SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
  371. return recordTypeIndexForDINode(SP, TI, Class);
  372. }
  373. TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
  374. TypeIndex TI,
  375. const DIType *ClassTy) {
  376. auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
  377. (void)InsertResult;
  378. assert(InsertResult.second && "DINode was already assigned a type index");
  379. return TI;
  380. }
  381. unsigned CodeViewDebug::getPointerSizeInBytes() {
  382. return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
  383. }
  384. void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
  385. const LexicalScope *LS) {
  386. if (const DILocation *InlinedAt = LS->getInlinedAt()) {
  387. // This variable was inlined. Associate it with the InlineSite.
  388. const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
  389. InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
  390. Site.InlinedLocals.emplace_back(Var);
  391. } else {
  392. // This variable goes into the corresponding lexical scope.
  393. ScopeVariables[LS].emplace_back(Var);
  394. }
  395. }
  396. static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
  397. const DILocation *Loc) {
  398. auto B = Locs.begin(), E = Locs.end();
  399. if (std::find(B, E, Loc) == E)
  400. Locs.push_back(Loc);
  401. }
  402. void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
  403. const MachineFunction *MF) {
  404. // Skip this instruction if it has the same location as the previous one.
  405. if (!DL || DL == PrevInstLoc)
  406. return;
  407. const DIScope *Scope = DL.get()->getScope();
  408. if (!Scope)
  409. return;
  410. // Skip this line if it is longer than the maximum we can record.
  411. LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
  412. if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
  413. LI.isNeverStepInto())
  414. return;
  415. ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
  416. if (CI.getStartColumn() != DL.getCol())
  417. return;
  418. if (!CurFn->HaveLineInfo)
  419. CurFn->HaveLineInfo = true;
  420. unsigned FileId = 0;
  421. if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
  422. FileId = CurFn->LastFileId;
  423. else
  424. FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
  425. PrevInstLoc = DL;
  426. unsigned FuncId = CurFn->FuncId;
  427. if (const DILocation *SiteLoc = DL->getInlinedAt()) {
  428. const DILocation *Loc = DL.get();
  429. // If this location was actually inlined from somewhere else, give it the ID
  430. // of the inline call site.
  431. FuncId =
  432. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
  433. // Ensure we have links in the tree of inline call sites.
  434. bool FirstLoc = true;
  435. while ((SiteLoc = Loc->getInlinedAt())) {
  436. InlineSite &Site =
  437. getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
  438. if (!FirstLoc)
  439. addLocIfNotPresent(Site.ChildSites, Loc);
  440. FirstLoc = false;
  441. Loc = SiteLoc;
  442. }
  443. addLocIfNotPresent(CurFn->ChildSites, Loc);
  444. }
  445. OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
  446. /*PrologueEnd=*/false, /*IsStmt=*/false,
  447. DL->getFilename(), SMLoc());
  448. }
  449. void CodeViewDebug::emitCodeViewMagicVersion() {
  450. OS.EmitValueToAlignment(4);
  451. OS.AddComment("Debug section magic");
  452. OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
  453. }
  454. void CodeViewDebug::endModule() {
  455. if (!Asm || !MMI->hasDebugInfo())
  456. return;
  457. assert(Asm != nullptr);
  458. // The COFF .debug$S section consists of several subsections, each starting
  459. // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
  460. // of the payload followed by the payload itself. The subsections are 4-byte
  461. // aligned.
  462. // Use the generic .debug$S section, and make a subsection for all the inlined
  463. // subprograms.
  464. switchToDebugSectionForSymbol(nullptr);
  465. MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
  466. emitCompilerInformation();
  467. endCVSubsection(CompilerInfo);
  468. emitInlineeLinesSubsection();
  469. // Emit per-function debug information.
  470. for (auto &P : FnDebugInfo)
  471. if (!P.first->isDeclarationForLinker())
  472. emitDebugInfoForFunction(P.first, *P.second);
  473. // Emit global variable debug information.
  474. setCurrentSubprogram(nullptr);
  475. emitDebugInfoForGlobals();
  476. // Emit retained types.
  477. emitDebugInfoForRetainedTypes();
  478. // Switch back to the generic .debug$S section after potentially processing
  479. // comdat symbol sections.
  480. switchToDebugSectionForSymbol(nullptr);
  481. // Emit UDT records for any types used by global variables.
  482. if (!GlobalUDTs.empty()) {
  483. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  484. emitDebugInfoForUDTs(GlobalUDTs);
  485. endCVSubsection(SymbolsEnd);
  486. }
  487. // This subsection holds a file index to offset in string table table.
  488. OS.AddComment("File index to string table offset subsection");
  489. OS.EmitCVFileChecksumsDirective();
  490. // This subsection holds the string table.
  491. OS.AddComment("String table");
  492. OS.EmitCVStringTableDirective();
  493. // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
  494. // subsection in the generic .debug$S section at the end. There is no
  495. // particular reason for this ordering other than to match MSVC.
  496. emitBuildInfo();
  497. // Emit type information and hashes last, so that any types we translate while
  498. // emitting function info are included.
  499. emitTypeInformation();
  500. if (EmitDebugGlobalHashes)
  501. emitTypeGlobalHashes();
  502. clear();
  503. }
  504. static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
  505. unsigned MaxFixedRecordLength = 0xF00) {
  506. // The maximum CV record length is 0xFF00. Most of the strings we emit appear
  507. // after a fixed length portion of the record. The fixed length portion should
  508. // always be less than 0xF00 (3840) bytes, so truncate the string so that the
  509. // overall record size is less than the maximum allowed.
  510. SmallString<32> NullTerminatedString(
  511. S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
  512. NullTerminatedString.push_back('\0');
  513. OS.EmitBytes(NullTerminatedString);
  514. }
  515. void CodeViewDebug::emitTypeInformation() {
  516. if (TypeTable.empty())
  517. return;
  518. // Start the .debug$T or .debug$P section with 0x4.
  519. OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
  520. emitCodeViewMagicVersion();
  521. SmallString<8> CommentPrefix;
  522. if (OS.isVerboseAsm()) {
  523. CommentPrefix += '\t';
  524. CommentPrefix += Asm->MAI->getCommentString();
  525. CommentPrefix += ' ';
  526. }
  527. TypeTableCollection Table(TypeTable.records());
  528. Optional<TypeIndex> B = Table.getFirst();
  529. while (B) {
  530. // This will fail if the record data is invalid.
  531. CVType Record = Table.getType(*B);
  532. if (OS.isVerboseAsm()) {
  533. // Emit a block comment describing the type record for readability.
  534. SmallString<512> CommentBlock;
  535. raw_svector_ostream CommentOS(CommentBlock);
  536. ScopedPrinter SP(CommentOS);
  537. SP.setPrefix(CommentPrefix);
  538. TypeDumpVisitor TDV(Table, &SP, false);
  539. Error E = codeview::visitTypeRecord(Record, *B, TDV);
  540. if (E) {
  541. logAllUnhandledErrors(std::move(E), errs(), "error: ");
  542. llvm_unreachable("produced malformed type record");
  543. }
  544. // emitRawComment will insert its own tab and comment string before
  545. // the first line, so strip off our first one. It also prints its own
  546. // newline.
  547. OS.emitRawComment(
  548. CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
  549. }
  550. OS.EmitBinaryData(Record.str_data());
  551. B = Table.getNext(*B);
  552. }
  553. }
  554. void CodeViewDebug::emitTypeGlobalHashes() {
  555. if (TypeTable.empty())
  556. return;
  557. // Start the .debug$H section with the version and hash algorithm, currently
  558. // hardcoded to version 0, SHA1.
  559. OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
  560. OS.EmitValueToAlignment(4);
  561. OS.AddComment("Magic");
  562. OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
  563. OS.AddComment("Section Version");
  564. OS.EmitIntValue(0, 2);
  565. OS.AddComment("Hash Algorithm");
  566. OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
  567. TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
  568. for (const auto &GHR : TypeTable.hashes()) {
  569. if (OS.isVerboseAsm()) {
  570. // Emit an EOL-comment describing which TypeIndex this hash corresponds
  571. // to, as well as the stringified SHA1 hash.
  572. SmallString<32> Comment;
  573. raw_svector_ostream CommentOS(Comment);
  574. CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
  575. OS.AddComment(Comment);
  576. ++TI;
  577. }
  578. assert(GHR.Hash.size() == 8);
  579. StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
  580. GHR.Hash.size());
  581. OS.EmitBinaryData(S);
  582. }
  583. }
  584. static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
  585. switch (DWLang) {
  586. case dwarf::DW_LANG_C:
  587. case dwarf::DW_LANG_C89:
  588. case dwarf::DW_LANG_C99:
  589. case dwarf::DW_LANG_C11:
  590. case dwarf::DW_LANG_ObjC:
  591. return SourceLanguage::C;
  592. case dwarf::DW_LANG_C_plus_plus:
  593. case dwarf::DW_LANG_C_plus_plus_03:
  594. case dwarf::DW_LANG_C_plus_plus_11:
  595. case dwarf::DW_LANG_C_plus_plus_14:
  596. return SourceLanguage::Cpp;
  597. case dwarf::DW_LANG_Fortran77:
  598. case dwarf::DW_LANG_Fortran90:
  599. case dwarf::DW_LANG_Fortran03:
  600. case dwarf::DW_LANG_Fortran08:
  601. return SourceLanguage::Fortran;
  602. case dwarf::DW_LANG_Pascal83:
  603. return SourceLanguage::Pascal;
  604. case dwarf::DW_LANG_Cobol74:
  605. case dwarf::DW_LANG_Cobol85:
  606. return SourceLanguage::Cobol;
  607. case dwarf::DW_LANG_Java:
  608. return SourceLanguage::Java;
  609. case dwarf::DW_LANG_D:
  610. return SourceLanguage::D;
  611. case dwarf::DW_LANG_Swift:
  612. return SourceLanguage::Swift;
  613. default:
  614. // There's no CodeView representation for this language, and CV doesn't
  615. // have an "unknown" option for the language field, so we'll use MASM,
  616. // as it's very low level.
  617. return SourceLanguage::Masm;
  618. }
  619. }
  620. namespace {
  621. struct Version {
  622. int Part[4];
  623. };
  624. } // end anonymous namespace
  625. // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
  626. // the version number.
  627. static Version parseVersion(StringRef Name) {
  628. Version V = {{0}};
  629. int N = 0;
  630. for (const char C : Name) {
  631. if (isdigit(C)) {
  632. V.Part[N] *= 10;
  633. V.Part[N] += C - '0';
  634. } else if (C == '.') {
  635. ++N;
  636. if (N >= 4)
  637. return V;
  638. } else if (N > 0)
  639. return V;
  640. }
  641. return V;
  642. }
  643. void CodeViewDebug::emitCompilerInformation() {
  644. MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
  645. uint32_t Flags = 0;
  646. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  647. const MDNode *Node = *CUs->operands().begin();
  648. const auto *CU = cast<DICompileUnit>(Node);
  649. // The low byte of the flags indicates the source language.
  650. Flags = MapDWLangToCVLang(CU->getSourceLanguage());
  651. // TODO: Figure out which other flags need to be set.
  652. OS.AddComment("Flags and language");
  653. OS.EmitIntValue(Flags, 4);
  654. OS.AddComment("CPUType");
  655. OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
  656. StringRef CompilerVersion = CU->getProducer();
  657. Version FrontVer = parseVersion(CompilerVersion);
  658. OS.AddComment("Frontend version");
  659. for (int N = 0; N < 4; ++N)
  660. OS.EmitIntValue(FrontVer.Part[N], 2);
  661. // Some Microsoft tools, like Binscope, expect a backend version number of at
  662. // least 8.something, so we'll coerce the LLVM version into a form that
  663. // guarantees it'll be big enough without really lying about the version.
  664. int Major = 1000 * LLVM_VERSION_MAJOR +
  665. 10 * LLVM_VERSION_MINOR +
  666. LLVM_VERSION_PATCH;
  667. // Clamp it for builds that use unusually large version numbers.
  668. Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
  669. Version BackVer = {{ Major, 0, 0, 0 }};
  670. OS.AddComment("Backend version");
  671. for (int N = 0; N < 4; ++N)
  672. OS.EmitIntValue(BackVer.Part[N], 2);
  673. OS.AddComment("Null-terminated compiler version string");
  674. emitNullTerminatedSymbolName(OS, CompilerVersion);
  675. endSymbolRecord(CompilerEnd);
  676. }
  677. static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
  678. StringRef S) {
  679. StringIdRecord SIR(TypeIndex(0x0), S);
  680. return TypeTable.writeLeafType(SIR);
  681. }
  682. void CodeViewDebug::emitBuildInfo() {
  683. // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
  684. // build info. The known prefix is:
  685. // - Absolute path of current directory
  686. // - Compiler path
  687. // - Main source file path, relative to CWD or absolute
  688. // - Type server PDB file
  689. // - Canonical compiler command line
  690. // If frontend and backend compilation are separated (think llc or LTO), it's
  691. // not clear if the compiler path should refer to the executable for the
  692. // frontend or the backend. Leave it blank for now.
  693. TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
  694. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  695. const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
  696. const auto *CU = cast<DICompileUnit>(Node);
  697. const DIFile *MainSourceFile = CU->getFile();
  698. BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
  699. getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
  700. BuildInfoArgs[BuildInfoRecord::SourceFile] =
  701. getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
  702. // FIXME: Path to compiler and command line. PDB is intentionally blank unless
  703. // we implement /Zi type servers.
  704. BuildInfoRecord BIR(BuildInfoArgs);
  705. TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
  706. // Make a new .debug$S subsection for the S_BUILDINFO record, which points
  707. // from the module symbols into the type stream.
  708. MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  709. MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
  710. OS.AddComment("LF_BUILDINFO index");
  711. OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
  712. endSymbolRecord(BIEnd);
  713. endCVSubsection(BISubsecEnd);
  714. }
  715. void CodeViewDebug::emitInlineeLinesSubsection() {
  716. if (InlinedSubprograms.empty())
  717. return;
  718. OS.AddComment("Inlinee lines subsection");
  719. MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
  720. // We emit the checksum info for files. This is used by debuggers to
  721. // determine if a pdb matches the source before loading it. Visual Studio,
  722. // for instance, will display a warning that the breakpoints are not valid if
  723. // the pdb does not match the source.
  724. OS.AddComment("Inlinee lines signature");
  725. OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
  726. for (const DISubprogram *SP : InlinedSubprograms) {
  727. assert(TypeIndices.count({SP, nullptr}));
  728. TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
  729. OS.AddBlankLine();
  730. unsigned FileId = maybeRecordFile(SP->getFile());
  731. OS.AddComment("Inlined function " + SP->getName() + " starts at " +
  732. SP->getFilename() + Twine(':') + Twine(SP->getLine()));
  733. OS.AddBlankLine();
  734. OS.AddComment("Type index of inlined function");
  735. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  736. OS.AddComment("Offset into filechecksum table");
  737. OS.EmitCVFileChecksumOffsetDirective(FileId);
  738. OS.AddComment("Starting line number");
  739. OS.EmitIntValue(SP->getLine(), 4);
  740. }
  741. endCVSubsection(InlineEnd);
  742. }
  743. void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
  744. const DILocation *InlinedAt,
  745. const InlineSite &Site) {
  746. assert(TypeIndices.count({Site.Inlinee, nullptr}));
  747. TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
  748. // SymbolRecord
  749. MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
  750. OS.AddComment("PtrParent");
  751. OS.EmitIntValue(0, 4);
  752. OS.AddComment("PtrEnd");
  753. OS.EmitIntValue(0, 4);
  754. OS.AddComment("Inlinee type index");
  755. OS.EmitIntValue(InlineeIdx.getIndex(), 4);
  756. unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
  757. unsigned StartLineNum = Site.Inlinee->getLine();
  758. OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
  759. FI.Begin, FI.End);
  760. endSymbolRecord(InlineEnd);
  761. emitLocalVariableList(FI, Site.InlinedLocals);
  762. // Recurse on child inlined call sites before closing the scope.
  763. for (const DILocation *ChildSite : Site.ChildSites) {
  764. auto I = FI.InlineSites.find(ChildSite);
  765. assert(I != FI.InlineSites.end() &&
  766. "child site not in function inline site map");
  767. emitInlinedCallSite(FI, ChildSite, I->second);
  768. }
  769. // Close the scope.
  770. emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
  771. }
  772. void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
  773. // If we have a symbol, it may be in a section that is COMDAT. If so, find the
  774. // comdat key. A section may be comdat because of -ffunction-sections or
  775. // because it is comdat in the IR.
  776. MCSectionCOFF *GVSec =
  777. GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
  778. const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
  779. MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
  780. Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
  781. DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
  782. OS.SwitchSection(DebugSec);
  783. // Emit the magic version number if this is the first time we've switched to
  784. // this section.
  785. if (ComdatDebugSections.insert(DebugSec).second)
  786. emitCodeViewMagicVersion();
  787. }
  788. // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
  789. // The only supported thunk ordinal is currently the standard type.
  790. void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
  791. FunctionInfo &FI,
  792. const MCSymbol *Fn) {
  793. std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
  794. const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
  795. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  796. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  797. // Emit S_THUNK32
  798. MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
  799. OS.AddComment("PtrParent");
  800. OS.EmitIntValue(0, 4);
  801. OS.AddComment("PtrEnd");
  802. OS.EmitIntValue(0, 4);
  803. OS.AddComment("PtrNext");
  804. OS.EmitIntValue(0, 4);
  805. OS.AddComment("Thunk section relative address");
  806. OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
  807. OS.AddComment("Thunk section index");
  808. OS.EmitCOFFSectionIndex(Fn);
  809. OS.AddComment("Code size");
  810. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
  811. OS.AddComment("Ordinal");
  812. OS.EmitIntValue(unsigned(ordinal), 1);
  813. OS.AddComment("Function name");
  814. emitNullTerminatedSymbolName(OS, FuncName);
  815. // Additional fields specific to the thunk ordinal would go here.
  816. endSymbolRecord(ThunkRecordEnd);
  817. // Local variables/inlined routines are purposely omitted here. The point of
  818. // marking this as a thunk is so Visual Studio will NOT stop in this routine.
  819. // Emit S_PROC_ID_END
  820. emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
  821. endCVSubsection(SymbolsEnd);
  822. }
  823. void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
  824. FunctionInfo &FI) {
  825. // For each function there is a separate subsection which holds the PC to
  826. // file:line table.
  827. const MCSymbol *Fn = Asm->getSymbol(GV);
  828. assert(Fn);
  829. // Switch to the to a comdat section, if appropriate.
  830. switchToDebugSectionForSymbol(Fn);
  831. std::string FuncName;
  832. auto *SP = GV->getSubprogram();
  833. assert(SP);
  834. setCurrentSubprogram(SP);
  835. if (SP->isThunk()) {
  836. emitDebugInfoForThunk(GV, FI, Fn);
  837. return;
  838. }
  839. // If we have a display name, build the fully qualified name by walking the
  840. // chain of scopes.
  841. if (!SP->getName().empty())
  842. FuncName =
  843. getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
  844. // If our DISubprogram name is empty, use the mangled name.
  845. if (FuncName.empty())
  846. FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
  847. // Emit FPO data, but only on 32-bit x86. No other platforms use it.
  848. if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
  849. OS.EmitCVFPOData(Fn);
  850. // Emit a symbol subsection, required by VS2012+ to find function boundaries.
  851. OS.AddComment("Symbol subsection for " + Twine(FuncName));
  852. MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
  853. {
  854. SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
  855. : SymbolKind::S_GPROC32_ID;
  856. MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
  857. // These fields are filled in by tools like CVPACK which run after the fact.
  858. OS.AddComment("PtrParent");
  859. OS.EmitIntValue(0, 4);
  860. OS.AddComment("PtrEnd");
  861. OS.EmitIntValue(0, 4);
  862. OS.AddComment("PtrNext");
  863. OS.EmitIntValue(0, 4);
  864. // This is the important bit that tells the debugger where the function
  865. // code is located and what's its size:
  866. OS.AddComment("Code size");
  867. OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
  868. OS.AddComment("Offset after prologue");
  869. OS.EmitIntValue(0, 4);
  870. OS.AddComment("Offset before epilogue");
  871. OS.EmitIntValue(0, 4);
  872. OS.AddComment("Function type index");
  873. OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
  874. OS.AddComment("Function section relative address");
  875. OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
  876. OS.AddComment("Function section index");
  877. OS.EmitCOFFSectionIndex(Fn);
  878. OS.AddComment("Flags");
  879. OS.EmitIntValue(0, 1);
  880. // Emit the function display name as a null-terminated string.
  881. OS.AddComment("Function name");
  882. // Truncate the name so we won't overflow the record length field.
  883. emitNullTerminatedSymbolName(OS, FuncName);
  884. endSymbolRecord(ProcRecordEnd);
  885. MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
  886. // Subtract out the CSR size since MSVC excludes that and we include it.
  887. OS.AddComment("FrameSize");
  888. OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
  889. OS.AddComment("Padding");
  890. OS.EmitIntValue(0, 4);
  891. OS.AddComment("Offset of padding");
  892. OS.EmitIntValue(0, 4);
  893. OS.AddComment("Bytes of callee saved registers");
  894. OS.EmitIntValue(FI.CSRSize, 4);
  895. OS.AddComment("Exception handler offset");
  896. OS.EmitIntValue(0, 4);
  897. OS.AddComment("Exception handler section");
  898. OS.EmitIntValue(0, 2);
  899. OS.AddComment("Flags (defines frame register)");
  900. OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
  901. endSymbolRecord(FrameProcEnd);
  902. emitLocalVariableList(FI, FI.Locals);
  903. emitGlobalVariableList(FI.Globals);
  904. emitLexicalBlockList(FI.ChildBlocks, FI);
  905. // Emit inlined call site information. Only emit functions inlined directly
  906. // into the parent function. We'll emit the other sites recursively as part
  907. // of their parent inline site.
  908. for (const DILocation *InlinedAt : FI.ChildSites) {
  909. auto I = FI.InlineSites.find(InlinedAt);
  910. assert(I != FI.InlineSites.end() &&
  911. "child site not in function inline site map");
  912. emitInlinedCallSite(FI, InlinedAt, I->second);
  913. }
  914. for (auto Annot : FI.Annotations) {
  915. MCSymbol *Label = Annot.first;
  916. MDTuple *Strs = cast<MDTuple>(Annot.second);
  917. MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
  918. OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
  919. // FIXME: Make sure we don't overflow the max record size.
  920. OS.EmitCOFFSectionIndex(Label);
  921. OS.EmitIntValue(Strs->getNumOperands(), 2);
  922. for (Metadata *MD : Strs->operands()) {
  923. // MDStrings are null terminated, so we can do EmitBytes and get the
  924. // nice .asciz directive.
  925. StringRef Str = cast<MDString>(MD)->getString();
  926. assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
  927. OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
  928. }
  929. endSymbolRecord(AnnotEnd);
  930. }
  931. if (SP != nullptr)
  932. emitDebugInfoForUDTs(LocalUDTs);
  933. // We're done with this function.
  934. emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
  935. }
  936. endCVSubsection(SymbolsEnd);
  937. // We have an assembler directive that takes care of the whole line table.
  938. OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
  939. }
  940. CodeViewDebug::LocalVarDefRange
  941. CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
  942. LocalVarDefRange DR;
  943. DR.InMemory = -1;
  944. DR.DataOffset = Offset;
  945. assert(DR.DataOffset == Offset && "truncation");
  946. DR.IsSubfield = 0;
  947. DR.StructOffset = 0;
  948. DR.CVRegister = CVRegister;
  949. return DR;
  950. }
  951. void CodeViewDebug::collectVariableInfoFromMFTable(
  952. DenseSet<InlinedEntity> &Processed) {
  953. const MachineFunction &MF = *Asm->MF;
  954. const TargetSubtargetInfo &TSI = MF.getSubtarget();
  955. const TargetFrameLowering *TFI = TSI.getFrameLowering();
  956. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  957. for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
  958. if (!VI.Var)
  959. continue;
  960. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  961. "Expected inlined-at fields to agree");
  962. Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
  963. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  964. // If variable scope is not found then skip this variable.
  965. if (!Scope)
  966. continue;
  967. // If the variable has an attached offset expression, extract it.
  968. // FIXME: Try to handle DW_OP_deref as well.
  969. int64_t ExprOffset = 0;
  970. if (VI.Expr)
  971. if (!VI.Expr->extractIfOffset(ExprOffset))
  972. continue;
  973. // Get the frame register used and the offset.
  974. unsigned FrameReg = 0;
  975. int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
  976. uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
  977. // Calculate the label ranges.
  978. LocalVarDefRange DefRange =
  979. createDefRangeMem(CVReg, FrameOffset + ExprOffset);
  980. for (const InsnRange &Range : Scope->getRanges()) {
  981. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  982. const MCSymbol *End = getLabelAfterInsn(Range.second);
  983. End = End ? End : Asm->getFunctionEnd();
  984. DefRange.Ranges.emplace_back(Begin, End);
  985. }
  986. LocalVariable Var;
  987. Var.DIVar = VI.Var;
  988. Var.DefRanges.emplace_back(std::move(DefRange));
  989. recordLocalVariable(std::move(Var), Scope);
  990. }
  991. }
  992. static bool canUseReferenceType(const DbgVariableLocation &Loc) {
  993. return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
  994. }
  995. static bool needsReferenceType(const DbgVariableLocation &Loc) {
  996. return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
  997. }
  998. void CodeViewDebug::calculateRanges(
  999. LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
  1000. const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
  1001. // Calculate the definition ranges.
  1002. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  1003. const InsnRange &Range = *I;
  1004. const MachineInstr *DVInst = Range.first;
  1005. assert(DVInst->isDebugValue() && "Invalid History entry");
  1006. // FIXME: Find a way to represent constant variables, since they are
  1007. // relatively common.
  1008. Optional<DbgVariableLocation> Location =
  1009. DbgVariableLocation::extractFromMachineInstruction(*DVInst);
  1010. if (!Location)
  1011. continue;
  1012. // CodeView can only express variables in register and variables in memory
  1013. // at a constant offset from a register. However, for variables passed
  1014. // indirectly by pointer, it is common for that pointer to be spilled to a
  1015. // stack location. For the special case of one offseted load followed by a
  1016. // zero offset load (a pointer spilled to the stack), we change the type of
  1017. // the local variable from a value type to a reference type. This tricks the
  1018. // debugger into doing the load for us.
  1019. if (Var.UseReferenceType) {
  1020. // We're using a reference type. Drop the last zero offset load.
  1021. if (canUseReferenceType(*Location))
  1022. Location->LoadChain.pop_back();
  1023. else
  1024. continue;
  1025. } else if (needsReferenceType(*Location)) {
  1026. // This location can't be expressed without switching to a reference type.
  1027. // Start over using that.
  1028. Var.UseReferenceType = true;
  1029. Var.DefRanges.clear();
  1030. calculateRanges(Var, Ranges);
  1031. return;
  1032. }
  1033. // We can only handle a register or an offseted load of a register.
  1034. if (Location->Register == 0 || Location->LoadChain.size() > 1)
  1035. continue;
  1036. {
  1037. LocalVarDefRange DR;
  1038. DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
  1039. DR.InMemory = !Location->LoadChain.empty();
  1040. DR.DataOffset =
  1041. !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
  1042. if (Location->FragmentInfo) {
  1043. DR.IsSubfield = true;
  1044. DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
  1045. } else {
  1046. DR.IsSubfield = false;
  1047. DR.StructOffset = 0;
  1048. }
  1049. if (Var.DefRanges.empty() ||
  1050. Var.DefRanges.back().isDifferentLocation(DR)) {
  1051. Var.DefRanges.emplace_back(std::move(DR));
  1052. }
  1053. }
  1054. // Compute the label range.
  1055. const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
  1056. const MCSymbol *End = getLabelAfterInsn(Range.second);
  1057. if (!End) {
  1058. // This range is valid until the next overlapping bitpiece. In the
  1059. // common case, ranges will not be bitpieces, so they will overlap.
  1060. auto J = std::next(I);
  1061. const DIExpression *DIExpr = DVInst->getDebugExpression();
  1062. while (J != E &&
  1063. !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
  1064. ++J;
  1065. if (J != E)
  1066. End = getLabelBeforeInsn(J->first);
  1067. else
  1068. End = Asm->getFunctionEnd();
  1069. }
  1070. // If the last range end is our begin, just extend the last range.
  1071. // Otherwise make a new range.
  1072. SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
  1073. Var.DefRanges.back().Ranges;
  1074. if (!R.empty() && R.back().second == Begin)
  1075. R.back().second = End;
  1076. else
  1077. R.emplace_back(Begin, End);
  1078. // FIXME: Do more range combining.
  1079. }
  1080. }
  1081. void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
  1082. DenseSet<InlinedEntity> Processed;
  1083. // Grab the variable info that was squirreled away in the MMI side-table.
  1084. collectVariableInfoFromMFTable(Processed);
  1085. for (const auto &I : DbgValues) {
  1086. InlinedEntity IV = I.first;
  1087. if (Processed.count(IV))
  1088. continue;
  1089. const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
  1090. const DILocation *InlinedAt = IV.second;
  1091. // Instruction ranges, specifying where IV is accessible.
  1092. const auto &Ranges = I.second;
  1093. LexicalScope *Scope = nullptr;
  1094. if (InlinedAt)
  1095. Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
  1096. else
  1097. Scope = LScopes.findLexicalScope(DIVar->getScope());
  1098. // If variable scope is not found then skip this variable.
  1099. if (!Scope)
  1100. continue;
  1101. LocalVariable Var;
  1102. Var.DIVar = DIVar;
  1103. calculateRanges(Var, Ranges);
  1104. recordLocalVariable(std::move(Var), Scope);
  1105. }
  1106. }
  1107. void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
  1108. const TargetSubtargetInfo &TSI = MF->getSubtarget();
  1109. const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
  1110. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1111. const Function &GV = MF->getFunction();
  1112. auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
  1113. assert(Insertion.second && "function already has info");
  1114. CurFn = Insertion.first->second.get();
  1115. CurFn->FuncId = NextFuncId++;
  1116. CurFn->Begin = Asm->getFunctionBegin();
  1117. // The S_FRAMEPROC record reports the stack size, and how many bytes of
  1118. // callee-saved registers were used. For targets that don't use a PUSH
  1119. // instruction (AArch64), this will be zero.
  1120. CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
  1121. CurFn->FrameSize = MFI.getStackSize();
  1122. CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
  1123. CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
  1124. // For this function S_FRAMEPROC record, figure out which codeview register
  1125. // will be the frame pointer.
  1126. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
  1127. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
  1128. if (CurFn->FrameSize > 0) {
  1129. if (!TSI.getFrameLowering()->hasFP(*MF)) {
  1130. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
  1131. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
  1132. } else {
  1133. // If there is an FP, parameters are always relative to it.
  1134. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
  1135. if (CurFn->HasStackRealignment) {
  1136. // If the stack needs realignment, locals are relative to SP or VFRAME.
  1137. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
  1138. } else {
  1139. // Otherwise, locals are relative to EBP, and we probably have VLAs or
  1140. // other stack adjustments.
  1141. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
  1142. }
  1143. }
  1144. }
  1145. // Compute other frame procedure options.
  1146. FrameProcedureOptions FPO = FrameProcedureOptions::None;
  1147. if (MFI.hasVarSizedObjects())
  1148. FPO |= FrameProcedureOptions::HasAlloca;
  1149. if (MF->exposesReturnsTwice())
  1150. FPO |= FrameProcedureOptions::HasSetJmp;
  1151. // FIXME: Set HasLongJmp if we ever track that info.
  1152. if (MF->hasInlineAsm())
  1153. FPO |= FrameProcedureOptions::HasInlineAssembly;
  1154. if (GV.hasPersonalityFn()) {
  1155. if (isAsynchronousEHPersonality(
  1156. classifyEHPersonality(GV.getPersonalityFn())))
  1157. FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
  1158. else
  1159. FPO |= FrameProcedureOptions::HasExceptionHandling;
  1160. }
  1161. if (GV.hasFnAttribute(Attribute::InlineHint))
  1162. FPO |= FrameProcedureOptions::MarkedInline;
  1163. if (GV.hasFnAttribute(Attribute::Naked))
  1164. FPO |= FrameProcedureOptions::Naked;
  1165. if (MFI.hasStackProtectorIndex())
  1166. FPO |= FrameProcedureOptions::SecurityChecks;
  1167. FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
  1168. FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
  1169. if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
  1170. !GV.hasOptSize() && !GV.hasOptNone())
  1171. FPO |= FrameProcedureOptions::OptimizedForSpeed;
  1172. // FIXME: Set GuardCfg when it is implemented.
  1173. CurFn->FrameProcOpts = FPO;
  1174. OS.EmitCVFuncIdDirective(CurFn->FuncId);
  1175. // Find the end of the function prolog. First known non-DBG_VALUE and
  1176. // non-frame setup location marks the beginning of the function body.
  1177. // FIXME: is there a simpler a way to do this? Can we just search
  1178. // for the first instruction of the function, not the last of the prolog?
  1179. DebugLoc PrologEndLoc;
  1180. bool EmptyPrologue = true;
  1181. for (const auto &MBB : *MF) {
  1182. for (const auto &MI : MBB) {
  1183. if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
  1184. MI.getDebugLoc()) {
  1185. PrologEndLoc = MI.getDebugLoc();
  1186. break;
  1187. } else if (!MI.isMetaInstruction()) {
  1188. EmptyPrologue = false;
  1189. }
  1190. }
  1191. }
  1192. // Record beginning of function if we have a non-empty prologue.
  1193. if (PrologEndLoc && !EmptyPrologue) {
  1194. DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
  1195. maybeRecordLocation(FnStartDL, MF);
  1196. }
  1197. }
  1198. static bool shouldEmitUdt(const DIType *T) {
  1199. if (!T)
  1200. return false;
  1201. // MSVC does not emit UDTs for typedefs that are scoped to classes.
  1202. if (T->getTag() == dwarf::DW_TAG_typedef) {
  1203. if (DIScope *Scope = T->getScope().resolve()) {
  1204. switch (Scope->getTag()) {
  1205. case dwarf::DW_TAG_structure_type:
  1206. case dwarf::DW_TAG_class_type:
  1207. case dwarf::DW_TAG_union_type:
  1208. return false;
  1209. }
  1210. }
  1211. }
  1212. while (true) {
  1213. if (!T || T->isForwardDecl())
  1214. return false;
  1215. const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
  1216. if (!DT)
  1217. return true;
  1218. T = DT->getBaseType().resolve();
  1219. }
  1220. return true;
  1221. }
  1222. void CodeViewDebug::addToUDTs(const DIType *Ty) {
  1223. // Don't record empty UDTs.
  1224. if (Ty->getName().empty())
  1225. return;
  1226. if (!shouldEmitUdt(Ty))
  1227. return;
  1228. SmallVector<StringRef, 5> QualifiedNameComponents;
  1229. const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
  1230. Ty->getScope().resolve(), QualifiedNameComponents);
  1231. std::string FullyQualifiedName =
  1232. getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
  1233. if (ClosestSubprogram == nullptr) {
  1234. GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
  1235. } else if (ClosestSubprogram == CurrentSubprogram) {
  1236. LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
  1237. }
  1238. // TODO: What if the ClosestSubprogram is neither null or the current
  1239. // subprogram? Currently, the UDT just gets dropped on the floor.
  1240. //
  1241. // The current behavior is not desirable. To get maximal fidelity, we would
  1242. // need to perform all type translation before beginning emission of .debug$S
  1243. // and then make LocalUDTs a member of FunctionInfo
  1244. }
  1245. TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
  1246. // Generic dispatch for lowering an unknown type.
  1247. switch (Ty->getTag()) {
  1248. case dwarf::DW_TAG_array_type:
  1249. return lowerTypeArray(cast<DICompositeType>(Ty));
  1250. case dwarf::DW_TAG_typedef:
  1251. return lowerTypeAlias(cast<DIDerivedType>(Ty));
  1252. case dwarf::DW_TAG_base_type:
  1253. return lowerTypeBasic(cast<DIBasicType>(Ty));
  1254. case dwarf::DW_TAG_pointer_type:
  1255. if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
  1256. return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
  1257. LLVM_FALLTHROUGH;
  1258. case dwarf::DW_TAG_reference_type:
  1259. case dwarf::DW_TAG_rvalue_reference_type:
  1260. return lowerTypePointer(cast<DIDerivedType>(Ty));
  1261. case dwarf::DW_TAG_ptr_to_member_type:
  1262. return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
  1263. case dwarf::DW_TAG_restrict_type:
  1264. case dwarf::DW_TAG_const_type:
  1265. case dwarf::DW_TAG_volatile_type:
  1266. // TODO: add support for DW_TAG_atomic_type here
  1267. return lowerTypeModifier(cast<DIDerivedType>(Ty));
  1268. case dwarf::DW_TAG_subroutine_type:
  1269. if (ClassTy) {
  1270. // The member function type of a member function pointer has no
  1271. // ThisAdjustment.
  1272. return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
  1273. /*ThisAdjustment=*/0,
  1274. /*IsStaticMethod=*/false);
  1275. }
  1276. return lowerTypeFunction(cast<DISubroutineType>(Ty));
  1277. case dwarf::DW_TAG_enumeration_type:
  1278. return lowerTypeEnum(cast<DICompositeType>(Ty));
  1279. case dwarf::DW_TAG_class_type:
  1280. case dwarf::DW_TAG_structure_type:
  1281. return lowerTypeClass(cast<DICompositeType>(Ty));
  1282. case dwarf::DW_TAG_union_type:
  1283. return lowerTypeUnion(cast<DICompositeType>(Ty));
  1284. case dwarf::DW_TAG_unspecified_type:
  1285. if (Ty->getName() == "decltype(nullptr)")
  1286. return TypeIndex::NullptrT();
  1287. return TypeIndex::None();
  1288. default:
  1289. // Use the null type index.
  1290. return TypeIndex();
  1291. }
  1292. }
  1293. TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
  1294. DITypeRef UnderlyingTypeRef = Ty->getBaseType();
  1295. TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
  1296. StringRef TypeName = Ty->getName();
  1297. addToUDTs(Ty);
  1298. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
  1299. TypeName == "HRESULT")
  1300. return TypeIndex(SimpleTypeKind::HResult);
  1301. if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
  1302. TypeName == "wchar_t")
  1303. return TypeIndex(SimpleTypeKind::WideCharacter);
  1304. return UnderlyingTypeIndex;
  1305. }
  1306. TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
  1307. DITypeRef ElementTypeRef = Ty->getBaseType();
  1308. TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
  1309. // IndexType is size_t, which depends on the bitness of the target.
  1310. TypeIndex IndexType = getPointerSizeInBytes() == 8
  1311. ? TypeIndex(SimpleTypeKind::UInt64Quad)
  1312. : TypeIndex(SimpleTypeKind::UInt32Long);
  1313. uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
  1314. // Add subranges to array type.
  1315. DINodeArray Elements = Ty->getElements();
  1316. for (int i = Elements.size() - 1; i >= 0; --i) {
  1317. const DINode *Element = Elements[i];
  1318. assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
  1319. const DISubrange *Subrange = cast<DISubrange>(Element);
  1320. assert(Subrange->getLowerBound() == 0 &&
  1321. "codeview doesn't support subranges with lower bounds");
  1322. int64_t Count = -1;
  1323. if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
  1324. Count = CI->getSExtValue();
  1325. // Forward declarations of arrays without a size and VLAs use a count of -1.
  1326. // Emit a count of zero in these cases to match what MSVC does for arrays
  1327. // without a size. MSVC doesn't support VLAs, so it's not clear what we
  1328. // should do for them even if we could distinguish them.
  1329. if (Count == -1)
  1330. Count = 0;
  1331. // Update the element size and element type index for subsequent subranges.
  1332. ElementSize *= Count;
  1333. // If this is the outermost array, use the size from the array. It will be
  1334. // more accurate if we had a VLA or an incomplete element type size.
  1335. uint64_t ArraySize =
  1336. (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
  1337. StringRef Name = (i == 0) ? Ty->getName() : "";
  1338. ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
  1339. ElementTypeIndex = TypeTable.writeLeafType(AR);
  1340. }
  1341. return ElementTypeIndex;
  1342. }
  1343. TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
  1344. TypeIndex Index;
  1345. dwarf::TypeKind Kind;
  1346. uint32_t ByteSize;
  1347. Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
  1348. ByteSize = Ty->getSizeInBits() / 8;
  1349. SimpleTypeKind STK = SimpleTypeKind::None;
  1350. switch (Kind) {
  1351. case dwarf::DW_ATE_address:
  1352. // FIXME: Translate
  1353. break;
  1354. case dwarf::DW_ATE_boolean:
  1355. switch (ByteSize) {
  1356. case 1: STK = SimpleTypeKind::Boolean8; break;
  1357. case 2: STK = SimpleTypeKind::Boolean16; break;
  1358. case 4: STK = SimpleTypeKind::Boolean32; break;
  1359. case 8: STK = SimpleTypeKind::Boolean64; break;
  1360. case 16: STK = SimpleTypeKind::Boolean128; break;
  1361. }
  1362. break;
  1363. case dwarf::DW_ATE_complex_float:
  1364. switch (ByteSize) {
  1365. case 2: STK = SimpleTypeKind::Complex16; break;
  1366. case 4: STK = SimpleTypeKind::Complex32; break;
  1367. case 8: STK = SimpleTypeKind::Complex64; break;
  1368. case 10: STK = SimpleTypeKind::Complex80; break;
  1369. case 16: STK = SimpleTypeKind::Complex128; break;
  1370. }
  1371. break;
  1372. case dwarf::DW_ATE_float:
  1373. switch (ByteSize) {
  1374. case 2: STK = SimpleTypeKind::Float16; break;
  1375. case 4: STK = SimpleTypeKind::Float32; break;
  1376. case 6: STK = SimpleTypeKind::Float48; break;
  1377. case 8: STK = SimpleTypeKind::Float64; break;
  1378. case 10: STK = SimpleTypeKind::Float80; break;
  1379. case 16: STK = SimpleTypeKind::Float128; break;
  1380. }
  1381. break;
  1382. case dwarf::DW_ATE_signed:
  1383. switch (ByteSize) {
  1384. case 1: STK = SimpleTypeKind::SignedCharacter; break;
  1385. case 2: STK = SimpleTypeKind::Int16Short; break;
  1386. case 4: STK = SimpleTypeKind::Int32; break;
  1387. case 8: STK = SimpleTypeKind::Int64Quad; break;
  1388. case 16: STK = SimpleTypeKind::Int128Oct; break;
  1389. }
  1390. break;
  1391. case dwarf::DW_ATE_unsigned:
  1392. switch (ByteSize) {
  1393. case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
  1394. case 2: STK = SimpleTypeKind::UInt16Short; break;
  1395. case 4: STK = SimpleTypeKind::UInt32; break;
  1396. case 8: STK = SimpleTypeKind::UInt64Quad; break;
  1397. case 16: STK = SimpleTypeKind::UInt128Oct; break;
  1398. }
  1399. break;
  1400. case dwarf::DW_ATE_UTF:
  1401. switch (ByteSize) {
  1402. case 2: STK = SimpleTypeKind::Character16; break;
  1403. case 4: STK = SimpleTypeKind::Character32; break;
  1404. }
  1405. break;
  1406. case dwarf::DW_ATE_signed_char:
  1407. if (ByteSize == 1)
  1408. STK = SimpleTypeKind::SignedCharacter;
  1409. break;
  1410. case dwarf::DW_ATE_unsigned_char:
  1411. if (ByteSize == 1)
  1412. STK = SimpleTypeKind::UnsignedCharacter;
  1413. break;
  1414. default:
  1415. break;
  1416. }
  1417. // Apply some fixups based on the source-level type name.
  1418. if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
  1419. STK = SimpleTypeKind::Int32Long;
  1420. if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
  1421. STK = SimpleTypeKind::UInt32Long;
  1422. if (STK == SimpleTypeKind::UInt16Short &&
  1423. (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
  1424. STK = SimpleTypeKind::WideCharacter;
  1425. if ((STK == SimpleTypeKind::SignedCharacter ||
  1426. STK == SimpleTypeKind::UnsignedCharacter) &&
  1427. Ty->getName() == "char")
  1428. STK = SimpleTypeKind::NarrowCharacter;
  1429. return TypeIndex(STK);
  1430. }
  1431. TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
  1432. PointerOptions PO) {
  1433. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
  1434. // Pointers to simple types without any options can use SimpleTypeMode, rather
  1435. // than having a dedicated pointer type record.
  1436. if (PointeeTI.isSimple() && PO == PointerOptions::None &&
  1437. PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
  1438. Ty->getTag() == dwarf::DW_TAG_pointer_type) {
  1439. SimpleTypeMode Mode = Ty->getSizeInBits() == 64
  1440. ? SimpleTypeMode::NearPointer64
  1441. : SimpleTypeMode::NearPointer32;
  1442. return TypeIndex(PointeeTI.getSimpleKind(), Mode);
  1443. }
  1444. PointerKind PK =
  1445. Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
  1446. PointerMode PM = PointerMode::Pointer;
  1447. switch (Ty->getTag()) {
  1448. default: llvm_unreachable("not a pointer tag type");
  1449. case dwarf::DW_TAG_pointer_type:
  1450. PM = PointerMode::Pointer;
  1451. break;
  1452. case dwarf::DW_TAG_reference_type:
  1453. PM = PointerMode::LValueReference;
  1454. break;
  1455. case dwarf::DW_TAG_rvalue_reference_type:
  1456. PM = PointerMode::RValueReference;
  1457. break;
  1458. }
  1459. if (Ty->isObjectPointer())
  1460. PO |= PointerOptions::Const;
  1461. PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
  1462. return TypeTable.writeLeafType(PR);
  1463. }
  1464. static PointerToMemberRepresentation
  1465. translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
  1466. // SizeInBytes being zero generally implies that the member pointer type was
  1467. // incomplete, which can happen if it is part of a function prototype. In this
  1468. // case, use the unknown model instead of the general model.
  1469. if (IsPMF) {
  1470. switch (Flags & DINode::FlagPtrToMemberRep) {
  1471. case 0:
  1472. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1473. : PointerToMemberRepresentation::GeneralFunction;
  1474. case DINode::FlagSingleInheritance:
  1475. return PointerToMemberRepresentation::SingleInheritanceFunction;
  1476. case DINode::FlagMultipleInheritance:
  1477. return PointerToMemberRepresentation::MultipleInheritanceFunction;
  1478. case DINode::FlagVirtualInheritance:
  1479. return PointerToMemberRepresentation::VirtualInheritanceFunction;
  1480. }
  1481. } else {
  1482. switch (Flags & DINode::FlagPtrToMemberRep) {
  1483. case 0:
  1484. return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
  1485. : PointerToMemberRepresentation::GeneralData;
  1486. case DINode::FlagSingleInheritance:
  1487. return PointerToMemberRepresentation::SingleInheritanceData;
  1488. case DINode::FlagMultipleInheritance:
  1489. return PointerToMemberRepresentation::MultipleInheritanceData;
  1490. case DINode::FlagVirtualInheritance:
  1491. return PointerToMemberRepresentation::VirtualInheritanceData;
  1492. }
  1493. }
  1494. llvm_unreachable("invalid ptr to member representation");
  1495. }
  1496. TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
  1497. PointerOptions PO) {
  1498. assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
  1499. TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
  1500. TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
  1501. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  1502. : PointerKind::Near32;
  1503. bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
  1504. PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
  1505. : PointerMode::PointerToDataMember;
  1506. assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
  1507. uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
  1508. MemberPointerInfo MPI(
  1509. ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
  1510. PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
  1511. return TypeTable.writeLeafType(PR);
  1512. }
  1513. /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
  1514. /// have a translation, use the NearC convention.
  1515. static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
  1516. switch (DwarfCC) {
  1517. case dwarf::DW_CC_normal: return CallingConvention::NearC;
  1518. case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
  1519. case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
  1520. case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
  1521. case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
  1522. case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
  1523. }
  1524. return CallingConvention::NearC;
  1525. }
  1526. TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
  1527. ModifierOptions Mods = ModifierOptions::None;
  1528. PointerOptions PO = PointerOptions::None;
  1529. bool IsModifier = true;
  1530. const DIType *BaseTy = Ty;
  1531. while (IsModifier && BaseTy) {
  1532. // FIXME: Need to add DWARF tags for __unaligned and _Atomic
  1533. switch (BaseTy->getTag()) {
  1534. case dwarf::DW_TAG_const_type:
  1535. Mods |= ModifierOptions::Const;
  1536. PO |= PointerOptions::Const;
  1537. break;
  1538. case dwarf::DW_TAG_volatile_type:
  1539. Mods |= ModifierOptions::Volatile;
  1540. PO |= PointerOptions::Volatile;
  1541. break;
  1542. case dwarf::DW_TAG_restrict_type:
  1543. // Only pointer types be marked with __restrict. There is no known flag
  1544. // for __restrict in LF_MODIFIER records.
  1545. PO |= PointerOptions::Restrict;
  1546. break;
  1547. default:
  1548. IsModifier = false;
  1549. break;
  1550. }
  1551. if (IsModifier)
  1552. BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
  1553. }
  1554. // Check if the inner type will use an LF_POINTER record. If so, the
  1555. // qualifiers will go in the LF_POINTER record. This comes up for types like
  1556. // 'int *const' and 'int *__restrict', not the more common cases like 'const
  1557. // char *'.
  1558. if (BaseTy) {
  1559. switch (BaseTy->getTag()) {
  1560. case dwarf::DW_TAG_pointer_type:
  1561. case dwarf::DW_TAG_reference_type:
  1562. case dwarf::DW_TAG_rvalue_reference_type:
  1563. return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
  1564. case dwarf::DW_TAG_ptr_to_member_type:
  1565. return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
  1566. default:
  1567. break;
  1568. }
  1569. }
  1570. TypeIndex ModifiedTI = getTypeIndex(BaseTy);
  1571. // Return the base type index if there aren't any modifiers. For example, the
  1572. // metadata could contain restrict wrappers around non-pointer types.
  1573. if (Mods == ModifierOptions::None)
  1574. return ModifiedTI;
  1575. ModifierRecord MR(ModifiedTI, Mods);
  1576. return TypeTable.writeLeafType(MR);
  1577. }
  1578. TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
  1579. SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
  1580. for (DITypeRef ArgTypeRef : Ty->getTypeArray())
  1581. ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
  1582. // MSVC uses type none for variadic argument.
  1583. if (ReturnAndArgTypeIndices.size() > 1 &&
  1584. ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
  1585. ReturnAndArgTypeIndices.back() = TypeIndex::None();
  1586. }
  1587. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1588. ArrayRef<TypeIndex> ArgTypeIndices = None;
  1589. if (!ReturnAndArgTypeIndices.empty()) {
  1590. auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
  1591. ReturnTypeIndex = ReturnAndArgTypesRef.front();
  1592. ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
  1593. }
  1594. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1595. TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
  1596. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1597. FunctionOptions FO = getFunctionOptions(Ty);
  1598. ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
  1599. ArgListIndex);
  1600. return TypeTable.writeLeafType(Procedure);
  1601. }
  1602. TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
  1603. const DIType *ClassTy,
  1604. int ThisAdjustment,
  1605. bool IsStaticMethod,
  1606. FunctionOptions FO) {
  1607. // Lower the containing class type.
  1608. TypeIndex ClassType = getTypeIndex(ClassTy);
  1609. DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
  1610. unsigned Index = 0;
  1611. SmallVector<TypeIndex, 8> ArgTypeIndices;
  1612. TypeIndex ReturnTypeIndex = TypeIndex::Void();
  1613. if (ReturnAndArgs.size() > Index) {
  1614. ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
  1615. }
  1616. // If the first argument is a pointer type and this isn't a static method,
  1617. // treat it as the special 'this' parameter, which is encoded separately from
  1618. // the arguments.
  1619. TypeIndex ThisTypeIndex;
  1620. if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
  1621. if (const DIDerivedType *PtrTy =
  1622. dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index].resolve())) {
  1623. if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
  1624. ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
  1625. Index++;
  1626. }
  1627. }
  1628. }
  1629. while (Index < ReturnAndArgs.size())
  1630. ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
  1631. // MSVC uses type none for variadic argument.
  1632. if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
  1633. ArgTypeIndices.back() = TypeIndex::None();
  1634. ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
  1635. TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
  1636. CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
  1637. MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
  1638. ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
  1639. return TypeTable.writeLeafType(MFR);
  1640. }
  1641. TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
  1642. unsigned VSlotCount =
  1643. Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
  1644. SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
  1645. VFTableShapeRecord VFTSR(Slots);
  1646. return TypeTable.writeLeafType(VFTSR);
  1647. }
  1648. static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
  1649. switch (Flags & DINode::FlagAccessibility) {
  1650. case DINode::FlagPrivate: return MemberAccess::Private;
  1651. case DINode::FlagPublic: return MemberAccess::Public;
  1652. case DINode::FlagProtected: return MemberAccess::Protected;
  1653. case 0:
  1654. // If there was no explicit access control, provide the default for the tag.
  1655. return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
  1656. : MemberAccess::Public;
  1657. }
  1658. llvm_unreachable("access flags are exclusive");
  1659. }
  1660. static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
  1661. if (SP->isArtificial())
  1662. return MethodOptions::CompilerGenerated;
  1663. // FIXME: Handle other MethodOptions.
  1664. return MethodOptions::None;
  1665. }
  1666. static MethodKind translateMethodKindFlags(const DISubprogram *SP,
  1667. bool Introduced) {
  1668. if (SP->getFlags() & DINode::FlagStaticMember)
  1669. return MethodKind::Static;
  1670. switch (SP->getVirtuality()) {
  1671. case dwarf::DW_VIRTUALITY_none:
  1672. break;
  1673. case dwarf::DW_VIRTUALITY_virtual:
  1674. return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
  1675. case dwarf::DW_VIRTUALITY_pure_virtual:
  1676. return Introduced ? MethodKind::PureIntroducingVirtual
  1677. : MethodKind::PureVirtual;
  1678. default:
  1679. llvm_unreachable("unhandled virtuality case");
  1680. }
  1681. return MethodKind::Vanilla;
  1682. }
  1683. static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
  1684. switch (Ty->getTag()) {
  1685. case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
  1686. case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
  1687. }
  1688. llvm_unreachable("unexpected tag");
  1689. }
  1690. /// Return ClassOptions that should be present on both the forward declaration
  1691. /// and the defintion of a tag type.
  1692. static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
  1693. ClassOptions CO = ClassOptions::None;
  1694. // MSVC always sets this flag, even for local types. Clang doesn't always
  1695. // appear to give every type a linkage name, which may be problematic for us.
  1696. // FIXME: Investigate the consequences of not following them here.
  1697. if (!Ty->getIdentifier().empty())
  1698. CO |= ClassOptions::HasUniqueName;
  1699. // Put the Nested flag on a type if it appears immediately inside a tag type.
  1700. // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
  1701. // here. That flag is only set on definitions, and not forward declarations.
  1702. const DIScope *ImmediateScope = Ty->getScope().resolve();
  1703. if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
  1704. CO |= ClassOptions::Nested;
  1705. // Put the Scoped flag on function-local types. MSVC puts this flag for enum
  1706. // type only when it has an immediate function scope. Clang never puts enums
  1707. // inside DILexicalBlock scopes. Enum types, as generated by clang, are
  1708. // always in function, class, or file scopes.
  1709. if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
  1710. if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
  1711. CO |= ClassOptions::Scoped;
  1712. } else {
  1713. for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
  1714. Scope = Scope->getScope().resolve()) {
  1715. if (isa<DISubprogram>(Scope)) {
  1716. CO |= ClassOptions::Scoped;
  1717. break;
  1718. }
  1719. }
  1720. }
  1721. return CO;
  1722. }
  1723. void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
  1724. switch (Ty->getTag()) {
  1725. case dwarf::DW_TAG_class_type:
  1726. case dwarf::DW_TAG_structure_type:
  1727. case dwarf::DW_TAG_union_type:
  1728. case dwarf::DW_TAG_enumeration_type:
  1729. break;
  1730. default:
  1731. return;
  1732. }
  1733. if (const auto *File = Ty->getFile()) {
  1734. StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
  1735. TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
  1736. UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
  1737. TypeTable.writeLeafType(USLR);
  1738. }
  1739. }
  1740. TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
  1741. ClassOptions CO = getCommonClassOptions(Ty);
  1742. TypeIndex FTI;
  1743. unsigned EnumeratorCount = 0;
  1744. if (Ty->isForwardDecl()) {
  1745. CO |= ClassOptions::ForwardReference;
  1746. } else {
  1747. ContinuationRecordBuilder ContinuationBuilder;
  1748. ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
  1749. for (const DINode *Element : Ty->getElements()) {
  1750. // We assume that the frontend provides all members in source declaration
  1751. // order, which is what MSVC does.
  1752. if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
  1753. EnumeratorRecord ER(MemberAccess::Public,
  1754. APSInt::getUnsigned(Enumerator->getValue()),
  1755. Enumerator->getName());
  1756. ContinuationBuilder.writeMemberType(ER);
  1757. EnumeratorCount++;
  1758. }
  1759. }
  1760. FTI = TypeTable.insertRecord(ContinuationBuilder);
  1761. }
  1762. std::string FullName = getFullyQualifiedName(Ty);
  1763. EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
  1764. getTypeIndex(Ty->getBaseType()));
  1765. TypeIndex EnumTI = TypeTable.writeLeafType(ER);
  1766. addUDTSrcLine(Ty, EnumTI);
  1767. return EnumTI;
  1768. }
  1769. //===----------------------------------------------------------------------===//
  1770. // ClassInfo
  1771. //===----------------------------------------------------------------------===//
  1772. struct llvm::ClassInfo {
  1773. struct MemberInfo {
  1774. const DIDerivedType *MemberTypeNode;
  1775. uint64_t BaseOffset;
  1776. };
  1777. // [MemberInfo]
  1778. using MemberList = std::vector<MemberInfo>;
  1779. using MethodsList = TinyPtrVector<const DISubprogram *>;
  1780. // MethodName -> MethodsList
  1781. using MethodsMap = MapVector<MDString *, MethodsList>;
  1782. /// Base classes.
  1783. std::vector<const DIDerivedType *> Inheritance;
  1784. /// Direct members.
  1785. MemberList Members;
  1786. // Direct overloaded methods gathered by name.
  1787. MethodsMap Methods;
  1788. TypeIndex VShapeTI;
  1789. std::vector<const DIType *> NestedTypes;
  1790. };
  1791. void CodeViewDebug::clear() {
  1792. assert(CurFn == nullptr);
  1793. FileIdMap.clear();
  1794. FnDebugInfo.clear();
  1795. FileToFilepathMap.clear();
  1796. LocalUDTs.clear();
  1797. GlobalUDTs.clear();
  1798. TypeIndices.clear();
  1799. CompleteTypeIndices.clear();
  1800. ScopeGlobals.clear();
  1801. }
  1802. void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
  1803. const DIDerivedType *DDTy) {
  1804. if (!DDTy->getName().empty()) {
  1805. Info.Members.push_back({DDTy, 0});
  1806. return;
  1807. }
  1808. // An unnamed member may represent a nested struct or union. Attempt to
  1809. // interpret the unnamed member as a DICompositeType possibly wrapped in
  1810. // qualifier types. Add all the indirect fields to the current record if that
  1811. // succeeds, and drop the member if that fails.
  1812. assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
  1813. uint64_t Offset = DDTy->getOffsetInBits();
  1814. const DIType *Ty = DDTy->getBaseType().resolve();
  1815. bool FullyResolved = false;
  1816. while (!FullyResolved) {
  1817. switch (Ty->getTag()) {
  1818. case dwarf::DW_TAG_const_type:
  1819. case dwarf::DW_TAG_volatile_type:
  1820. // FIXME: we should apply the qualifier types to the indirect fields
  1821. // rather than dropping them.
  1822. Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
  1823. break;
  1824. default:
  1825. FullyResolved = true;
  1826. break;
  1827. }
  1828. }
  1829. const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
  1830. if (!DCTy)
  1831. return;
  1832. ClassInfo NestedInfo = collectClassInfo(DCTy);
  1833. for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
  1834. Info.Members.push_back(
  1835. {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
  1836. }
  1837. ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
  1838. ClassInfo Info;
  1839. // Add elements to structure type.
  1840. DINodeArray Elements = Ty->getElements();
  1841. for (auto *Element : Elements) {
  1842. // We assume that the frontend provides all members in source declaration
  1843. // order, which is what MSVC does.
  1844. if (!Element)
  1845. continue;
  1846. if (auto *SP = dyn_cast<DISubprogram>(Element)) {
  1847. Info.Methods[SP->getRawName()].push_back(SP);
  1848. } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
  1849. if (DDTy->getTag() == dwarf::DW_TAG_member) {
  1850. collectMemberInfo(Info, DDTy);
  1851. } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
  1852. Info.Inheritance.push_back(DDTy);
  1853. } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
  1854. DDTy->getName() == "__vtbl_ptr_type") {
  1855. Info.VShapeTI = getTypeIndex(DDTy);
  1856. } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
  1857. Info.NestedTypes.push_back(DDTy);
  1858. } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
  1859. // Ignore friend members. It appears that MSVC emitted info about
  1860. // friends in the past, but modern versions do not.
  1861. }
  1862. } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
  1863. Info.NestedTypes.push_back(Composite);
  1864. }
  1865. // Skip other unrecognized kinds of elements.
  1866. }
  1867. return Info;
  1868. }
  1869. static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
  1870. // This routine is used by lowerTypeClass and lowerTypeUnion to determine
  1871. // if a complete type should be emitted instead of a forward reference.
  1872. return Ty->getName().empty() && Ty->getIdentifier().empty() &&
  1873. !Ty->isForwardDecl();
  1874. }
  1875. TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
  1876. // Emit the complete type for unnamed structs. C++ classes with methods
  1877. // which have a circular reference back to the class type are expected to
  1878. // be named by the front-end and should not be "unnamed". C unnamed
  1879. // structs should not have circular references.
  1880. if (shouldAlwaysEmitCompleteClassType(Ty)) {
  1881. // If this unnamed complete type is already in the process of being defined
  1882. // then the description of the type is malformed and cannot be emitted
  1883. // into CodeView correctly so report a fatal error.
  1884. auto I = CompleteTypeIndices.find(Ty);
  1885. if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
  1886. report_fatal_error("cannot debug circular reference to unnamed type");
  1887. return getCompleteTypeIndex(Ty);
  1888. }
  1889. // First, construct the forward decl. Don't look into Ty to compute the
  1890. // forward decl options, since it might not be available in all TUs.
  1891. TypeRecordKind Kind = getRecordKind(Ty);
  1892. ClassOptions CO =
  1893. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1894. std::string FullName = getFullyQualifiedName(Ty);
  1895. ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
  1896. FullName, Ty->getIdentifier());
  1897. TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
  1898. if (!Ty->isForwardDecl())
  1899. DeferredCompleteTypes.push_back(Ty);
  1900. return FwdDeclTI;
  1901. }
  1902. TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
  1903. // Construct the field list and complete type record.
  1904. TypeRecordKind Kind = getRecordKind(Ty);
  1905. ClassOptions CO = getCommonClassOptions(Ty);
  1906. TypeIndex FieldTI;
  1907. TypeIndex VShapeTI;
  1908. unsigned FieldCount;
  1909. bool ContainsNestedClass;
  1910. std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
  1911. lowerRecordFieldList(Ty);
  1912. if (ContainsNestedClass)
  1913. CO |= ClassOptions::ContainsNestedClass;
  1914. // MSVC appears to set this flag by searching any destructor or method with
  1915. // FunctionOptions::Constructor among the emitted members. Clang AST has all
  1916. // the members, however special member functions are not yet emitted into
  1917. // debug information. For now checking a class's non-triviality seems enough.
  1918. // FIXME: not true for a nested unnamed struct.
  1919. if (isNonTrivial(Ty))
  1920. CO |= ClassOptions::HasConstructorOrDestructor;
  1921. std::string FullName = getFullyQualifiedName(Ty);
  1922. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1923. ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
  1924. SizeInBytes, FullName, Ty->getIdentifier());
  1925. TypeIndex ClassTI = TypeTable.writeLeafType(CR);
  1926. addUDTSrcLine(Ty, ClassTI);
  1927. addToUDTs(Ty);
  1928. return ClassTI;
  1929. }
  1930. TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
  1931. // Emit the complete type for unnamed unions.
  1932. if (shouldAlwaysEmitCompleteClassType(Ty))
  1933. return getCompleteTypeIndex(Ty);
  1934. ClassOptions CO =
  1935. ClassOptions::ForwardReference | getCommonClassOptions(Ty);
  1936. std::string FullName = getFullyQualifiedName(Ty);
  1937. UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
  1938. TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
  1939. if (!Ty->isForwardDecl())
  1940. DeferredCompleteTypes.push_back(Ty);
  1941. return FwdDeclTI;
  1942. }
  1943. TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
  1944. ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
  1945. TypeIndex FieldTI;
  1946. unsigned FieldCount;
  1947. bool ContainsNestedClass;
  1948. std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
  1949. lowerRecordFieldList(Ty);
  1950. if (ContainsNestedClass)
  1951. CO |= ClassOptions::ContainsNestedClass;
  1952. uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
  1953. std::string FullName = getFullyQualifiedName(Ty);
  1954. UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
  1955. Ty->getIdentifier());
  1956. TypeIndex UnionTI = TypeTable.writeLeafType(UR);
  1957. addUDTSrcLine(Ty, UnionTI);
  1958. addToUDTs(Ty);
  1959. return UnionTI;
  1960. }
  1961. std::tuple<TypeIndex, TypeIndex, unsigned, bool>
  1962. CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
  1963. // Manually count members. MSVC appears to count everything that generates a
  1964. // field list record. Each individual overload in a method overload group
  1965. // contributes to this count, even though the overload group is a single field
  1966. // list record.
  1967. unsigned MemberCount = 0;
  1968. ClassInfo Info = collectClassInfo(Ty);
  1969. ContinuationRecordBuilder ContinuationBuilder;
  1970. ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
  1971. // Create base classes.
  1972. for (const DIDerivedType *I : Info.Inheritance) {
  1973. if (I->getFlags() & DINode::FlagVirtual) {
  1974. // Virtual base.
  1975. unsigned VBPtrOffset = I->getVBPtrOffset();
  1976. // FIXME: Despite the accessor name, the offset is really in bytes.
  1977. unsigned VBTableIndex = I->getOffsetInBits() / 4;
  1978. auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
  1979. ? TypeRecordKind::IndirectVirtualBaseClass
  1980. : TypeRecordKind::VirtualBaseClass;
  1981. VirtualBaseClassRecord VBCR(
  1982. RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
  1983. getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
  1984. VBTableIndex);
  1985. ContinuationBuilder.writeMemberType(VBCR);
  1986. MemberCount++;
  1987. } else {
  1988. assert(I->getOffsetInBits() % 8 == 0 &&
  1989. "bases must be on byte boundaries");
  1990. BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
  1991. getTypeIndex(I->getBaseType()),
  1992. I->getOffsetInBits() / 8);
  1993. ContinuationBuilder.writeMemberType(BCR);
  1994. MemberCount++;
  1995. }
  1996. }
  1997. // Create members.
  1998. for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
  1999. const DIDerivedType *Member = MemberInfo.MemberTypeNode;
  2000. TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
  2001. StringRef MemberName = Member->getName();
  2002. MemberAccess Access =
  2003. translateAccessFlags(Ty->getTag(), Member->getFlags());
  2004. if (Member->isStaticMember()) {
  2005. StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
  2006. ContinuationBuilder.writeMemberType(SDMR);
  2007. MemberCount++;
  2008. continue;
  2009. }
  2010. // Virtual function pointer member.
  2011. if ((Member->getFlags() & DINode::FlagArtificial) &&
  2012. Member->getName().startswith("_vptr$")) {
  2013. VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
  2014. ContinuationBuilder.writeMemberType(VFPR);
  2015. MemberCount++;
  2016. continue;
  2017. }
  2018. // Data member.
  2019. uint64_t MemberOffsetInBits =
  2020. Member->getOffsetInBits() + MemberInfo.BaseOffset;
  2021. if (Member->isBitField()) {
  2022. uint64_t StartBitOffset = MemberOffsetInBits;
  2023. if (const auto *CI =
  2024. dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
  2025. MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
  2026. }
  2027. StartBitOffset -= MemberOffsetInBits;
  2028. BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
  2029. StartBitOffset);
  2030. MemberBaseType = TypeTable.writeLeafType(BFR);
  2031. }
  2032. uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
  2033. DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
  2034. MemberName);
  2035. ContinuationBuilder.writeMemberType(DMR);
  2036. MemberCount++;
  2037. }
  2038. // Create methods
  2039. for (auto &MethodItr : Info.Methods) {
  2040. StringRef Name = MethodItr.first->getString();
  2041. std::vector<OneMethodRecord> Methods;
  2042. for (const DISubprogram *SP : MethodItr.second) {
  2043. TypeIndex MethodType = getMemberFunctionType(SP, Ty);
  2044. bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
  2045. unsigned VFTableOffset = -1;
  2046. if (Introduced)
  2047. VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
  2048. Methods.push_back(OneMethodRecord(
  2049. MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
  2050. translateMethodKindFlags(SP, Introduced),
  2051. translateMethodOptionFlags(SP), VFTableOffset, Name));
  2052. MemberCount++;
  2053. }
  2054. assert(!Methods.empty() && "Empty methods map entry");
  2055. if (Methods.size() == 1)
  2056. ContinuationBuilder.writeMemberType(Methods[0]);
  2057. else {
  2058. // FIXME: Make this use its own ContinuationBuilder so that
  2059. // MethodOverloadList can be split correctly.
  2060. MethodOverloadListRecord MOLR(Methods);
  2061. TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
  2062. OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
  2063. ContinuationBuilder.writeMemberType(OMR);
  2064. }
  2065. }
  2066. // Create nested classes.
  2067. for (const DIType *Nested : Info.NestedTypes) {
  2068. NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
  2069. ContinuationBuilder.writeMemberType(R);
  2070. MemberCount++;
  2071. }
  2072. TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
  2073. return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
  2074. !Info.NestedTypes.empty());
  2075. }
  2076. TypeIndex CodeViewDebug::getVBPTypeIndex() {
  2077. if (!VBPType.getIndex()) {
  2078. // Make a 'const int *' type.
  2079. ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
  2080. TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
  2081. PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
  2082. : PointerKind::Near32;
  2083. PointerMode PM = PointerMode::Pointer;
  2084. PointerOptions PO = PointerOptions::None;
  2085. PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
  2086. VBPType = TypeTable.writeLeafType(PR);
  2087. }
  2088. return VBPType;
  2089. }
  2090. TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
  2091. const DIType *Ty = TypeRef.resolve();
  2092. const DIType *ClassTy = ClassTyRef.resolve();
  2093. // The null DIType is the void type. Don't try to hash it.
  2094. if (!Ty)
  2095. return TypeIndex::Void();
  2096. // Check if we've already translated this type. Don't try to do a
  2097. // get-or-create style insertion that caches the hash lookup across the
  2098. // lowerType call. It will update the TypeIndices map.
  2099. auto I = TypeIndices.find({Ty, ClassTy});
  2100. if (I != TypeIndices.end())
  2101. return I->second;
  2102. TypeLoweringScope S(*this);
  2103. TypeIndex TI = lowerType(Ty, ClassTy);
  2104. return recordTypeIndexForDINode(Ty, TI, ClassTy);
  2105. }
  2106. codeview::TypeIndex
  2107. CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
  2108. const DISubroutineType *SubroutineTy) {
  2109. assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
  2110. "this type must be a pointer type");
  2111. PointerOptions Options = PointerOptions::None;
  2112. if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
  2113. Options = PointerOptions::LValueRefThisPointer;
  2114. else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
  2115. Options = PointerOptions::RValueRefThisPointer;
  2116. // Check if we've already translated this type. If there is no ref qualifier
  2117. // on the function then we look up this pointer type with no associated class
  2118. // so that the TypeIndex for the this pointer can be shared with the type
  2119. // index for other pointers to this class type. If there is a ref qualifier
  2120. // then we lookup the pointer using the subroutine as the parent type.
  2121. auto I = TypeIndices.find({PtrTy, SubroutineTy});
  2122. if (I != TypeIndices.end())
  2123. return I->second;
  2124. TypeLoweringScope S(*this);
  2125. TypeIndex TI = lowerTypePointer(PtrTy, Options);
  2126. return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
  2127. }
  2128. TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
  2129. DIType *Ty = TypeRef.resolve();
  2130. PointerRecord PR(getTypeIndex(Ty),
  2131. getPointerSizeInBytes() == 8 ? PointerKind::Near64
  2132. : PointerKind::Near32,
  2133. PointerMode::LValueReference, PointerOptions::None,
  2134. Ty->getSizeInBits() / 8);
  2135. return TypeTable.writeLeafType(PR);
  2136. }
  2137. TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
  2138. const DIType *Ty = TypeRef.resolve();
  2139. // The null DIType is the void type. Don't try to hash it.
  2140. if (!Ty)
  2141. return TypeIndex::Void();
  2142. // Look through typedefs when getting the complete type index. Call
  2143. // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
  2144. // emitted only once.
  2145. if (Ty->getTag() == dwarf::DW_TAG_typedef)
  2146. (void)getTypeIndex(Ty);
  2147. while (Ty->getTag() == dwarf::DW_TAG_typedef)
  2148. Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
  2149. // If this is a non-record type, the complete type index is the same as the
  2150. // normal type index. Just call getTypeIndex.
  2151. switch (Ty->getTag()) {
  2152. case dwarf::DW_TAG_class_type:
  2153. case dwarf::DW_TAG_structure_type:
  2154. case dwarf::DW_TAG_union_type:
  2155. break;
  2156. default:
  2157. return getTypeIndex(Ty);
  2158. }
  2159. // Check if we've already translated the complete record type.
  2160. const auto *CTy = cast<DICompositeType>(Ty);
  2161. auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
  2162. if (!InsertResult.second)
  2163. return InsertResult.first->second;
  2164. TypeLoweringScope S(*this);
  2165. // Make sure the forward declaration is emitted first. It's unclear if this
  2166. // is necessary, but MSVC does it, and we should follow suit until we can show
  2167. // otherwise.
  2168. // We only emit a forward declaration for named types.
  2169. if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
  2170. TypeIndex FwdDeclTI = getTypeIndex(CTy);
  2171. // Just use the forward decl if we don't have complete type info. This
  2172. // might happen if the frontend is using modules and expects the complete
  2173. // definition to be emitted elsewhere.
  2174. if (CTy->isForwardDecl())
  2175. return FwdDeclTI;
  2176. }
  2177. TypeIndex TI;
  2178. switch (CTy->getTag()) {
  2179. case dwarf::DW_TAG_class_type:
  2180. case dwarf::DW_TAG_structure_type:
  2181. TI = lowerCompleteTypeClass(CTy);
  2182. break;
  2183. case dwarf::DW_TAG_union_type:
  2184. TI = lowerCompleteTypeUnion(CTy);
  2185. break;
  2186. default:
  2187. llvm_unreachable("not a record");
  2188. }
  2189. // Update the type index associated with this CompositeType. This cannot
  2190. // use the 'InsertResult' iterator above because it is potentially
  2191. // invalidated by map insertions which can occur while lowering the class
  2192. // type above.
  2193. CompleteTypeIndices[CTy] = TI;
  2194. return TI;
  2195. }
  2196. /// Emit all the deferred complete record types. Try to do this in FIFO order,
  2197. /// and do this until fixpoint, as each complete record type typically
  2198. /// references
  2199. /// many other record types.
  2200. void CodeViewDebug::emitDeferredCompleteTypes() {
  2201. SmallVector<const DICompositeType *, 4> TypesToEmit;
  2202. while (!DeferredCompleteTypes.empty()) {
  2203. std::swap(DeferredCompleteTypes, TypesToEmit);
  2204. for (const DICompositeType *RecordTy : TypesToEmit)
  2205. getCompleteTypeIndex(RecordTy);
  2206. TypesToEmit.clear();
  2207. }
  2208. }
  2209. void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
  2210. ArrayRef<LocalVariable> Locals) {
  2211. // Get the sorted list of parameters and emit them first.
  2212. SmallVector<const LocalVariable *, 6> Params;
  2213. for (const LocalVariable &L : Locals)
  2214. if (L.DIVar->isParameter())
  2215. Params.push_back(&L);
  2216. llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
  2217. return L->DIVar->getArg() < R->DIVar->getArg();
  2218. });
  2219. for (const LocalVariable *L : Params)
  2220. emitLocalVariable(FI, *L);
  2221. // Next emit all non-parameters in the order that we found them.
  2222. for (const LocalVariable &L : Locals)
  2223. if (!L.DIVar->isParameter())
  2224. emitLocalVariable(FI, L);
  2225. }
  2226. /// Only call this on endian-specific types like ulittle16_t and little32_t, or
  2227. /// structs composed of them.
  2228. template <typename T>
  2229. static void copyBytesForDefRange(SmallString<20> &BytePrefix,
  2230. SymbolKind SymKind, const T &DefRangeHeader) {
  2231. BytePrefix.resize(2 + sizeof(T));
  2232. ulittle16_t SymKindLE = ulittle16_t(SymKind);
  2233. memcpy(&BytePrefix[0], &SymKindLE, 2);
  2234. memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
  2235. }
  2236. void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
  2237. const LocalVariable &Var) {
  2238. // LocalSym record, see SymbolRecord.h for more info.
  2239. MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
  2240. LocalSymFlags Flags = LocalSymFlags::None;
  2241. if (Var.DIVar->isParameter())
  2242. Flags |= LocalSymFlags::IsParameter;
  2243. if (Var.DefRanges.empty())
  2244. Flags |= LocalSymFlags::IsOptimizedOut;
  2245. OS.AddComment("TypeIndex");
  2246. TypeIndex TI = Var.UseReferenceType
  2247. ? getTypeIndexForReferenceTo(Var.DIVar->getType())
  2248. : getCompleteTypeIndex(Var.DIVar->getType());
  2249. OS.EmitIntValue(TI.getIndex(), 4);
  2250. OS.AddComment("Flags");
  2251. OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
  2252. // Truncate the name so we won't overflow the record length field.
  2253. emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
  2254. endSymbolRecord(LocalEnd);
  2255. // Calculate the on disk prefix of the appropriate def range record. The
  2256. // records and on disk formats are described in SymbolRecords.h. BytePrefix
  2257. // should be big enough to hold all forms without memory allocation.
  2258. SmallString<20> BytePrefix;
  2259. for (const LocalVarDefRange &DefRange : Var.DefRanges) {
  2260. BytePrefix.clear();
  2261. if (DefRange.InMemory) {
  2262. int Offset = DefRange.DataOffset;
  2263. unsigned Reg = DefRange.CVRegister;
  2264. // 32-bit x86 call sequences often use PUSH instructions, which disrupt
  2265. // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
  2266. // instead. In frames without stack realignment, $T0 will be the CFA.
  2267. if (RegisterId(Reg) == RegisterId::ESP) {
  2268. Reg = unsigned(RegisterId::VFRAME);
  2269. Offset += FI.OffsetAdjustment;
  2270. }
  2271. // If we can use the chosen frame pointer for the frame and this isn't a
  2272. // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
  2273. // Otherwise, use S_DEFRANGE_REGISTER_REL.
  2274. EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
  2275. if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
  2276. (bool(Flags & LocalSymFlags::IsParameter)
  2277. ? (EncFP == FI.EncodedParamFramePtrReg)
  2278. : (EncFP == FI.EncodedLocalFramePtrReg))) {
  2279. little32_t FPOffset = little32_t(Offset);
  2280. copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
  2281. } else {
  2282. uint16_t RegRelFlags = 0;
  2283. if (DefRange.IsSubfield) {
  2284. RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
  2285. (DefRange.StructOffset
  2286. << DefRangeRegisterRelSym::OffsetInParentShift);
  2287. }
  2288. DefRangeRegisterRelSym::Header DRHdr;
  2289. DRHdr.Register = Reg;
  2290. DRHdr.Flags = RegRelFlags;
  2291. DRHdr.BasePointerOffset = Offset;
  2292. copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
  2293. }
  2294. } else {
  2295. assert(DefRange.DataOffset == 0 && "unexpected offset into register");
  2296. if (DefRange.IsSubfield) {
  2297. DefRangeSubfieldRegisterSym::Header DRHdr;
  2298. DRHdr.Register = DefRange.CVRegister;
  2299. DRHdr.MayHaveNoName = 0;
  2300. DRHdr.OffsetInParent = DefRange.StructOffset;
  2301. copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
  2302. } else {
  2303. DefRangeRegisterSym::Header DRHdr;
  2304. DRHdr.Register = DefRange.CVRegister;
  2305. DRHdr.MayHaveNoName = 0;
  2306. copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
  2307. }
  2308. }
  2309. OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
  2310. }
  2311. }
  2312. void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
  2313. const FunctionInfo& FI) {
  2314. for (LexicalBlock *Block : Blocks)
  2315. emitLexicalBlock(*Block, FI);
  2316. }
  2317. /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
  2318. /// lexical block scope.
  2319. void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
  2320. const FunctionInfo& FI) {
  2321. MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
  2322. OS.AddComment("PtrParent");
  2323. OS.EmitIntValue(0, 4); // PtrParent
  2324. OS.AddComment("PtrEnd");
  2325. OS.EmitIntValue(0, 4); // PtrEnd
  2326. OS.AddComment("Code size");
  2327. OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
  2328. OS.AddComment("Function section relative address");
  2329. OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
  2330. OS.AddComment("Function section index");
  2331. OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
  2332. OS.AddComment("Lexical block name");
  2333. emitNullTerminatedSymbolName(OS, Block.Name); // Name
  2334. endSymbolRecord(RecordEnd);
  2335. // Emit variables local to this lexical block.
  2336. emitLocalVariableList(FI, Block.Locals);
  2337. emitGlobalVariableList(Block.Globals);
  2338. // Emit lexical blocks contained within this block.
  2339. emitLexicalBlockList(Block.Children, FI);
  2340. // Close the lexical block scope.
  2341. emitEndSymbolRecord(SymbolKind::S_END);
  2342. }
  2343. /// Convenience routine for collecting lexical block information for a list
  2344. /// of lexical scopes.
  2345. void CodeViewDebug::collectLexicalBlockInfo(
  2346. SmallVectorImpl<LexicalScope *> &Scopes,
  2347. SmallVectorImpl<LexicalBlock *> &Blocks,
  2348. SmallVectorImpl<LocalVariable> &Locals,
  2349. SmallVectorImpl<CVGlobalVariable> &Globals) {
  2350. for (LexicalScope *Scope : Scopes)
  2351. collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
  2352. }
  2353. /// Populate the lexical blocks and local variable lists of the parent with
  2354. /// information about the specified lexical scope.
  2355. void CodeViewDebug::collectLexicalBlockInfo(
  2356. LexicalScope &Scope,
  2357. SmallVectorImpl<LexicalBlock *> &ParentBlocks,
  2358. SmallVectorImpl<LocalVariable> &ParentLocals,
  2359. SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
  2360. if (Scope.isAbstractScope())
  2361. return;
  2362. // Gather information about the lexical scope including local variables,
  2363. // global variables, and address ranges.
  2364. bool IgnoreScope = false;
  2365. auto LI = ScopeVariables.find(&Scope);
  2366. SmallVectorImpl<LocalVariable> *Locals =
  2367. LI != ScopeVariables.end() ? &LI->second : nullptr;
  2368. auto GI = ScopeGlobals.find(Scope.getScopeNode());
  2369. SmallVectorImpl<CVGlobalVariable> *Globals =
  2370. GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
  2371. const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
  2372. const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
  2373. // Ignore lexical scopes which do not contain variables.
  2374. if (!Locals && !Globals)
  2375. IgnoreScope = true;
  2376. // Ignore lexical scopes which are not lexical blocks.
  2377. if (!DILB)
  2378. IgnoreScope = true;
  2379. // Ignore scopes which have too many address ranges to represent in the
  2380. // current CodeView format or do not have a valid address range.
  2381. //
  2382. // For lexical scopes with multiple address ranges you may be tempted to
  2383. // construct a single range covering every instruction where the block is
  2384. // live and everything in between. Unfortunately, Visual Studio only
  2385. // displays variables from the first matching lexical block scope. If the
  2386. // first lexical block contains exception handling code or cold code which
  2387. // is moved to the bottom of the routine creating a single range covering
  2388. // nearly the entire routine, then it will hide all other lexical blocks
  2389. // and the variables they contain.
  2390. if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
  2391. IgnoreScope = true;
  2392. if (IgnoreScope) {
  2393. // This scope can be safely ignored and eliminating it will reduce the
  2394. // size of the debug information. Be sure to collect any variable and scope
  2395. // information from the this scope or any of its children and collapse them
  2396. // into the parent scope.
  2397. if (Locals)
  2398. ParentLocals.append(Locals->begin(), Locals->end());
  2399. if (Globals)
  2400. ParentGlobals.append(Globals->begin(), Globals->end());
  2401. collectLexicalBlockInfo(Scope.getChildren(),
  2402. ParentBlocks,
  2403. ParentLocals,
  2404. ParentGlobals);
  2405. return;
  2406. }
  2407. // Create a new CodeView lexical block for this lexical scope. If we've
  2408. // seen this DILexicalBlock before then the scope tree is malformed and
  2409. // we can handle this gracefully by not processing it a second time.
  2410. auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
  2411. if (!BlockInsertion.second)
  2412. return;
  2413. // Create a lexical block containing the variables and collect the the
  2414. // lexical block information for the children.
  2415. const InsnRange &Range = Ranges.front();
  2416. assert(Range.first && Range.second);
  2417. LexicalBlock &Block = BlockInsertion.first->second;
  2418. Block.Begin = getLabelBeforeInsn(Range.first);
  2419. Block.End = getLabelAfterInsn(Range.second);
  2420. assert(Block.Begin && "missing label for scope begin");
  2421. assert(Block.End && "missing label for scope end");
  2422. Block.Name = DILB->getName();
  2423. if (Locals)
  2424. Block.Locals = std::move(*Locals);
  2425. if (Globals)
  2426. Block.Globals = std::move(*Globals);
  2427. ParentBlocks.push_back(&Block);
  2428. collectLexicalBlockInfo(Scope.getChildren(),
  2429. Block.Children,
  2430. Block.Locals,
  2431. Block.Globals);
  2432. }
  2433. void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
  2434. const Function &GV = MF->getFunction();
  2435. assert(FnDebugInfo.count(&GV));
  2436. assert(CurFn == FnDebugInfo[&GV].get());
  2437. collectVariableInfo(GV.getSubprogram());
  2438. // Build the lexical block structure to emit for this routine.
  2439. if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
  2440. collectLexicalBlockInfo(*CFS,
  2441. CurFn->ChildBlocks,
  2442. CurFn->Locals,
  2443. CurFn->Globals);
  2444. // Clear the scope and variable information from the map which will not be
  2445. // valid after we have finished processing this routine. This also prepares
  2446. // the map for the subsequent routine.
  2447. ScopeVariables.clear();
  2448. // Don't emit anything if we don't have any line tables.
  2449. // Thunks are compiler-generated and probably won't have source correlation.
  2450. if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
  2451. FnDebugInfo.erase(&GV);
  2452. CurFn = nullptr;
  2453. return;
  2454. }
  2455. CurFn->Annotations = MF->getCodeViewAnnotations();
  2456. CurFn->End = Asm->getFunctionEnd();
  2457. CurFn = nullptr;
  2458. }
  2459. void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
  2460. DebugHandlerBase::beginInstruction(MI);
  2461. // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
  2462. if (!Asm || !CurFn || MI->isDebugInstr() ||
  2463. MI->getFlag(MachineInstr::FrameSetup))
  2464. return;
  2465. // If the first instruction of a new MBB has no location, find the first
  2466. // instruction with a location and use that.
  2467. DebugLoc DL = MI->getDebugLoc();
  2468. if (!DL && MI->getParent() != PrevInstBB) {
  2469. for (const auto &NextMI : *MI->getParent()) {
  2470. if (NextMI.isDebugInstr())
  2471. continue;
  2472. DL = NextMI.getDebugLoc();
  2473. if (DL)
  2474. break;
  2475. }
  2476. }
  2477. PrevInstBB = MI->getParent();
  2478. // If we still don't have a debug location, don't record a location.
  2479. if (!DL)
  2480. return;
  2481. maybeRecordLocation(DL, Asm->MF);
  2482. }
  2483. MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
  2484. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  2485. *EndLabel = MMI->getContext().createTempSymbol();
  2486. OS.EmitIntValue(unsigned(Kind), 4);
  2487. OS.AddComment("Subsection size");
  2488. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
  2489. OS.EmitLabel(BeginLabel);
  2490. return EndLabel;
  2491. }
  2492. void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
  2493. OS.EmitLabel(EndLabel);
  2494. // Every subsection must be aligned to a 4-byte boundary.
  2495. OS.EmitValueToAlignment(4);
  2496. }
  2497. static StringRef getSymbolName(SymbolKind SymKind) {
  2498. for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
  2499. if (EE.Value == SymKind)
  2500. return EE.Name;
  2501. return "";
  2502. }
  2503. MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
  2504. MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
  2505. *EndLabel = MMI->getContext().createTempSymbol();
  2506. OS.AddComment("Record length");
  2507. OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
  2508. OS.EmitLabel(BeginLabel);
  2509. if (OS.isVerboseAsm())
  2510. OS.AddComment("Record kind: " + getSymbolName(SymKind));
  2511. OS.EmitIntValue(unsigned(SymKind), 2);
  2512. return EndLabel;
  2513. }
  2514. void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
  2515. // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
  2516. // an extra copy of every symbol record in LLD. This increases object file
  2517. // size by less than 1% in the clang build, and is compatible with the Visual
  2518. // C++ linker.
  2519. OS.EmitValueToAlignment(4);
  2520. OS.EmitLabel(SymEnd);
  2521. }
  2522. void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
  2523. OS.AddComment("Record length");
  2524. OS.EmitIntValue(2, 2);
  2525. if (OS.isVerboseAsm())
  2526. OS.AddComment("Record kind: " + getSymbolName(EndKind));
  2527. OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
  2528. }
  2529. void CodeViewDebug::emitDebugInfoForUDTs(
  2530. ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
  2531. for (const auto &UDT : UDTs) {
  2532. const DIType *T = UDT.second;
  2533. assert(shouldEmitUdt(T));
  2534. MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
  2535. OS.AddComment("Type");
  2536. OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
  2537. emitNullTerminatedSymbolName(OS, UDT.first);
  2538. endSymbolRecord(UDTRecordEnd);
  2539. }
  2540. }
  2541. void CodeViewDebug::collectGlobalVariableInfo() {
  2542. DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
  2543. GlobalMap;
  2544. for (const GlobalVariable &GV : MMI->getModule()->globals()) {
  2545. SmallVector<DIGlobalVariableExpression *, 1> GVEs;
  2546. GV.getDebugInfo(GVEs);
  2547. for (const auto *GVE : GVEs)
  2548. GlobalMap[GVE] = &GV;
  2549. }
  2550. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  2551. for (const MDNode *Node : CUs->operands()) {
  2552. const auto *CU = cast<DICompileUnit>(Node);
  2553. for (const auto *GVE : CU->getGlobalVariables()) {
  2554. const auto *GV = GlobalMap.lookup(GVE);
  2555. if (!GV || GV->isDeclarationForLinker())
  2556. continue;
  2557. const DIGlobalVariable *DIGV = GVE->getVariable();
  2558. DIScope *Scope = DIGV->getScope();
  2559. SmallVector<CVGlobalVariable, 1> *VariableList;
  2560. if (Scope && isa<DILocalScope>(Scope)) {
  2561. // Locate a global variable list for this scope, creating one if
  2562. // necessary.
  2563. auto Insertion = ScopeGlobals.insert(
  2564. {Scope, std::unique_ptr<GlobalVariableList>()});
  2565. if (Insertion.second)
  2566. Insertion.first->second = llvm::make_unique<GlobalVariableList>();
  2567. VariableList = Insertion.first->second.get();
  2568. } else if (GV->hasComdat())
  2569. // Emit this global variable into a COMDAT section.
  2570. VariableList = &ComdatVariables;
  2571. else
  2572. // Emit this globla variable in a single global symbol section.
  2573. VariableList = &GlobalVariables;
  2574. CVGlobalVariable CVGV = {DIGV, GV};
  2575. VariableList->emplace_back(std::move(CVGV));
  2576. }
  2577. }
  2578. }
  2579. void CodeViewDebug::emitDebugInfoForGlobals() {
  2580. // First, emit all globals that are not in a comdat in a single symbol
  2581. // substream. MSVC doesn't like it if the substream is empty, so only open
  2582. // it if we have at least one global to emit.
  2583. switchToDebugSectionForSymbol(nullptr);
  2584. if (!GlobalVariables.empty()) {
  2585. OS.AddComment("Symbol subsection for globals");
  2586. MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
  2587. emitGlobalVariableList(GlobalVariables);
  2588. endCVSubsection(EndLabel);
  2589. }
  2590. // Second, emit each global that is in a comdat into its own .debug$S
  2591. // section along with its own symbol substream.
  2592. for (const CVGlobalVariable &CVGV : ComdatVariables) {
  2593. MCSymbol *GVSym = Asm->getSymbol(CVGV.GV);
  2594. OS.AddComment("Symbol subsection for " +
  2595. Twine(GlobalValue::dropLLVMManglingEscape(CVGV.GV->getName())));
  2596. switchToDebugSectionForSymbol(GVSym);
  2597. MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
  2598. // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
  2599. emitDebugInfoForGlobal(CVGV.DIGV, CVGV.GV, GVSym);
  2600. endCVSubsection(EndLabel);
  2601. }
  2602. }
  2603. void CodeViewDebug::emitDebugInfoForRetainedTypes() {
  2604. NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
  2605. for (const MDNode *Node : CUs->operands()) {
  2606. for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
  2607. if (DIType *RT = dyn_cast<DIType>(Ty)) {
  2608. getTypeIndex(RT);
  2609. // FIXME: Add to global/local DTU list.
  2610. }
  2611. }
  2612. }
  2613. }
  2614. // Emit each global variable in the specified array.
  2615. void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
  2616. for (const CVGlobalVariable &CVGV : Globals) {
  2617. MCSymbol *GVSym = Asm->getSymbol(CVGV.GV);
  2618. // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
  2619. emitDebugInfoForGlobal(CVGV.DIGV, CVGV.GV, GVSym);
  2620. }
  2621. }
  2622. void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
  2623. const GlobalVariable *GV,
  2624. MCSymbol *GVSym) {
  2625. // DataSym record, see SymbolRecord.h for more info. Thread local data
  2626. // happens to have the same format as global data.
  2627. SymbolKind DataSym = GV->isThreadLocal()
  2628. ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
  2629. : SymbolKind::S_GTHREAD32)
  2630. : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
  2631. : SymbolKind::S_GDATA32);
  2632. MCSymbol *DataEnd = beginSymbolRecord(DataSym);
  2633. OS.AddComment("Type");
  2634. OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
  2635. OS.AddComment("DataOffset");
  2636. OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
  2637. OS.AddComment("Segment");
  2638. OS.EmitCOFFSectionIndex(GVSym);
  2639. OS.AddComment("Name");
  2640. const unsigned LengthOfDataRecord = 12;
  2641. emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
  2642. endSymbolRecord(DataEnd);
  2643. }