CGDebugInfo.cpp 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566
  1. //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This coordinates the debug information generation while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CGBlocks.h"
  15. #include "CGCXXABI.h"
  16. #include "CGObjCRuntime.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/DeclFriend.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/RecordLayout.h"
  25. #include "clang/Basic/FileManager.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/Version.h"
  28. #include "clang/Frontend/CodeGenOptions.h"
  29. #include "clang/Lex/HeaderSearchOptions.h"
  30. #include "clang/Lex/ModuleMap.h"
  31. #include "clang/Lex/PreprocessorOptions.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/StringExtras.h"
  34. #include "llvm/IR/Constants.h"
  35. #include "llvm/IR/DataLayout.h"
  36. #include "llvm/IR/DerivedTypes.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/Intrinsics.h"
  39. #include "llvm/IR/Module.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/Path.h"
  42. using namespace clang;
  43. using namespace clang::CodeGen;
  44. CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
  45. : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
  46. DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
  47. DBuilder(CGM.getModule()) {
  48. for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
  49. DebugPrefixMap[KV.first] = KV.second;
  50. CreateCompileUnit();
  51. }
  52. CGDebugInfo::~CGDebugInfo() {
  53. assert(LexicalBlockStack.empty() &&
  54. "Region stack mismatch, stack not empty!");
  55. }
  56. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  57. SourceLocation TemporaryLocation)
  58. : CGF(&CGF) {
  59. init(TemporaryLocation);
  60. }
  61. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
  62. bool DefaultToEmpty,
  63. SourceLocation TemporaryLocation)
  64. : CGF(&CGF) {
  65. init(TemporaryLocation, DefaultToEmpty);
  66. }
  67. void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
  68. bool DefaultToEmpty) {
  69. auto *DI = CGF->getDebugInfo();
  70. if (!DI) {
  71. CGF = nullptr;
  72. return;
  73. }
  74. OriginalLocation = CGF->Builder.getCurrentDebugLocation();
  75. if (TemporaryLocation.isValid()) {
  76. DI->EmitLocation(CGF->Builder, TemporaryLocation);
  77. return;
  78. }
  79. if (DefaultToEmpty) {
  80. CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
  81. return;
  82. }
  83. // Construct a location that has a valid scope, but no line info.
  84. assert(!DI->LexicalBlockStack.empty());
  85. CGF->Builder.SetCurrentDebugLocation(
  86. llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
  87. }
  88. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
  89. : CGF(&CGF) {
  90. init(E->getExprLoc());
  91. }
  92. ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
  93. : CGF(&CGF) {
  94. if (!CGF.getDebugInfo()) {
  95. this->CGF = nullptr;
  96. return;
  97. }
  98. OriginalLocation = CGF.Builder.getCurrentDebugLocation();
  99. if (Loc)
  100. CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
  101. }
  102. ApplyDebugLocation::~ApplyDebugLocation() {
  103. // Query CGF so the location isn't overwritten when location updates are
  104. // temporarily disabled (for C++ default function arguments)
  105. if (CGF)
  106. CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
  107. }
  108. void CGDebugInfo::setLocation(SourceLocation Loc) {
  109. // If the new location isn't valid return.
  110. if (Loc.isInvalid())
  111. return;
  112. CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
  113. // If we've changed files in the middle of a lexical scope go ahead
  114. // and create a new lexical scope with file node if it's different
  115. // from the one in the scope.
  116. if (LexicalBlockStack.empty())
  117. return;
  118. SourceManager &SM = CGM.getContext().getSourceManager();
  119. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  120. PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
  121. if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
  122. return;
  123. if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
  124. LexicalBlockStack.pop_back();
  125. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
  126. LBF->getScope(), getOrCreateFile(CurLoc)));
  127. } else if (isa<llvm::DILexicalBlock>(Scope) ||
  128. isa<llvm::DISubprogram>(Scope)) {
  129. LexicalBlockStack.pop_back();
  130. LexicalBlockStack.emplace_back(
  131. DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
  132. }
  133. }
  134. llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
  135. llvm::DIScope *Mod = getParentModuleOrNull(D);
  136. return getContextDescriptor(cast<Decl>(D->getDeclContext()),
  137. Mod ? Mod : TheCU);
  138. }
  139. llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
  140. llvm::DIScope *Default) {
  141. if (!Context)
  142. return Default;
  143. auto I = RegionMap.find(Context);
  144. if (I != RegionMap.end()) {
  145. llvm::Metadata *V = I->second;
  146. return dyn_cast_or_null<llvm::DIScope>(V);
  147. }
  148. // Check namespace.
  149. if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
  150. return getOrCreateNameSpace(NSDecl);
  151. if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
  152. if (!RDecl->isDependentType())
  153. return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
  154. getOrCreateMainFile());
  155. return Default;
  156. }
  157. StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
  158. assert(FD && "Invalid FunctionDecl!");
  159. IdentifierInfo *FII = FD->getIdentifier();
  160. FunctionTemplateSpecializationInfo *Info =
  161. FD->getTemplateSpecializationInfo();
  162. if (!Info && FII && !CGM.getCodeGenOpts().EmitCodeView)
  163. return FII->getName();
  164. // Otherwise construct human readable name for debug info.
  165. SmallString<128> NS;
  166. llvm::raw_svector_ostream OS(NS);
  167. PrintingPolicy Policy(CGM.getLangOpts());
  168. if (CGM.getCodeGenOpts().EmitCodeView) {
  169. // Print a fully qualified name like MSVC would.
  170. Policy.MSVCFormatting = true;
  171. FD->printQualifiedName(OS, Policy);
  172. } else {
  173. // Print the unqualified name with some template arguments. This is what
  174. // DWARF-based debuggers expect.
  175. FD->printName(OS);
  176. // Add any template specialization args.
  177. if (Info) {
  178. const TemplateArgumentList *TArgs = Info->TemplateArguments;
  179. const TemplateArgument *Args = TArgs->data();
  180. unsigned NumArgs = TArgs->size();
  181. TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
  182. Policy);
  183. }
  184. }
  185. // Copy this name on the side and use its reference.
  186. return internString(OS.str());
  187. }
  188. StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
  189. SmallString<256> MethodName;
  190. llvm::raw_svector_ostream OS(MethodName);
  191. OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
  192. const DeclContext *DC = OMD->getDeclContext();
  193. if (const ObjCImplementationDecl *OID =
  194. dyn_cast<const ObjCImplementationDecl>(DC)) {
  195. OS << OID->getName();
  196. } else if (const ObjCInterfaceDecl *OID =
  197. dyn_cast<const ObjCInterfaceDecl>(DC)) {
  198. OS << OID->getName();
  199. } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
  200. if (OC->IsClassExtension()) {
  201. OS << OC->getClassInterface()->getName();
  202. } else {
  203. OS << ((const NamedDecl *)OC)->getIdentifier()->getNameStart() << '('
  204. << OC->getIdentifier()->getNameStart() << ')';
  205. }
  206. } else if (const ObjCCategoryImplDecl *OCD =
  207. dyn_cast<const ObjCCategoryImplDecl>(DC)) {
  208. OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
  209. << OCD->getIdentifier()->getNameStart() << ')';
  210. } else if (isa<ObjCProtocolDecl>(DC)) {
  211. // We can extract the type of the class from the self pointer.
  212. if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
  213. QualType ClassTy =
  214. cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
  215. ClassTy.print(OS, PrintingPolicy(LangOptions()));
  216. }
  217. }
  218. OS << ' ' << OMD->getSelector().getAsString() << ']';
  219. return internString(OS.str());
  220. }
  221. StringRef CGDebugInfo::getSelectorName(Selector S) {
  222. return internString(S.getAsString());
  223. }
  224. StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
  225. // quick optimization to avoid having to intern strings that are already
  226. // stored reliably elsewhere
  227. if (!isa<ClassTemplateSpecializationDecl>(RD))
  228. return RD->getName();
  229. SmallString<128> Name;
  230. {
  231. llvm::raw_svector_ostream OS(Name);
  232. RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
  233. /*Qualified*/ false);
  234. }
  235. // Copy this name on the side and use its reference.
  236. return internString(Name);
  237. }
  238. llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
  239. if (!Loc.isValid())
  240. // If Location is not valid then use main input file.
  241. return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
  242. remapDIPath(TheCU->getDirectory()));
  243. SourceManager &SM = CGM.getContext().getSourceManager();
  244. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  245. if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
  246. // If the location is not valid then use main input file.
  247. return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
  248. remapDIPath(TheCU->getDirectory()));
  249. // Cache the results.
  250. const char *fname = PLoc.getFilename();
  251. auto it = DIFileCache.find(fname);
  252. if (it != DIFileCache.end()) {
  253. // Verify that the information still exists.
  254. if (llvm::Metadata *V = it->second)
  255. return cast<llvm::DIFile>(V);
  256. }
  257. llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
  258. remapDIPath(getCurrentDirname()));
  259. DIFileCache[fname].reset(F);
  260. return F;
  261. }
  262. llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
  263. return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
  264. remapDIPath(TheCU->getDirectory()));
  265. }
  266. std::string CGDebugInfo::remapDIPath(StringRef Path) const {
  267. for (const auto &Entry : DebugPrefixMap)
  268. if (Path.startswith(Entry.first))
  269. return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
  270. return Path.str();
  271. }
  272. unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
  273. if (Loc.isInvalid() && CurLoc.isInvalid())
  274. return 0;
  275. SourceManager &SM = CGM.getContext().getSourceManager();
  276. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  277. return PLoc.isValid() ? PLoc.getLine() : 0;
  278. }
  279. unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
  280. // We may not want column information at all.
  281. if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
  282. return 0;
  283. // If the location is invalid then use the current column.
  284. if (Loc.isInvalid() && CurLoc.isInvalid())
  285. return 0;
  286. SourceManager &SM = CGM.getContext().getSourceManager();
  287. PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
  288. return PLoc.isValid() ? PLoc.getColumn() : 0;
  289. }
  290. StringRef CGDebugInfo::getCurrentDirname() {
  291. if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
  292. return CGM.getCodeGenOpts().DebugCompilationDir;
  293. if (!CWDName.empty())
  294. return CWDName;
  295. SmallString<256> CWD;
  296. llvm::sys::fs::current_path(CWD);
  297. return CWDName = internString(CWD);
  298. }
  299. void CGDebugInfo::CreateCompileUnit() {
  300. // Should we be asking the SourceManager for the main file name, instead of
  301. // accepting it as an argument? This just causes the main file name to
  302. // mismatch with source locations and create extra lexical scopes or
  303. // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
  304. // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
  305. // because that's what the SourceManager says)
  306. // Get absolute path name.
  307. SourceManager &SM = CGM.getContext().getSourceManager();
  308. std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
  309. if (MainFileName.empty())
  310. MainFileName = "<stdin>";
  311. // The main file name provided via the "-main-file-name" option contains just
  312. // the file name itself with no path information. This file name may have had
  313. // a relative path, so we look into the actual file entry for the main
  314. // file to determine the real absolute path for the file.
  315. std::string MainFileDir;
  316. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  317. MainFileDir = remapDIPath(MainFile->getDir()->getName());
  318. if (MainFileDir != ".") {
  319. llvm::SmallString<1024> MainFileDirSS(MainFileDir);
  320. llvm::sys::path::append(MainFileDirSS, MainFileName);
  321. MainFileName = MainFileDirSS.str();
  322. }
  323. }
  324. llvm::dwarf::SourceLanguage LangTag;
  325. const LangOptions &LO = CGM.getLangOpts();
  326. if (LO.CPlusPlus) {
  327. if (LO.ObjC1)
  328. LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
  329. else
  330. LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
  331. } else if (LO.ObjC1) {
  332. LangTag = llvm::dwarf::DW_LANG_ObjC;
  333. } else if (LO.C99) {
  334. LangTag = llvm::dwarf::DW_LANG_C99;
  335. } else {
  336. LangTag = llvm::dwarf::DW_LANG_C89;
  337. }
  338. std::string Producer = getClangFullVersion();
  339. // Figure out which version of the ObjC runtime we have.
  340. unsigned RuntimeVers = 0;
  341. if (LO.ObjC1)
  342. RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
  343. // Create new compile unit.
  344. // FIXME - Eliminate TheCU.
  345. TheCU = DBuilder.createCompileUnit(
  346. LangTag, remapDIPath(MainFileName), remapDIPath(getCurrentDirname()),
  347. Producer, LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers,
  348. CGM.getCodeGenOpts().SplitDwarfFile,
  349. DebugKind <= CodeGenOptions::DebugLineTablesOnly
  350. ? llvm::DIBuilder::LineTablesOnly
  351. : llvm::DIBuilder::FullDebug,
  352. 0 /* DWOid */, DebugKind != CodeGenOptions::LocTrackingOnly);
  353. }
  354. llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
  355. llvm::dwarf::TypeKind Encoding;
  356. StringRef BTName;
  357. switch (BT->getKind()) {
  358. #define BUILTIN_TYPE(Id, SingletonId)
  359. #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
  360. #include "clang/AST/BuiltinTypes.def"
  361. case BuiltinType::Dependent:
  362. llvm_unreachable("Unexpected builtin type");
  363. case BuiltinType::NullPtr:
  364. return DBuilder.createNullPtrType();
  365. case BuiltinType::Void:
  366. return nullptr;
  367. case BuiltinType::ObjCClass:
  368. if (!ClassTy)
  369. ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  370. "objc_class", TheCU,
  371. getOrCreateMainFile(), 0);
  372. return ClassTy;
  373. case BuiltinType::ObjCId: {
  374. // typedef struct objc_class *Class;
  375. // typedef struct objc_object {
  376. // Class isa;
  377. // } *id;
  378. if (ObjTy)
  379. return ObjTy;
  380. if (!ClassTy)
  381. ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  382. "objc_class", TheCU,
  383. getOrCreateMainFile(), 0);
  384. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  385. auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
  386. ObjTy =
  387. DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
  388. 0, 0, 0, 0, nullptr, llvm::DINodeArray());
  389. DBuilder.replaceArrays(
  390. ObjTy,
  391. DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
  392. ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
  393. return ObjTy;
  394. }
  395. case BuiltinType::ObjCSel: {
  396. if (!SelTy)
  397. SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  398. "objc_selector", TheCU,
  399. getOrCreateMainFile(), 0);
  400. return SelTy;
  401. }
  402. case BuiltinType::OCLImage1d:
  403. return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
  404. case BuiltinType::OCLImage1dArray:
  405. return getOrCreateStructPtrType("opencl_image1d_array_t",
  406. OCLImage1dArrayDITy);
  407. case BuiltinType::OCLImage1dBuffer:
  408. return getOrCreateStructPtrType("opencl_image1d_buffer_t",
  409. OCLImage1dBufferDITy);
  410. case BuiltinType::OCLImage2d:
  411. return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
  412. case BuiltinType::OCLImage2dArray:
  413. return getOrCreateStructPtrType("opencl_image2d_array_t",
  414. OCLImage2dArrayDITy);
  415. case BuiltinType::OCLImage2dDepth:
  416. return getOrCreateStructPtrType("opencl_image2d_depth_t",
  417. OCLImage2dDepthDITy);
  418. case BuiltinType::OCLImage2dArrayDepth:
  419. return getOrCreateStructPtrType("opencl_image2d_array_depth_t",
  420. OCLImage2dArrayDepthDITy);
  421. case BuiltinType::OCLImage2dMSAA:
  422. return getOrCreateStructPtrType("opencl_image2d_msaa_t",
  423. OCLImage2dMSAADITy);
  424. case BuiltinType::OCLImage2dArrayMSAA:
  425. return getOrCreateStructPtrType("opencl_image2d_array_msaa_t",
  426. OCLImage2dArrayMSAADITy);
  427. case BuiltinType::OCLImage2dMSAADepth:
  428. return getOrCreateStructPtrType("opencl_image2d_msaa_depth_t",
  429. OCLImage2dMSAADepthDITy);
  430. case BuiltinType::OCLImage2dArrayMSAADepth:
  431. return getOrCreateStructPtrType("opencl_image2d_array_msaa_depth_t",
  432. OCLImage2dArrayMSAADepthDITy);
  433. case BuiltinType::OCLImage3d:
  434. return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
  435. case BuiltinType::OCLSampler:
  436. return DBuilder.createBasicType(
  437. "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
  438. CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
  439. case BuiltinType::OCLEvent:
  440. return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
  441. case BuiltinType::OCLClkEvent:
  442. return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
  443. case BuiltinType::OCLQueue:
  444. return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
  445. case BuiltinType::OCLNDRange:
  446. return getOrCreateStructPtrType("opencl_ndrange_t", OCLNDRangeDITy);
  447. case BuiltinType::OCLReserveID:
  448. return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
  449. case BuiltinType::UChar:
  450. case BuiltinType::Char_U:
  451. Encoding = llvm::dwarf::DW_ATE_unsigned_char;
  452. break;
  453. case BuiltinType::Char_S:
  454. case BuiltinType::SChar:
  455. Encoding = llvm::dwarf::DW_ATE_signed_char;
  456. break;
  457. case BuiltinType::Char16:
  458. case BuiltinType::Char32:
  459. Encoding = llvm::dwarf::DW_ATE_UTF;
  460. break;
  461. case BuiltinType::UShort:
  462. case BuiltinType::UInt:
  463. case BuiltinType::UInt128:
  464. case BuiltinType::ULong:
  465. case BuiltinType::WChar_U:
  466. case BuiltinType::ULongLong:
  467. Encoding = llvm::dwarf::DW_ATE_unsigned;
  468. break;
  469. case BuiltinType::Short:
  470. case BuiltinType::Int:
  471. case BuiltinType::Int128:
  472. case BuiltinType::Long:
  473. case BuiltinType::WChar_S:
  474. case BuiltinType::LongLong:
  475. Encoding = llvm::dwarf::DW_ATE_signed;
  476. break;
  477. case BuiltinType::Bool:
  478. Encoding = llvm::dwarf::DW_ATE_boolean;
  479. break;
  480. case BuiltinType::Half:
  481. case BuiltinType::Float:
  482. case BuiltinType::LongDouble:
  483. case BuiltinType::Double:
  484. Encoding = llvm::dwarf::DW_ATE_float;
  485. break;
  486. }
  487. switch (BT->getKind()) {
  488. case BuiltinType::Long:
  489. BTName = "long int";
  490. break;
  491. case BuiltinType::LongLong:
  492. BTName = "long long int";
  493. break;
  494. case BuiltinType::ULong:
  495. BTName = "long unsigned int";
  496. break;
  497. case BuiltinType::ULongLong:
  498. BTName = "long long unsigned int";
  499. break;
  500. default:
  501. BTName = BT->getName(CGM.getLangOpts());
  502. break;
  503. }
  504. // Bit size, align and offset of the type.
  505. uint64_t Size = CGM.getContext().getTypeSize(BT);
  506. uint64_t Align = CGM.getContext().getTypeAlign(BT);
  507. return DBuilder.createBasicType(BTName, Size, Align, Encoding);
  508. }
  509. llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
  510. // Bit size, align and offset of the type.
  511. llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
  512. if (Ty->isComplexIntegerType())
  513. Encoding = llvm::dwarf::DW_ATE_lo_user;
  514. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  515. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  516. return DBuilder.createBasicType("complex", Size, Align, Encoding);
  517. }
  518. llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
  519. llvm::DIFile *Unit) {
  520. QualifierCollector Qc;
  521. const Type *T = Qc.strip(Ty);
  522. // Ignore these qualifiers for now.
  523. Qc.removeObjCGCAttr();
  524. Qc.removeAddressSpace();
  525. Qc.removeObjCLifetime();
  526. // We will create one Derived type for one qualifier and recurse to handle any
  527. // additional ones.
  528. llvm::dwarf::Tag Tag;
  529. if (Qc.hasConst()) {
  530. Tag = llvm::dwarf::DW_TAG_const_type;
  531. Qc.removeConst();
  532. } else if (Qc.hasVolatile()) {
  533. Tag = llvm::dwarf::DW_TAG_volatile_type;
  534. Qc.removeVolatile();
  535. } else if (Qc.hasRestrict()) {
  536. Tag = llvm::dwarf::DW_TAG_restrict_type;
  537. Qc.removeRestrict();
  538. } else {
  539. assert(Qc.empty() && "Unknown type qualifier for debug info");
  540. return getOrCreateType(QualType(T, 0), Unit);
  541. }
  542. auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
  543. // No need to fill in the Name, Line, Size, Alignment, Offset in case of
  544. // CVR derived types.
  545. return DBuilder.createQualifiedType(Tag, FromTy);
  546. }
  547. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
  548. llvm::DIFile *Unit) {
  549. // The frontend treats 'id' as a typedef to an ObjCObjectType,
  550. // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
  551. // debug info, we want to emit 'id' in both cases.
  552. if (Ty->isObjCQualifiedIdType())
  553. return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
  554. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  555. Ty->getPointeeType(), Unit);
  556. }
  557. llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
  558. llvm::DIFile *Unit) {
  559. return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
  560. Ty->getPointeeType(), Unit);
  561. }
  562. /// \return whether a C++ mangling exists for the type defined by TD.
  563. static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
  564. switch (TheCU->getSourceLanguage()) {
  565. case llvm::dwarf::DW_LANG_C_plus_plus:
  566. return true;
  567. case llvm::dwarf::DW_LANG_ObjC_plus_plus:
  568. return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
  569. default:
  570. return false;
  571. }
  572. }
  573. /// In C++ mode, types have linkage, so we can rely on the ODR and
  574. /// on their mangled names, if they're external.
  575. static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
  576. CodeGenModule &CGM,
  577. llvm::DICompileUnit *TheCU) {
  578. SmallString<256> FullName;
  579. const TagDecl *TD = Ty->getDecl();
  580. if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
  581. return FullName;
  582. // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
  583. if (CGM.getTarget().getCXXABI().isMicrosoft())
  584. return FullName;
  585. // TODO: This is using the RTTI name. Is there a better way to get
  586. // a unique string for a type?
  587. llvm::raw_svector_ostream Out(FullName);
  588. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
  589. return FullName;
  590. }
  591. /// \return the approproate DWARF tag for a composite type.
  592. static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
  593. llvm::dwarf::Tag Tag;
  594. if (RD->isStruct() || RD->isInterface())
  595. Tag = llvm::dwarf::DW_TAG_structure_type;
  596. else if (RD->isUnion())
  597. Tag = llvm::dwarf::DW_TAG_union_type;
  598. else {
  599. // FIXME: This could be a struct type giving a default visibility different
  600. // than C++ class type, but needs llvm metadata changes first.
  601. assert(RD->isClass());
  602. Tag = llvm::dwarf::DW_TAG_class_type;
  603. }
  604. return Tag;
  605. }
  606. llvm::DICompositeType *
  607. CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
  608. llvm::DIScope *Ctx) {
  609. const RecordDecl *RD = Ty->getDecl();
  610. if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
  611. return cast<llvm::DICompositeType>(T);
  612. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  613. unsigned Line = getLineNumber(RD->getLocation());
  614. StringRef RDName = getClassName(RD);
  615. uint64_t Size = 0;
  616. uint64_t Align = 0;
  617. const RecordDecl *D = RD->getDefinition();
  618. if (D && D->isCompleteDefinition()) {
  619. Size = CGM.getContext().getTypeSize(Ty);
  620. Align = CGM.getContext().getTypeAlign(Ty);
  621. }
  622. // Create the type.
  623. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  624. llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
  625. getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
  626. llvm::DINode::FlagFwdDecl, FullName);
  627. ReplaceMap.emplace_back(
  628. std::piecewise_construct, std::make_tuple(Ty),
  629. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  630. return RetTy;
  631. }
  632. llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
  633. const Type *Ty,
  634. QualType PointeeTy,
  635. llvm::DIFile *Unit) {
  636. // Bit size, align and offset of the type.
  637. // Size is always the size of a pointer. We can't use getTypeSize here
  638. // because that does not return the correct value for references.
  639. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  640. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  641. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  642. if (Tag == llvm::dwarf::DW_TAG_reference_type ||
  643. Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
  644. return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
  645. Size, Align);
  646. else
  647. return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
  648. Align);
  649. }
  650. llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
  651. llvm::DIType *&Cache) {
  652. if (Cache)
  653. return Cache;
  654. Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
  655. TheCU, getOrCreateMainFile(), 0);
  656. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  657. Cache = DBuilder.createPointerType(Cache, Size);
  658. return Cache;
  659. }
  660. llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
  661. llvm::DIFile *Unit) {
  662. SmallVector<llvm::Metadata *, 8> EltTys;
  663. QualType FType;
  664. uint64_t FieldSize, FieldOffset;
  665. unsigned FieldAlign;
  666. llvm::DINodeArray Elements;
  667. FieldOffset = 0;
  668. FType = CGM.getContext().UnsignedLongTy;
  669. EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
  670. EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
  671. Elements = DBuilder.getOrCreateArray(EltTys);
  672. EltTys.clear();
  673. unsigned Flags = llvm::DINode::FlagAppleBlock;
  674. unsigned LineNo = 0;
  675. auto *EltTy =
  676. DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
  677. FieldOffset, 0, Flags, nullptr, Elements);
  678. // Bit size, align and offset of the type.
  679. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  680. auto *DescTy = DBuilder.createPointerType(EltTy, Size);
  681. FieldOffset = 0;
  682. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  683. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  684. FType = CGM.getContext().IntTy;
  685. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  686. EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
  687. FType = CGM.getContext().getPointerType(Ty->getPointeeType());
  688. EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
  689. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  690. FieldSize = CGM.getContext().getTypeSize(Ty);
  691. FieldAlign = CGM.getContext().getTypeAlign(Ty);
  692. EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo,
  693. FieldSize, FieldAlign, FieldOffset,
  694. 0, DescTy));
  695. FieldOffset += FieldSize;
  696. Elements = DBuilder.getOrCreateArray(EltTys);
  697. // The __block_literal_generic structs are marked with a special
  698. // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
  699. // the debugger needs to know about. To allow type uniquing, emit
  700. // them without a name or a location.
  701. EltTy =
  702. DBuilder.createStructType(Unit, "", nullptr, LineNo,
  703. FieldOffset, 0, Flags, nullptr, Elements);
  704. return DBuilder.createPointerType(EltTy, Size);
  705. }
  706. llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
  707. llvm::DIFile *Unit) {
  708. assert(Ty->isTypeAlias());
  709. llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
  710. SmallString<128> NS;
  711. llvm::raw_svector_ostream OS(NS);
  712. Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
  713. /*qualified*/ false);
  714. TemplateSpecializationType::PrintTemplateArgumentList(
  715. OS, Ty->getArgs(), Ty->getNumArgs(),
  716. CGM.getContext().getPrintingPolicy());
  717. TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
  718. Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
  719. SourceLocation Loc = AliasDecl->getLocation();
  720. return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
  721. getLineNumber(Loc),
  722. getDeclContextDescriptor(AliasDecl));
  723. }
  724. llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
  725. llvm::DIFile *Unit) {
  726. // We don't set size information, but do specify where the typedef was
  727. // declared.
  728. SourceLocation Loc = Ty->getDecl()->getLocation();
  729. // Typedefs are derived from some other type.
  730. return DBuilder.createTypedef(
  731. getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
  732. Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
  733. getDeclContextDescriptor(Ty->getDecl()));
  734. }
  735. llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
  736. llvm::DIFile *Unit) {
  737. SmallVector<llvm::Metadata *, 16> EltTys;
  738. // Add the result type at least.
  739. EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
  740. // Set up remainder of arguments if there is a prototype.
  741. // otherwise emit it as a variadic function.
  742. if (isa<FunctionNoProtoType>(Ty))
  743. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  744. else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
  745. for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
  746. EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
  747. if (FPT->isVariadic())
  748. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  749. }
  750. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  751. return DBuilder.createSubroutineType(EltTypeArray);
  752. }
  753. /// Convert an AccessSpecifier into the corresponding DINode flag.
  754. /// As an optimization, return 0 if the access specifier equals the
  755. /// default for the containing type.
  756. static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
  757. AccessSpecifier Default = clang::AS_none;
  758. if (RD && RD->isClass())
  759. Default = clang::AS_private;
  760. else if (RD && (RD->isStruct() || RD->isUnion()))
  761. Default = clang::AS_public;
  762. if (Access == Default)
  763. return 0;
  764. switch (Access) {
  765. case clang::AS_private:
  766. return llvm::DINode::FlagPrivate;
  767. case clang::AS_protected:
  768. return llvm::DINode::FlagProtected;
  769. case clang::AS_public:
  770. return llvm::DINode::FlagPublic;
  771. case clang::AS_none:
  772. return 0;
  773. }
  774. llvm_unreachable("unexpected access enumerator");
  775. }
  776. llvm::DIType *CGDebugInfo::createFieldType(
  777. StringRef name, QualType type, uint64_t sizeInBitsOverride,
  778. SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
  779. llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) {
  780. llvm::DIType *debugType = getOrCreateType(type, tunit);
  781. // Get the location for the field.
  782. llvm::DIFile *file = getOrCreateFile(loc);
  783. unsigned line = getLineNumber(loc);
  784. uint64_t SizeInBits = 0;
  785. unsigned AlignInBits = 0;
  786. if (!type->isIncompleteArrayType()) {
  787. TypeInfo TI = CGM.getContext().getTypeInfo(type);
  788. SizeInBits = TI.Width;
  789. AlignInBits = TI.Align;
  790. if (sizeInBitsOverride)
  791. SizeInBits = sizeInBitsOverride;
  792. }
  793. unsigned flags = getAccessFlag(AS, RD);
  794. return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
  795. AlignInBits, offsetInBits, flags, debugType);
  796. }
  797. void CGDebugInfo::CollectRecordLambdaFields(
  798. const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
  799. llvm::DIType *RecordTy) {
  800. // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
  801. // has the name and the location of the variable so we should iterate over
  802. // both concurrently.
  803. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
  804. RecordDecl::field_iterator Field = CXXDecl->field_begin();
  805. unsigned fieldno = 0;
  806. for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
  807. E = CXXDecl->captures_end();
  808. I != E; ++I, ++Field, ++fieldno) {
  809. const LambdaCapture &C = *I;
  810. if (C.capturesVariable()) {
  811. VarDecl *V = C.getCapturedVar();
  812. llvm::DIFile *VUnit = getOrCreateFile(C.getLocation());
  813. StringRef VName = V->getName();
  814. uint64_t SizeInBitsOverride = 0;
  815. if (Field->isBitField()) {
  816. SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
  817. assert(SizeInBitsOverride && "found named 0-width bitfield");
  818. }
  819. llvm::DIType *fieldType = createFieldType(
  820. VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
  821. Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
  822. CXXDecl);
  823. elements.push_back(fieldType);
  824. } else if (C.capturesThis()) {
  825. // TODO: Need to handle 'this' in some way by probably renaming the
  826. // this of the lambda class and having a field member of 'this' or
  827. // by using AT_object_pointer for the function and having that be
  828. // used as 'this' for semantic references.
  829. FieldDecl *f = *Field;
  830. llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
  831. QualType type = f->getType();
  832. llvm::DIType *fieldType = createFieldType(
  833. "this", type, 0, f->getLocation(), f->getAccess(),
  834. layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
  835. elements.push_back(fieldType);
  836. }
  837. }
  838. }
  839. llvm::DIDerivedType *
  840. CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
  841. const RecordDecl *RD) {
  842. // Create the descriptor for the static variable, with or without
  843. // constant initializers.
  844. Var = Var->getCanonicalDecl();
  845. llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
  846. llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
  847. unsigned LineNumber = getLineNumber(Var->getLocation());
  848. StringRef VName = Var->getName();
  849. llvm::Constant *C = nullptr;
  850. if (Var->getInit()) {
  851. const APValue *Value = Var->evaluateValue();
  852. if (Value) {
  853. if (Value->isInt())
  854. C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
  855. if (Value->isFloat())
  856. C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
  857. }
  858. }
  859. unsigned Flags = getAccessFlag(Var->getAccess(), RD);
  860. llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
  861. RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
  862. StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
  863. return GV;
  864. }
  865. void CGDebugInfo::CollectRecordNormalField(
  866. const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
  867. SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
  868. const RecordDecl *RD) {
  869. StringRef name = field->getName();
  870. QualType type = field->getType();
  871. // Ignore unnamed fields unless they're anonymous structs/unions.
  872. if (name.empty() && !type->isRecordType())
  873. return;
  874. uint64_t SizeInBitsOverride = 0;
  875. if (field->isBitField()) {
  876. SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
  877. assert(SizeInBitsOverride && "found named 0-width bitfield");
  878. }
  879. llvm::DIType *fieldType =
  880. createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
  881. field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
  882. elements.push_back(fieldType);
  883. }
  884. void CGDebugInfo::CollectRecordFields(
  885. const RecordDecl *record, llvm::DIFile *tunit,
  886. SmallVectorImpl<llvm::Metadata *> &elements,
  887. llvm::DICompositeType *RecordTy) {
  888. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
  889. if (CXXDecl && CXXDecl->isLambda())
  890. CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
  891. else {
  892. const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
  893. // Field number for non-static fields.
  894. unsigned fieldNo = 0;
  895. // Static and non-static members should appear in the same order as
  896. // the corresponding declarations in the source program.
  897. for (const auto *I : record->decls())
  898. if (const auto *V = dyn_cast<VarDecl>(I)) {
  899. // Reuse the existing static member declaration if one exists
  900. auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
  901. if (MI != StaticDataMemberCache.end()) {
  902. assert(MI->second &&
  903. "Static data member declaration should still exist");
  904. elements.push_back(MI->second);
  905. } else {
  906. auto Field = CreateRecordStaticField(V, RecordTy, record);
  907. elements.push_back(Field);
  908. }
  909. } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
  910. CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
  911. elements, RecordTy, record);
  912. // Bump field number for next field.
  913. ++fieldNo;
  914. }
  915. }
  916. }
  917. llvm::DISubroutineType *
  918. CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
  919. llvm::DIFile *Unit) {
  920. const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
  921. if (Method->isStatic())
  922. return cast_or_null<llvm::DISubroutineType>(
  923. getOrCreateType(QualType(Func, 0), Unit));
  924. return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
  925. Func, Unit);
  926. }
  927. llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
  928. QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
  929. // Add "this" pointer.
  930. llvm::DITypeRefArray Args(
  931. cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
  932. ->getTypeArray());
  933. assert(Args.size() && "Invalid number of arguments!");
  934. SmallVector<llvm::Metadata *, 16> Elts;
  935. // First element is always return type. For 'void' functions it is NULL.
  936. Elts.push_back(Args[0]);
  937. // "this" pointer is always first argument.
  938. const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
  939. if (isa<ClassTemplateSpecializationDecl>(RD)) {
  940. // Create pointer type directly in this case.
  941. const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
  942. QualType PointeeTy = ThisPtrTy->getPointeeType();
  943. unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
  944. uint64_t Size = CGM.getTarget().getPointerWidth(AS);
  945. uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
  946. llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
  947. llvm::DIType *ThisPtrType =
  948. DBuilder.createPointerType(PointeeType, Size, Align);
  949. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  950. // TODO: This and the artificial type below are misleading, the
  951. // types aren't artificial the argument is, but the current
  952. // metadata doesn't represent that.
  953. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  954. Elts.push_back(ThisPtrType);
  955. } else {
  956. llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
  957. TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
  958. ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
  959. Elts.push_back(ThisPtrType);
  960. }
  961. // Copy rest of the arguments.
  962. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  963. Elts.push_back(Args[i]);
  964. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  965. unsigned Flags = 0;
  966. if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
  967. Flags |= llvm::DINode::FlagLValueReference;
  968. if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
  969. Flags |= llvm::DINode::FlagRValueReference;
  970. return DBuilder.createSubroutineType(EltTypeArray, Flags);
  971. }
  972. /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
  973. /// inside a function.
  974. static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
  975. if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
  976. return isFunctionLocalClass(NRD);
  977. if (isa<FunctionDecl>(RD->getDeclContext()))
  978. return true;
  979. return false;
  980. }
  981. llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
  982. const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
  983. bool IsCtorOrDtor =
  984. isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
  985. StringRef MethodName = getFunctionName(Method);
  986. llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
  987. // Since a single ctor/dtor corresponds to multiple functions, it doesn't
  988. // make sense to give a single ctor/dtor a linkage name.
  989. StringRef MethodLinkageName;
  990. if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
  991. MethodLinkageName = CGM.getMangledName(Method);
  992. // Get the location for the method.
  993. llvm::DIFile *MethodDefUnit = nullptr;
  994. unsigned MethodLine = 0;
  995. if (!Method->isImplicit()) {
  996. MethodDefUnit = getOrCreateFile(Method->getLocation());
  997. MethodLine = getLineNumber(Method->getLocation());
  998. }
  999. // Collect virtual method info.
  1000. llvm::DIType *ContainingType = nullptr;
  1001. unsigned Virtuality = 0;
  1002. unsigned VIndex = 0;
  1003. if (Method->isVirtual()) {
  1004. if (Method->isPure())
  1005. Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
  1006. else
  1007. Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
  1008. // It doesn't make sense to give a virtual destructor a vtable index,
  1009. // since a single destructor has two entries in the vtable.
  1010. // FIXME: Add proper support for debug info for virtual calls in
  1011. // the Microsoft ABI, where we may use multiple vptrs to make a vftable
  1012. // lookup if we have multiple or virtual inheritance.
  1013. if (!isa<CXXDestructorDecl>(Method) &&
  1014. !CGM.getTarget().getCXXABI().isMicrosoft())
  1015. VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
  1016. ContainingType = RecordTy;
  1017. }
  1018. unsigned Flags = 0;
  1019. if (Method->isImplicit())
  1020. Flags |= llvm::DINode::FlagArtificial;
  1021. Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
  1022. if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
  1023. if (CXXC->isExplicit())
  1024. Flags |= llvm::DINode::FlagExplicit;
  1025. } else if (const CXXConversionDecl *CXXC =
  1026. dyn_cast<CXXConversionDecl>(Method)) {
  1027. if (CXXC->isExplicit())
  1028. Flags |= llvm::DINode::FlagExplicit;
  1029. }
  1030. if (Method->hasPrototype())
  1031. Flags |= llvm::DINode::FlagPrototyped;
  1032. if (Method->getRefQualifier() == RQ_LValue)
  1033. Flags |= llvm::DINode::FlagLValueReference;
  1034. if (Method->getRefQualifier() == RQ_RValue)
  1035. Flags |= llvm::DINode::FlagRValueReference;
  1036. llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
  1037. llvm::DISubprogram *SP = DBuilder.createMethod(
  1038. RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
  1039. MethodTy, /*isLocalToUnit=*/false,
  1040. /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
  1041. CGM.getLangOpts().Optimize, TParamsArray.get());
  1042. SPCache[Method->getCanonicalDecl()].reset(SP);
  1043. return SP;
  1044. }
  1045. void CGDebugInfo::CollectCXXMemberFunctions(
  1046. const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1047. SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
  1048. // Since we want more than just the individual member decls if we
  1049. // have templated functions iterate over every declaration to gather
  1050. // the functions.
  1051. for (const auto *I : RD->decls()) {
  1052. const auto *Method = dyn_cast<CXXMethodDecl>(I);
  1053. // If the member is implicit, don't add it to the member list. This avoids
  1054. // the member being added to type units by LLVM, while still allowing it
  1055. // to be emitted into the type declaration/reference inside the compile
  1056. // unit.
  1057. // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
  1058. // FIXME: Handle Using(Shadow?)Decls here to create
  1059. // DW_TAG_imported_declarations inside the class for base decls brought into
  1060. // derived classes. GDB doesn't seem to notice/leverage these when I tried
  1061. // it, so I'm not rushing to fix this. (GCC seems to produce them, if
  1062. // referenced)
  1063. if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
  1064. continue;
  1065. if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
  1066. continue;
  1067. // Reuse the existing member function declaration if it exists.
  1068. // It may be associated with the declaration of the type & should be
  1069. // reused as we're building the definition.
  1070. //
  1071. // This situation can arise in the vtable-based debug info reduction where
  1072. // implicit members are emitted in a non-vtable TU.
  1073. auto MI = SPCache.find(Method->getCanonicalDecl());
  1074. EltTys.push_back(MI == SPCache.end()
  1075. ? CreateCXXMemberFunction(Method, Unit, RecordTy)
  1076. : static_cast<llvm::Metadata *>(MI->second));
  1077. }
  1078. }
  1079. void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1080. SmallVectorImpl<llvm::Metadata *> &EltTys,
  1081. llvm::DIType *RecordTy) {
  1082. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1083. for (const auto &BI : RD->bases()) {
  1084. unsigned BFlags = 0;
  1085. uint64_t BaseOffset;
  1086. const CXXRecordDecl *Base =
  1087. cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
  1088. if (BI.isVirtual()) {
  1089. if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
  1090. // virtual base offset offset is -ve. The code generator emits dwarf
  1091. // expression where it expects +ve number.
  1092. BaseOffset = 0 - CGM.getItaniumVTableContext()
  1093. .getVirtualBaseOffsetOffset(RD, Base)
  1094. .getQuantity();
  1095. } else {
  1096. // In the MS ABI, store the vbtable offset, which is analogous to the
  1097. // vbase offset offset in Itanium.
  1098. BaseOffset =
  1099. 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
  1100. }
  1101. BFlags = llvm::DINode::FlagVirtual;
  1102. } else
  1103. BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
  1104. // FIXME: Inconsistent units for BaseOffset. It is in bytes when
  1105. // BI->isVirtual() and bits when not.
  1106. BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
  1107. llvm::DIType *DTy = DBuilder.createInheritance(
  1108. RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
  1109. EltTys.push_back(DTy);
  1110. }
  1111. }
  1112. llvm::DINodeArray
  1113. CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
  1114. ArrayRef<TemplateArgument> TAList,
  1115. llvm::DIFile *Unit) {
  1116. SmallVector<llvm::Metadata *, 16> TemplateParams;
  1117. for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
  1118. const TemplateArgument &TA = TAList[i];
  1119. StringRef Name;
  1120. if (TPList)
  1121. Name = TPList->getParam(i)->getName();
  1122. switch (TA.getKind()) {
  1123. case TemplateArgument::Type: {
  1124. llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
  1125. TemplateParams.push_back(
  1126. DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
  1127. } break;
  1128. case TemplateArgument::Integral: {
  1129. llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
  1130. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1131. TheCU, Name, TTy,
  1132. llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
  1133. } break;
  1134. case TemplateArgument::Declaration: {
  1135. const ValueDecl *D = TA.getAsDecl();
  1136. QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
  1137. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1138. llvm::Constant *V = nullptr;
  1139. const CXXMethodDecl *MD;
  1140. // Variable pointer template parameters have a value that is the address
  1141. // of the variable.
  1142. if (const auto *VD = dyn_cast<VarDecl>(D))
  1143. V = CGM.GetAddrOfGlobalVar(VD);
  1144. // Member function pointers have special support for building them, though
  1145. // this is currently unsupported in LLVM CodeGen.
  1146. else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
  1147. V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
  1148. else if (const auto *FD = dyn_cast<FunctionDecl>(D))
  1149. V = CGM.GetAddrOfFunction(FD);
  1150. // Member data pointers have special handling too to compute the fixed
  1151. // offset within the object.
  1152. else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
  1153. // These five lines (& possibly the above member function pointer
  1154. // handling) might be able to be refactored to use similar code in
  1155. // CodeGenModule::getMemberPointerConstant
  1156. uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
  1157. CharUnits chars =
  1158. CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
  1159. V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
  1160. }
  1161. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1162. TheCU, Name, TTy,
  1163. cast_or_null<llvm::Constant>(V->stripPointerCasts())));
  1164. } break;
  1165. case TemplateArgument::NullPtr: {
  1166. QualType T = TA.getNullPtrType();
  1167. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1168. llvm::Constant *V = nullptr;
  1169. // Special case member data pointer null values since they're actually -1
  1170. // instead of zero.
  1171. if (const MemberPointerType *MPT =
  1172. dyn_cast<MemberPointerType>(T.getTypePtr()))
  1173. // But treat member function pointers as simple zero integers because
  1174. // it's easier than having a special case in LLVM's CodeGen. If LLVM
  1175. // CodeGen grows handling for values of non-null member function
  1176. // pointers then perhaps we could remove this special case and rely on
  1177. // EmitNullMemberPointer for member function pointers.
  1178. if (MPT->isMemberDataPointer())
  1179. V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
  1180. if (!V)
  1181. V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
  1182. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1183. TheCU, Name, TTy, cast<llvm::Constant>(V)));
  1184. } break;
  1185. case TemplateArgument::Template:
  1186. TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
  1187. TheCU, Name, nullptr,
  1188. TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
  1189. break;
  1190. case TemplateArgument::Pack:
  1191. TemplateParams.push_back(DBuilder.createTemplateParameterPack(
  1192. TheCU, Name, nullptr,
  1193. CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
  1194. break;
  1195. case TemplateArgument::Expression: {
  1196. const Expr *E = TA.getAsExpr();
  1197. QualType T = E->getType();
  1198. if (E->isGLValue())
  1199. T = CGM.getContext().getLValueReferenceType(T);
  1200. llvm::Constant *V = CGM.EmitConstantExpr(E, T);
  1201. assert(V && "Expression in template argument isn't constant");
  1202. llvm::DIType *TTy = getOrCreateType(T, Unit);
  1203. TemplateParams.push_back(DBuilder.createTemplateValueParameter(
  1204. TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())));
  1205. } break;
  1206. // And the following should never occur:
  1207. case TemplateArgument::TemplateExpansion:
  1208. case TemplateArgument::Null:
  1209. llvm_unreachable(
  1210. "These argument types shouldn't exist in concrete types");
  1211. }
  1212. }
  1213. return DBuilder.getOrCreateArray(TemplateParams);
  1214. }
  1215. llvm::DINodeArray
  1216. CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
  1217. llvm::DIFile *Unit) {
  1218. if (FD->getTemplatedKind() ==
  1219. FunctionDecl::TK_FunctionTemplateSpecialization) {
  1220. const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
  1221. ->getTemplate()
  1222. ->getTemplateParameters();
  1223. return CollectTemplateParams(
  1224. TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
  1225. }
  1226. return llvm::DINodeArray();
  1227. }
  1228. llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
  1229. const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
  1230. // Always get the full list of parameters, not just the ones from
  1231. // the specialization.
  1232. TemplateParameterList *TPList =
  1233. TSpecial->getSpecializedTemplate()->getTemplateParameters();
  1234. const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
  1235. return CollectTemplateParams(TPList, TAList.asArray(), Unit);
  1236. }
  1237. llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
  1238. if (VTablePtrType)
  1239. return VTablePtrType;
  1240. ASTContext &Context = CGM.getContext();
  1241. /* Function type */
  1242. llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
  1243. llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
  1244. llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
  1245. unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
  1246. llvm::DIType *vtbl_ptr_type =
  1247. DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
  1248. VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
  1249. return VTablePtrType;
  1250. }
  1251. StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
  1252. // Copy the gdb compatible name on the side and use its reference.
  1253. return internString("_vptr$", RD->getNameAsString());
  1254. }
  1255. void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
  1256. SmallVectorImpl<llvm::Metadata *> &EltTys) {
  1257. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1258. // If there is a primary base then it will hold vtable info.
  1259. if (RL.getPrimaryBase())
  1260. return;
  1261. // If this class is not dynamic then there is not any vtable info to collect.
  1262. if (!RD->isDynamicClass())
  1263. return;
  1264. unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
  1265. llvm::DIType *VPTR = DBuilder.createMemberType(
  1266. Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
  1267. llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
  1268. EltTys.push_back(VPTR);
  1269. }
  1270. llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
  1271. SourceLocation Loc) {
  1272. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  1273. llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
  1274. return T;
  1275. }
  1276. llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
  1277. SourceLocation Loc) {
  1278. return getOrCreateStandaloneType(D, Loc);
  1279. }
  1280. llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
  1281. SourceLocation Loc) {
  1282. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  1283. assert(!D.isNull() && "null type");
  1284. llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
  1285. assert(T && "could not create debug info for type");
  1286. // Composite types with UIDs were already retained by DIBuilder
  1287. // because they are only referenced by name in the IR.
  1288. if (auto *CTy = dyn_cast<llvm::DICompositeType>(T))
  1289. if (!CTy->getIdentifier().empty())
  1290. return T;
  1291. RetainedTypes.push_back(D.getAsOpaquePtr());
  1292. return T;
  1293. }
  1294. void CGDebugInfo::completeType(const EnumDecl *ED) {
  1295. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1296. return;
  1297. QualType Ty = CGM.getContext().getEnumType(ED);
  1298. void *TyPtr = Ty.getAsOpaquePtr();
  1299. auto I = TypeCache.find(TyPtr);
  1300. if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
  1301. return;
  1302. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
  1303. assert(!Res->isForwardDecl());
  1304. TypeCache[TyPtr].reset(Res);
  1305. }
  1306. void CGDebugInfo::completeType(const RecordDecl *RD) {
  1307. if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
  1308. !CGM.getLangOpts().CPlusPlus)
  1309. completeRequiredType(RD);
  1310. }
  1311. void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
  1312. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1313. return;
  1314. if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1315. if (CXXDecl->isDynamicClass())
  1316. return;
  1317. if (DebugTypeExtRefs && RD->isFromASTFile())
  1318. return;
  1319. QualType Ty = CGM.getContext().getRecordType(RD);
  1320. llvm::DIType *T = getTypeOrNull(Ty);
  1321. if (T && T->isForwardDecl())
  1322. completeClassData(RD);
  1323. }
  1324. void CGDebugInfo::completeClassData(const RecordDecl *RD) {
  1325. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1326. return;
  1327. QualType Ty = CGM.getContext().getRecordType(RD);
  1328. void *TyPtr = Ty.getAsOpaquePtr();
  1329. auto I = TypeCache.find(TyPtr);
  1330. if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
  1331. return;
  1332. llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
  1333. assert(!Res->isForwardDecl());
  1334. TypeCache[TyPtr].reset(Res);
  1335. }
  1336. static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
  1337. CXXRecordDecl::method_iterator End) {
  1338. for (; I != End; ++I)
  1339. if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
  1340. if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
  1341. !I->getMemberSpecializationInfo()->isExplicitSpecialization())
  1342. return true;
  1343. return false;
  1344. }
  1345. static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
  1346. bool DebugTypeExtRefs,
  1347. const RecordDecl *RD,
  1348. const LangOptions &LangOpts) {
  1349. // Does the type exist in an imported clang module?
  1350. if (DebugTypeExtRefs && RD->isFromASTFile() && RD->getDefinition())
  1351. return true;
  1352. if (DebugKind > CodeGenOptions::LimitedDebugInfo)
  1353. return false;
  1354. if (!LangOpts.CPlusPlus)
  1355. return false;
  1356. if (!RD->isCompleteDefinitionRequired())
  1357. return true;
  1358. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1359. if (!CXXDecl)
  1360. return false;
  1361. if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
  1362. return true;
  1363. TemplateSpecializationKind Spec = TSK_Undeclared;
  1364. if (const ClassTemplateSpecializationDecl *SD =
  1365. dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1366. Spec = SD->getSpecializationKind();
  1367. if (Spec == TSK_ExplicitInstantiationDeclaration &&
  1368. hasExplicitMemberDefinition(CXXDecl->method_begin(),
  1369. CXXDecl->method_end()))
  1370. return true;
  1371. return false;
  1372. }
  1373. llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
  1374. RecordDecl *RD = Ty->getDecl();
  1375. llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
  1376. if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
  1377. CGM.getLangOpts())) {
  1378. if (!T)
  1379. T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
  1380. return T;
  1381. }
  1382. return CreateTypeDefinition(Ty);
  1383. }
  1384. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
  1385. RecordDecl *RD = Ty->getDecl();
  1386. // Get overall information about the record type for the debug info.
  1387. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  1388. // Records and classes and unions can all be recursive. To handle them, we
  1389. // first generate a debug descriptor for the struct as a forward declaration.
  1390. // Then (if it is a definition) we go through and get debug info for all of
  1391. // its members. Finally, we create a descriptor for the complete type (which
  1392. // may refer to the forward decl if the struct is recursive) and replace all
  1393. // uses of the forward declaration with the final definition.
  1394. llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
  1395. const RecordDecl *D = RD->getDefinition();
  1396. if (!D || !D->isCompleteDefinition())
  1397. return FwdDecl;
  1398. if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1399. CollectContainingType(CXXDecl, FwdDecl);
  1400. // Push the struct on region stack.
  1401. LexicalBlockStack.emplace_back(&*FwdDecl);
  1402. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1403. // Convert all the elements.
  1404. SmallVector<llvm::Metadata *, 16> EltTys;
  1405. // what about nested types?
  1406. // Note: The split of CXXDecl information here is intentional, the
  1407. // gdb tests will depend on a certain ordering at printout. The debug
  1408. // information offsets are still correct if we merge them all together
  1409. // though.
  1410. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1411. if (CXXDecl) {
  1412. CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
  1413. CollectVTableInfo(CXXDecl, DefUnit, EltTys);
  1414. }
  1415. // Collect data fields (including static variables and any initializers).
  1416. CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
  1417. if (CXXDecl)
  1418. CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
  1419. LexicalBlockStack.pop_back();
  1420. RegionMap.erase(Ty->getDecl());
  1421. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1422. DBuilder.replaceArrays(FwdDecl, Elements);
  1423. if (FwdDecl->isTemporary())
  1424. FwdDecl =
  1425. llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
  1426. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1427. return FwdDecl;
  1428. }
  1429. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
  1430. llvm::DIFile *Unit) {
  1431. // Ignore protocols.
  1432. return getOrCreateType(Ty->getBaseType(), Unit);
  1433. }
  1434. /// \return true if Getter has the default name for the property PD.
  1435. static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
  1436. const ObjCMethodDecl *Getter) {
  1437. assert(PD);
  1438. if (!Getter)
  1439. return true;
  1440. assert(Getter->getDeclName().isObjCZeroArgSelector());
  1441. return PD->getName() ==
  1442. Getter->getDeclName().getObjCSelector().getNameForSlot(0);
  1443. }
  1444. /// \return true if Setter has the default name for the property PD.
  1445. static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
  1446. const ObjCMethodDecl *Setter) {
  1447. assert(PD);
  1448. if (!Setter)
  1449. return true;
  1450. assert(Setter->getDeclName().isObjCOneArgSelector());
  1451. return SelectorTable::constructSetterName(PD->getName()) ==
  1452. Setter->getDeclName().getObjCSelector().getNameForSlot(0);
  1453. }
  1454. llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
  1455. llvm::DIFile *Unit) {
  1456. ObjCInterfaceDecl *ID = Ty->getDecl();
  1457. if (!ID)
  1458. return nullptr;
  1459. // Return a forward declaration if this type was imported from a clang module.
  1460. if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition())
  1461. return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  1462. ID->getName(),
  1463. getDeclContextDescriptor(ID), Unit, 0);
  1464. // Get overall information about the record type for the debug info.
  1465. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1466. unsigned Line = getLineNumber(ID->getLocation());
  1467. auto RuntimeLang =
  1468. static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
  1469. // If this is just a forward declaration return a special forward-declaration
  1470. // debug type since we won't be able to lay out the entire type.
  1471. ObjCInterfaceDecl *Def = ID->getDefinition();
  1472. if (!Def || !Def->getImplementation()) {
  1473. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  1474. llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
  1475. llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
  1476. DefUnit, Line, RuntimeLang);
  1477. ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
  1478. return FwdDecl;
  1479. }
  1480. return CreateTypeDefinition(Ty, Unit);
  1481. }
  1482. llvm::DIModule *
  1483. CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
  1484. bool CreateSkeletonCU) {
  1485. // Use the Module pointer as the key into the cache. This is a
  1486. // nullptr if the "Module" is a PCH, which is safe because we don't
  1487. // support chained PCH debug info, so there can only be a single PCH.
  1488. const Module *M = Mod.getModuleOrNull();
  1489. auto ModRef = ModuleCache.find(M);
  1490. if (ModRef != ModuleCache.end())
  1491. return cast<llvm::DIModule>(ModRef->second);
  1492. // Macro definitions that were defined with "-D" on the command line.
  1493. SmallString<128> ConfigMacros;
  1494. {
  1495. llvm::raw_svector_ostream OS(ConfigMacros);
  1496. const auto &PPOpts = CGM.getPreprocessorOpts();
  1497. unsigned I = 0;
  1498. // Translate the macro definitions back into a commmand line.
  1499. for (auto &M : PPOpts.Macros) {
  1500. if (++I > 1)
  1501. OS << " ";
  1502. const std::string &Macro = M.first;
  1503. bool Undef = M.second;
  1504. OS << "\"-" << (Undef ? 'U' : 'D');
  1505. for (char c : Macro)
  1506. switch (c) {
  1507. case '\\' : OS << "\\\\"; break;
  1508. case '"' : OS << "\\\""; break;
  1509. default: OS << c;
  1510. }
  1511. OS << '\"';
  1512. }
  1513. }
  1514. bool IsRootModule = M ? !M->Parent : true;
  1515. if (CreateSkeletonCU && IsRootModule) {
  1516. llvm::DIBuilder DIB(CGM.getModule());
  1517. DIB.createCompileUnit(TheCU->getSourceLanguage(), Mod.getModuleName(),
  1518. Mod.getPath(), TheCU->getProducer(), true,
  1519. StringRef(), 0, Mod.getASTFile(),
  1520. llvm::DIBuilder::FullDebug, Mod.getSignature());
  1521. DIB.finalize();
  1522. }
  1523. llvm::DIModule *Parent =
  1524. IsRootModule ? nullptr
  1525. : getOrCreateModuleRef(
  1526. ExternalASTSource::ASTSourceDescriptor(*M->Parent),
  1527. CreateSkeletonCU);
  1528. llvm::DIModule *DIMod =
  1529. DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
  1530. Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
  1531. ModuleCache[M].reset(DIMod);
  1532. return DIMod;
  1533. }
  1534. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
  1535. llvm::DIFile *Unit) {
  1536. ObjCInterfaceDecl *ID = Ty->getDecl();
  1537. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1538. unsigned Line = getLineNumber(ID->getLocation());
  1539. unsigned RuntimeLang = TheCU->getSourceLanguage();
  1540. // Bit size, align and offset of the type.
  1541. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1542. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1543. unsigned Flags = 0;
  1544. if (ID->getImplementation())
  1545. Flags |= llvm::DINode::FlagObjcClassComplete;
  1546. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  1547. llvm::DICompositeType *RealDecl = DBuilder.createStructType(
  1548. Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
  1549. nullptr, llvm::DINodeArray(), RuntimeLang);
  1550. QualType QTy(Ty, 0);
  1551. TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
  1552. // Push the struct on region stack.
  1553. LexicalBlockStack.emplace_back(RealDecl);
  1554. RegionMap[Ty->getDecl()].reset(RealDecl);
  1555. // Convert all the elements.
  1556. SmallVector<llvm::Metadata *, 16> EltTys;
  1557. ObjCInterfaceDecl *SClass = ID->getSuperClass();
  1558. if (SClass) {
  1559. llvm::DIType *SClassTy =
  1560. getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
  1561. if (!SClassTy)
  1562. return nullptr;
  1563. llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
  1564. EltTys.push_back(InhTag);
  1565. }
  1566. // Create entries for all of the properties.
  1567. auto AddProperty = [&](const ObjCPropertyDecl *PD) {
  1568. SourceLocation Loc = PD->getLocation();
  1569. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1570. unsigned PLine = getLineNumber(Loc);
  1571. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1572. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1573. llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
  1574. PD->getName(), PUnit, PLine,
  1575. hasDefaultGetterName(PD, Getter) ? ""
  1576. : getSelectorName(PD->getGetterName()),
  1577. hasDefaultSetterName(PD, Setter) ? ""
  1578. : getSelectorName(PD->getSetterName()),
  1579. PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
  1580. EltTys.push_back(PropertyNode);
  1581. };
  1582. {
  1583. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  1584. for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
  1585. for (auto *PD : ClassExt->properties()) {
  1586. PropertySet.insert(PD->getIdentifier());
  1587. AddProperty(PD);
  1588. }
  1589. for (const auto *PD : ID->properties()) {
  1590. // Don't emit duplicate metadata for properties that were already in a
  1591. // class extension.
  1592. if (!PropertySet.insert(PD->getIdentifier()).second)
  1593. continue;
  1594. AddProperty(PD);
  1595. }
  1596. }
  1597. const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
  1598. unsigned FieldNo = 0;
  1599. for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
  1600. Field = Field->getNextIvar(), ++FieldNo) {
  1601. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  1602. if (!FieldTy)
  1603. return nullptr;
  1604. StringRef FieldName = Field->getName();
  1605. // Ignore unnamed fields.
  1606. if (FieldName.empty())
  1607. continue;
  1608. // Get the location for the field.
  1609. llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
  1610. unsigned FieldLine = getLineNumber(Field->getLocation());
  1611. QualType FType = Field->getType();
  1612. uint64_t FieldSize = 0;
  1613. unsigned FieldAlign = 0;
  1614. if (!FType->isIncompleteArrayType()) {
  1615. // Bit size, align and offset of the type.
  1616. FieldSize = Field->isBitField()
  1617. ? Field->getBitWidthValue(CGM.getContext())
  1618. : CGM.getContext().getTypeSize(FType);
  1619. FieldAlign = CGM.getContext().getTypeAlign(FType);
  1620. }
  1621. uint64_t FieldOffset;
  1622. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  1623. // We don't know the runtime offset of an ivar if we're using the
  1624. // non-fragile ABI. For bitfields, use the bit offset into the first
  1625. // byte of storage of the bitfield. For other fields, use zero.
  1626. if (Field->isBitField()) {
  1627. FieldOffset =
  1628. CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
  1629. FieldOffset %= CGM.getContext().getCharWidth();
  1630. } else {
  1631. FieldOffset = 0;
  1632. }
  1633. } else {
  1634. FieldOffset = RL.getFieldOffset(FieldNo);
  1635. }
  1636. unsigned Flags = 0;
  1637. if (Field->getAccessControl() == ObjCIvarDecl::Protected)
  1638. Flags = llvm::DINode::FlagProtected;
  1639. else if (Field->getAccessControl() == ObjCIvarDecl::Private)
  1640. Flags = llvm::DINode::FlagPrivate;
  1641. else if (Field->getAccessControl() == ObjCIvarDecl::Public)
  1642. Flags = llvm::DINode::FlagPublic;
  1643. llvm::MDNode *PropertyNode = nullptr;
  1644. if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
  1645. if (ObjCPropertyImplDecl *PImpD =
  1646. ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
  1647. if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
  1648. SourceLocation Loc = PD->getLocation();
  1649. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1650. unsigned PLine = getLineNumber(Loc);
  1651. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1652. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1653. PropertyNode = DBuilder.createObjCProperty(
  1654. PD->getName(), PUnit, PLine,
  1655. hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
  1656. PD->getGetterName()),
  1657. hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
  1658. PD->getSetterName()),
  1659. PD->getPropertyAttributes(),
  1660. getOrCreateType(PD->getType(), PUnit));
  1661. }
  1662. }
  1663. }
  1664. FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
  1665. FieldSize, FieldAlign, FieldOffset, Flags,
  1666. FieldTy, PropertyNode);
  1667. EltTys.push_back(FieldTy);
  1668. }
  1669. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1670. DBuilder.replaceArrays(RealDecl, Elements);
  1671. LexicalBlockStack.pop_back();
  1672. return RealDecl;
  1673. }
  1674. llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
  1675. llvm::DIFile *Unit) {
  1676. llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
  1677. int64_t Count = Ty->getNumElements();
  1678. if (Count == 0)
  1679. // If number of elements are not known then this is an unbounded array.
  1680. // Use Count == -1 to express such arrays.
  1681. Count = -1;
  1682. llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
  1683. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
  1684. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1685. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1686. return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
  1687. }
  1688. llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
  1689. uint64_t Size;
  1690. uint64_t Align;
  1691. // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
  1692. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
  1693. Size = 0;
  1694. Align =
  1695. CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
  1696. } else if (Ty->isIncompleteArrayType()) {
  1697. Size = 0;
  1698. if (Ty->getElementType()->isIncompleteType())
  1699. Align = 0;
  1700. else
  1701. Align = CGM.getContext().getTypeAlign(Ty->getElementType());
  1702. } else if (Ty->isIncompleteType()) {
  1703. Size = 0;
  1704. Align = 0;
  1705. } else {
  1706. // Size and align of the whole array, not the element type.
  1707. Size = CGM.getContext().getTypeSize(Ty);
  1708. Align = CGM.getContext().getTypeAlign(Ty);
  1709. }
  1710. // Add the dimensions of the array. FIXME: This loses CV qualifiers from
  1711. // interior arrays, do we care? Why aren't nested arrays represented the
  1712. // obvious/recursive way?
  1713. SmallVector<llvm::Metadata *, 8> Subscripts;
  1714. QualType EltTy(Ty, 0);
  1715. while ((Ty = dyn_cast<ArrayType>(EltTy))) {
  1716. // If the number of elements is known, then count is that number. Otherwise,
  1717. // it's -1. This allows us to represent a subrange with an array of 0
  1718. // elements, like this:
  1719. //
  1720. // struct foo {
  1721. // int x[0];
  1722. // };
  1723. int64_t Count = -1; // Count == -1 is an unbounded array.
  1724. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
  1725. Count = CAT->getSize().getZExtValue();
  1726. // FIXME: Verify this is right for VLAs.
  1727. Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
  1728. EltTy = Ty->getElementType();
  1729. }
  1730. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
  1731. return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
  1732. SubscriptArray);
  1733. }
  1734. llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
  1735. llvm::DIFile *Unit) {
  1736. return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
  1737. Ty->getPointeeType(), Unit);
  1738. }
  1739. llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
  1740. llvm::DIFile *Unit) {
  1741. return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
  1742. Ty->getPointeeType(), Unit);
  1743. }
  1744. llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
  1745. llvm::DIFile *U) {
  1746. uint64_t Size =
  1747. !Ty->isIncompleteType() ? CGM.getContext().getTypeSize(Ty) : 0;
  1748. llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
  1749. if (Ty->isMemberDataPointerType())
  1750. return DBuilder.createMemberPointerType(
  1751. getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
  1752. const FunctionProtoType *FPT =
  1753. Ty->getPointeeType()->getAs<FunctionProtoType>();
  1754. return DBuilder.createMemberPointerType(
  1755. getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
  1756. Ty->getClass(), FPT->getTypeQuals())),
  1757. FPT, U),
  1758. ClassType, Size);
  1759. }
  1760. llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
  1761. // Ignore the atomic wrapping
  1762. // FIXME: What is the correct representation?
  1763. return getOrCreateType(Ty->getValueType(), U);
  1764. }
  1765. llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
  1766. llvm::DIFile *U) {
  1767. return getOrCreateType(Ty->getElementType(), U);
  1768. }
  1769. llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
  1770. const EnumDecl *ED = Ty->getDecl();
  1771. uint64_t Size = 0;
  1772. uint64_t Align = 0;
  1773. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1774. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1775. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1776. }
  1777. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1778. bool isImportedFromModule =
  1779. DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
  1780. // If this is just a forward declaration, construct an appropriately
  1781. // marked node and just return it.
  1782. if (isImportedFromModule || !ED->getDefinition()) {
  1783. llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
  1784. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  1785. unsigned Line = getLineNumber(ED->getLocation());
  1786. StringRef EDName = ED->getName();
  1787. llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
  1788. llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
  1789. 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
  1790. ReplaceMap.emplace_back(
  1791. std::piecewise_construct, std::make_tuple(Ty),
  1792. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  1793. return RetTy;
  1794. }
  1795. return CreateTypeDefinition(Ty);
  1796. }
  1797. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
  1798. const EnumDecl *ED = Ty->getDecl();
  1799. uint64_t Size = 0;
  1800. uint64_t Align = 0;
  1801. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1802. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1803. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1804. }
  1805. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1806. // Create elements for each enumerator.
  1807. SmallVector<llvm::Metadata *, 16> Enumerators;
  1808. ED = ED->getDefinition();
  1809. for (const auto *Enum : ED->enumerators()) {
  1810. Enumerators.push_back(DBuilder.createEnumerator(
  1811. Enum->getName(), Enum->getInitVal().getSExtValue()));
  1812. }
  1813. // Return a CompositeType for the enum itself.
  1814. llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
  1815. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  1816. unsigned Line = getLineNumber(ED->getLocation());
  1817. llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
  1818. llvm::DIType *ClassTy =
  1819. ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
  1820. return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
  1821. Line, Size, Align, EltArray, ClassTy,
  1822. FullName);
  1823. }
  1824. static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
  1825. Qualifiers Quals;
  1826. do {
  1827. Qualifiers InnerQuals = T.getLocalQualifiers();
  1828. // Qualifiers::operator+() doesn't like it if you add a Qualifier
  1829. // that is already there.
  1830. Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
  1831. Quals += InnerQuals;
  1832. QualType LastT = T;
  1833. switch (T->getTypeClass()) {
  1834. default:
  1835. return C.getQualifiedType(T.getTypePtr(), Quals);
  1836. case Type::TemplateSpecialization: {
  1837. const auto *Spec = cast<TemplateSpecializationType>(T);
  1838. if (Spec->isTypeAlias())
  1839. return C.getQualifiedType(T.getTypePtr(), Quals);
  1840. T = Spec->desugar();
  1841. break;
  1842. }
  1843. case Type::TypeOfExpr:
  1844. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  1845. break;
  1846. case Type::TypeOf:
  1847. T = cast<TypeOfType>(T)->getUnderlyingType();
  1848. break;
  1849. case Type::Decltype:
  1850. T = cast<DecltypeType>(T)->getUnderlyingType();
  1851. break;
  1852. case Type::UnaryTransform:
  1853. T = cast<UnaryTransformType>(T)->getUnderlyingType();
  1854. break;
  1855. case Type::Attributed:
  1856. T = cast<AttributedType>(T)->getEquivalentType();
  1857. break;
  1858. case Type::Elaborated:
  1859. T = cast<ElaboratedType>(T)->getNamedType();
  1860. break;
  1861. case Type::Paren:
  1862. T = cast<ParenType>(T)->getInnerType();
  1863. break;
  1864. case Type::SubstTemplateTypeParm:
  1865. T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
  1866. break;
  1867. case Type::Auto:
  1868. QualType DT = cast<AutoType>(T)->getDeducedType();
  1869. assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
  1870. T = DT;
  1871. break;
  1872. }
  1873. assert(T != LastT && "Type unwrapping failed to unwrap!");
  1874. (void)LastT;
  1875. } while (true);
  1876. }
  1877. llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
  1878. // Unwrap the type as needed for debug information.
  1879. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  1880. auto it = TypeCache.find(Ty.getAsOpaquePtr());
  1881. if (it != TypeCache.end()) {
  1882. // Verify that the debug info still exists.
  1883. if (llvm::Metadata *V = it->second)
  1884. return cast<llvm::DIType>(V);
  1885. }
  1886. return nullptr;
  1887. }
  1888. void CGDebugInfo::completeTemplateDefinition(
  1889. const ClassTemplateSpecializationDecl &SD) {
  1890. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1891. return;
  1892. completeClassData(&SD);
  1893. // In case this type has no member function definitions being emitted, ensure
  1894. // it is retained
  1895. RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
  1896. }
  1897. llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
  1898. if (Ty.isNull())
  1899. return nullptr;
  1900. // Unwrap the type as needed for debug information.
  1901. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  1902. if (auto *T = getTypeOrNull(Ty))
  1903. return T;
  1904. llvm::DIType *Res = CreateTypeNode(Ty, Unit);
  1905. void* TyPtr = Ty.getAsOpaquePtr();
  1906. // And update the type cache.
  1907. TypeCache[TyPtr].reset(Res);
  1908. return Res;
  1909. }
  1910. llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
  1911. // A forward declaration inside a module header does not belong to the module.
  1912. if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
  1913. return nullptr;
  1914. if (DebugTypeExtRefs && D->isFromASTFile()) {
  1915. // Record a reference to an imported clang module or precompiled header.
  1916. auto *Reader = CGM.getContext().getExternalSource();
  1917. auto Idx = D->getOwningModuleID();
  1918. auto Info = Reader->getSourceDescriptor(Idx);
  1919. if (Info)
  1920. return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
  1921. } else if (ClangModuleMap) {
  1922. // We are building a clang module or a precompiled header.
  1923. //
  1924. // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
  1925. // and it wouldn't be necessary to specify the parent scope
  1926. // because the type is already unique by definition (it would look
  1927. // like the output of -fno-standalone-debug). On the other hand,
  1928. // the parent scope helps a consumer to quickly locate the object
  1929. // file where the type's definition is located, so it might be
  1930. // best to make this behavior a command line or debugger tuning
  1931. // option.
  1932. FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
  1933. if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) {
  1934. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  1935. return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
  1936. }
  1937. }
  1938. return nullptr;
  1939. }
  1940. llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
  1941. // Handle qualifiers, which recursively handles what they refer to.
  1942. if (Ty.hasLocalQualifiers())
  1943. return CreateQualifiedType(Ty, Unit);
  1944. // Work out details of type.
  1945. switch (Ty->getTypeClass()) {
  1946. #define TYPE(Class, Base)
  1947. #define ABSTRACT_TYPE(Class, Base)
  1948. #define NON_CANONICAL_TYPE(Class, Base)
  1949. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1950. #include "clang/AST/TypeNodes.def"
  1951. llvm_unreachable("Dependent types cannot show up in debug information");
  1952. case Type::ExtVector:
  1953. case Type::Vector:
  1954. return CreateType(cast<VectorType>(Ty), Unit);
  1955. case Type::ObjCObjectPointer:
  1956. return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
  1957. case Type::ObjCObject:
  1958. return CreateType(cast<ObjCObjectType>(Ty), Unit);
  1959. case Type::ObjCInterface:
  1960. return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
  1961. case Type::Builtin:
  1962. return CreateType(cast<BuiltinType>(Ty));
  1963. case Type::Complex:
  1964. return CreateType(cast<ComplexType>(Ty));
  1965. case Type::Pointer:
  1966. return CreateType(cast<PointerType>(Ty), Unit);
  1967. case Type::Adjusted:
  1968. case Type::Decayed:
  1969. // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
  1970. return CreateType(
  1971. cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
  1972. case Type::BlockPointer:
  1973. return CreateType(cast<BlockPointerType>(Ty), Unit);
  1974. case Type::Typedef:
  1975. return CreateType(cast<TypedefType>(Ty), Unit);
  1976. case Type::Record:
  1977. return CreateType(cast<RecordType>(Ty));
  1978. case Type::Enum:
  1979. return CreateEnumType(cast<EnumType>(Ty));
  1980. case Type::FunctionProto:
  1981. case Type::FunctionNoProto:
  1982. return CreateType(cast<FunctionType>(Ty), Unit);
  1983. case Type::ConstantArray:
  1984. case Type::VariableArray:
  1985. case Type::IncompleteArray:
  1986. return CreateType(cast<ArrayType>(Ty), Unit);
  1987. case Type::LValueReference:
  1988. return CreateType(cast<LValueReferenceType>(Ty), Unit);
  1989. case Type::RValueReference:
  1990. return CreateType(cast<RValueReferenceType>(Ty), Unit);
  1991. case Type::MemberPointer:
  1992. return CreateType(cast<MemberPointerType>(Ty), Unit);
  1993. case Type::Atomic:
  1994. return CreateType(cast<AtomicType>(Ty), Unit);
  1995. case Type::Pipe:
  1996. return CreateType(cast<PipeType>(Ty), Unit);
  1997. case Type::TemplateSpecialization:
  1998. return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
  1999. case Type::Auto:
  2000. case Type::Attributed:
  2001. case Type::Elaborated:
  2002. case Type::Paren:
  2003. case Type::SubstTemplateTypeParm:
  2004. case Type::TypeOfExpr:
  2005. case Type::TypeOf:
  2006. case Type::Decltype:
  2007. case Type::UnaryTransform:
  2008. case Type::PackExpansion:
  2009. break;
  2010. }
  2011. llvm_unreachable("type should have been unwrapped!");
  2012. }
  2013. llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
  2014. llvm::DIFile *Unit) {
  2015. QualType QTy(Ty, 0);
  2016. auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
  2017. // We may have cached a forward decl when we could have created
  2018. // a non-forward decl. Go ahead and create a non-forward decl
  2019. // now.
  2020. if (T && !T->isForwardDecl())
  2021. return T;
  2022. // Otherwise create the type.
  2023. llvm::DICompositeType *Res = CreateLimitedType(Ty);
  2024. // Propagate members from the declaration to the definition
  2025. // CreateType(const RecordType*) will overwrite this with the members in the
  2026. // correct order if the full type is needed.
  2027. DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
  2028. // And update the type cache.
  2029. TypeCache[QTy.getAsOpaquePtr()].reset(Res);
  2030. return Res;
  2031. }
  2032. // TODO: Currently used for context chains when limiting debug info.
  2033. llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
  2034. RecordDecl *RD = Ty->getDecl();
  2035. // Get overall information about the record type for the debug info.
  2036. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  2037. unsigned Line = getLineNumber(RD->getLocation());
  2038. StringRef RDName = getClassName(RD);
  2039. llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
  2040. // If we ended up creating the type during the context chain construction,
  2041. // just return that.
  2042. auto *T = cast_or_null<llvm::DICompositeType>(
  2043. getTypeOrNull(CGM.getContext().getRecordType(RD)));
  2044. if (T && (!T->isForwardDecl() || !RD->getDefinition()))
  2045. return T;
  2046. // If this is just a forward or incomplete declaration, construct an
  2047. // appropriately marked node and just return it.
  2048. const RecordDecl *D = RD->getDefinition();
  2049. if (!D || !D->isCompleteDefinition())
  2050. return getOrCreateRecordFwdDecl(Ty, RDContext);
  2051. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  2052. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  2053. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  2054. llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
  2055. getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
  2056. FullName);
  2057. RegionMap[Ty->getDecl()].reset(RealDecl);
  2058. TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
  2059. if (const ClassTemplateSpecializationDecl *TSpecial =
  2060. dyn_cast<ClassTemplateSpecializationDecl>(RD))
  2061. DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
  2062. CollectCXXTemplateParams(TSpecial, DefUnit));
  2063. return RealDecl;
  2064. }
  2065. void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
  2066. llvm::DICompositeType *RealDecl) {
  2067. // A class's primary base or the class itself contains the vtable.
  2068. llvm::DICompositeType *ContainingType = nullptr;
  2069. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  2070. if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
  2071. // Seek non-virtual primary base root.
  2072. while (1) {
  2073. const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
  2074. const CXXRecordDecl *PBT = BRL.getPrimaryBase();
  2075. if (PBT && !BRL.isPrimaryBaseVirtual())
  2076. PBase = PBT;
  2077. else
  2078. break;
  2079. }
  2080. ContainingType = cast<llvm::DICompositeType>(
  2081. getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
  2082. getOrCreateFile(RD->getLocation())));
  2083. } else if (RD->isDynamicClass())
  2084. ContainingType = RealDecl;
  2085. DBuilder.replaceVTableHolder(RealDecl, ContainingType);
  2086. }
  2087. llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
  2088. StringRef Name, uint64_t *Offset) {
  2089. llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  2090. uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
  2091. unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
  2092. llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
  2093. FieldAlign, *Offset, 0, FieldTy);
  2094. *Offset += FieldSize;
  2095. return Ty;
  2096. }
  2097. void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
  2098. StringRef &Name,
  2099. StringRef &LinkageName,
  2100. llvm::DIScope *&FDContext,
  2101. llvm::DINodeArray &TParamsArray,
  2102. unsigned &Flags) {
  2103. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2104. Name = getFunctionName(FD);
  2105. // Use mangled name as linkage name for C/C++ functions.
  2106. if (FD->hasPrototype()) {
  2107. LinkageName = CGM.getMangledName(GD);
  2108. Flags |= llvm::DINode::FlagPrototyped;
  2109. }
  2110. // No need to replicate the linkage name if it isn't different from the
  2111. // subprogram name, no need to have it at all unless coverage is enabled or
  2112. // debug is set to more than just line tables.
  2113. if (LinkageName == Name ||
  2114. (!CGM.getCodeGenOpts().EmitGcovArcs &&
  2115. !CGM.getCodeGenOpts().EmitGcovNotes &&
  2116. DebugKind <= CodeGenOptions::DebugLineTablesOnly))
  2117. LinkageName = StringRef();
  2118. if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
  2119. if (const NamespaceDecl *NSDecl =
  2120. dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
  2121. FDContext = getOrCreateNameSpace(NSDecl);
  2122. else if (const RecordDecl *RDecl =
  2123. dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
  2124. llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
  2125. FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
  2126. }
  2127. // Collect template parameters.
  2128. TParamsArray = CollectFunctionTemplateParams(FD, Unit);
  2129. }
  2130. }
  2131. void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
  2132. unsigned &LineNo, QualType &T,
  2133. StringRef &Name, StringRef &LinkageName,
  2134. llvm::DIScope *&VDContext) {
  2135. Unit = getOrCreateFile(VD->getLocation());
  2136. LineNo = getLineNumber(VD->getLocation());
  2137. setLocation(VD->getLocation());
  2138. T = VD->getType();
  2139. if (T->isIncompleteArrayType()) {
  2140. // CodeGen turns int[] into int[1] so we'll do the same here.
  2141. llvm::APInt ConstVal(32, 1);
  2142. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2143. T = CGM.getContext().getConstantArrayType(ET, ConstVal,
  2144. ArrayType::Normal, 0);
  2145. }
  2146. Name = VD->getName();
  2147. if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
  2148. !isa<ObjCMethodDecl>(VD->getDeclContext()))
  2149. LinkageName = CGM.getMangledName(VD);
  2150. if (LinkageName == Name)
  2151. LinkageName = StringRef();
  2152. // Since we emit declarations (DW_AT_members) for static members, place the
  2153. // definition of those static members in the namespace they were declared in
  2154. // in the source code (the lexical decl context).
  2155. // FIXME: Generalize this for even non-member global variables where the
  2156. // declaration and definition may have different lexical decl contexts, once
  2157. // we have support for emitting declarations of (non-member) global variables.
  2158. const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
  2159. : VD->getDeclContext();
  2160. // When a record type contains an in-line initialization of a static data
  2161. // member, and the record type is marked as __declspec(dllexport), an implicit
  2162. // definition of the member will be created in the record context. DWARF
  2163. // doesn't seem to have a nice way to describe this in a form that consumers
  2164. // are likely to understand, so fake the "normal" situation of a definition
  2165. // outside the class by putting it in the global scope.
  2166. if (DC->isRecord())
  2167. DC = CGM.getContext().getTranslationUnitDecl();
  2168. llvm::DIScope *Mod = getParentModuleOrNull(VD);
  2169. VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
  2170. }
  2171. llvm::DISubprogram *
  2172. CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
  2173. llvm::DINodeArray TParamsArray;
  2174. StringRef Name, LinkageName;
  2175. unsigned Flags = 0;
  2176. SourceLocation Loc = FD->getLocation();
  2177. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2178. llvm::DIScope *DContext = Unit;
  2179. unsigned Line = getLineNumber(Loc);
  2180. collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
  2181. TParamsArray, Flags);
  2182. // Build function type.
  2183. SmallVector<QualType, 16> ArgTypes;
  2184. for (const ParmVarDecl *Parm: FD->parameters())
  2185. ArgTypes.push_back(Parm->getType());
  2186. QualType FnType =
  2187. CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
  2188. FunctionProtoType::ExtProtoInfo());
  2189. llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
  2190. DContext, Name, LinkageName, Unit, Line,
  2191. getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
  2192. /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
  2193. TParamsArray.get(), getFunctionDeclaration(FD));
  2194. const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
  2195. FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
  2196. std::make_tuple(CanonDecl),
  2197. std::make_tuple(SP));
  2198. return SP;
  2199. }
  2200. llvm::DIGlobalVariable *
  2201. CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
  2202. QualType T;
  2203. StringRef Name, LinkageName;
  2204. SourceLocation Loc = VD->getLocation();
  2205. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2206. llvm::DIScope *DContext = Unit;
  2207. unsigned Line = getLineNumber(Loc);
  2208. collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
  2209. auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
  2210. DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
  2211. !VD->isExternallyVisible(), nullptr, nullptr);
  2212. FwdDeclReplaceMap.emplace_back(
  2213. std::piecewise_construct,
  2214. std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
  2215. std::make_tuple(static_cast<llvm::Metadata *>(GV)));
  2216. return GV;
  2217. }
  2218. llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
  2219. // We only need a declaration (not a definition) of the type - so use whatever
  2220. // we would otherwise do to get a type for a pointee. (forward declarations in
  2221. // limited debug info, full definitions (if the type definition is available)
  2222. // in unlimited debug info)
  2223. if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
  2224. return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
  2225. getOrCreateFile(TD->getLocation()));
  2226. auto I = DeclCache.find(D->getCanonicalDecl());
  2227. if (I != DeclCache.end())
  2228. return dyn_cast_or_null<llvm::DINode>(I->second);
  2229. // No definition for now. Emit a forward definition that might be
  2230. // merged with a potential upcoming definition.
  2231. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  2232. return getFunctionForwardDeclaration(FD);
  2233. else if (const auto *VD = dyn_cast<VarDecl>(D))
  2234. return getGlobalVariableForwardDeclaration(VD);
  2235. return nullptr;
  2236. }
  2237. llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
  2238. if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2239. return nullptr;
  2240. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  2241. if (!FD)
  2242. return nullptr;
  2243. // Setup context.
  2244. auto *S = getDeclContextDescriptor(D);
  2245. auto MI = SPCache.find(FD->getCanonicalDecl());
  2246. if (MI == SPCache.end()) {
  2247. if (const CXXMethodDecl *MD =
  2248. dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
  2249. return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
  2250. cast<llvm::DICompositeType>(S));
  2251. }
  2252. }
  2253. if (MI != SPCache.end()) {
  2254. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2255. if (SP && !SP->isDefinition())
  2256. return SP;
  2257. }
  2258. for (auto NextFD : FD->redecls()) {
  2259. auto MI = SPCache.find(NextFD->getCanonicalDecl());
  2260. if (MI != SPCache.end()) {
  2261. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2262. if (SP && !SP->isDefinition())
  2263. return SP;
  2264. }
  2265. }
  2266. return nullptr;
  2267. }
  2268. // getOrCreateFunctionType - Construct type. If it is a c++ method, include
  2269. // implicit parameter "this".
  2270. llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
  2271. QualType FnType,
  2272. llvm::DIFile *F) {
  2273. if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2274. // Create fake but valid subroutine type. Otherwise -verify would fail, and
  2275. // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
  2276. return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
  2277. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  2278. return getOrCreateMethodType(Method, F);
  2279. if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
  2280. // Add "self" and "_cmd"
  2281. SmallVector<llvm::Metadata *, 16> Elts;
  2282. // First element is always return type. For 'void' functions it is NULL.
  2283. QualType ResultTy = OMethod->getReturnType();
  2284. // Replace the instancetype keyword with the actual type.
  2285. if (ResultTy == CGM.getContext().getObjCInstanceType())
  2286. ResultTy = CGM.getContext().getPointerType(
  2287. QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
  2288. Elts.push_back(getOrCreateType(ResultTy, F));
  2289. // "self" pointer is always first argument.
  2290. QualType SelfDeclTy;
  2291. if (auto *SelfDecl = OMethod->getSelfDecl())
  2292. SelfDeclTy = SelfDecl->getType();
  2293. else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
  2294. if (FPT->getNumParams() > 1)
  2295. SelfDeclTy = FPT->getParamType(0);
  2296. if (!SelfDeclTy.isNull())
  2297. Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
  2298. // "_cmd" pointer is always second argument.
  2299. Elts.push_back(DBuilder.createArtificialType(
  2300. getOrCreateType(CGM.getContext().getObjCSelType(), F)));
  2301. // Get rest of the arguments.
  2302. for (const auto *PI : OMethod->params())
  2303. Elts.push_back(getOrCreateType(PI->getType(), F));
  2304. // Variadic methods need a special marker at the end of the type list.
  2305. if (OMethod->isVariadic())
  2306. Elts.push_back(DBuilder.createUnspecifiedParameter());
  2307. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  2308. return DBuilder.createSubroutineType(EltTypeArray);
  2309. }
  2310. // Handle variadic function types; they need an additional
  2311. // unspecified parameter.
  2312. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2313. if (FD->isVariadic()) {
  2314. SmallVector<llvm::Metadata *, 16> EltTys;
  2315. EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
  2316. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
  2317. for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
  2318. EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
  2319. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  2320. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  2321. return DBuilder.createSubroutineType(EltTypeArray);
  2322. }
  2323. return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
  2324. }
  2325. void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
  2326. SourceLocation ScopeLoc, QualType FnType,
  2327. llvm::Function *Fn, CGBuilderTy &Builder) {
  2328. StringRef Name;
  2329. StringRef LinkageName;
  2330. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  2331. const Decl *D = GD.getDecl();
  2332. bool HasDecl = (D != nullptr);
  2333. unsigned Flags = 0;
  2334. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2335. llvm::DIScope *FDContext = Unit;
  2336. llvm::DINodeArray TParamsArray;
  2337. if (!HasDecl) {
  2338. // Use llvm function name.
  2339. LinkageName = Fn->getName();
  2340. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2341. // If there is a subprogram for this function available then use it.
  2342. auto FI = SPCache.find(FD->getCanonicalDecl());
  2343. if (FI != SPCache.end()) {
  2344. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
  2345. if (SP && SP->isDefinition()) {
  2346. LexicalBlockStack.emplace_back(SP);
  2347. RegionMap[D].reset(SP);
  2348. return;
  2349. }
  2350. }
  2351. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2352. TParamsArray, Flags);
  2353. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2354. Name = getObjCMethodName(OMD);
  2355. Flags |= llvm::DINode::FlagPrototyped;
  2356. } else {
  2357. // Use llvm function name.
  2358. Name = Fn->getName();
  2359. Flags |= llvm::DINode::FlagPrototyped;
  2360. }
  2361. if (!Name.empty() && Name[0] == '\01')
  2362. Name = Name.substr(1);
  2363. if (!HasDecl || D->isImplicit()) {
  2364. Flags |= llvm::DINode::FlagArtificial;
  2365. // Artificial functions without a location should not silently reuse CurLoc.
  2366. if (Loc.isInvalid())
  2367. CurLoc = SourceLocation();
  2368. }
  2369. unsigned LineNo = getLineNumber(Loc);
  2370. unsigned ScopeLine = getLineNumber(ScopeLoc);
  2371. // FIXME: The function declaration we're constructing here is mostly reusing
  2372. // declarations from CXXMethodDecl and not constructing new ones for arbitrary
  2373. // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
  2374. // all subprograms instead of the actual context since subprogram definitions
  2375. // are emitted as CU level entities by the backend.
  2376. llvm::DISubprogram *SP = DBuilder.createFunction(
  2377. FDContext, Name, LinkageName, Unit, LineNo,
  2378. getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
  2379. true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
  2380. TParamsArray.get(), getFunctionDeclaration(D));
  2381. Fn->setSubprogram(SP);
  2382. // We might get here with a VarDecl in the case we're generating
  2383. // code for the initialization of globals. Do not record these decls
  2384. // as they will overwrite the actual VarDecl Decl in the cache.
  2385. if (HasDecl && isa<FunctionDecl>(D))
  2386. DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
  2387. // Push the function onto the lexical block stack.
  2388. LexicalBlockStack.emplace_back(SP);
  2389. if (HasDecl)
  2390. RegionMap[D].reset(SP);
  2391. }
  2392. void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
  2393. QualType FnType) {
  2394. StringRef Name;
  2395. StringRef LinkageName;
  2396. const Decl *D = GD.getDecl();
  2397. if (!D)
  2398. return;
  2399. unsigned Flags = 0;
  2400. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2401. llvm::DIScope *FDContext = getDeclContextDescriptor(D);
  2402. llvm::DINodeArray TParamsArray;
  2403. if (isa<FunctionDecl>(D)) {
  2404. // If there is a DISubprogram for this function available then use it.
  2405. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2406. TParamsArray, Flags);
  2407. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2408. Name = getObjCMethodName(OMD);
  2409. Flags |= llvm::DINode::FlagPrototyped;
  2410. } else {
  2411. llvm_unreachable("not a function or ObjC method");
  2412. }
  2413. if (!Name.empty() && Name[0] == '\01')
  2414. Name = Name.substr(1);
  2415. if (D->isImplicit()) {
  2416. Flags |= llvm::DINode::FlagArtificial;
  2417. // Artificial functions without a location should not silently reuse CurLoc.
  2418. if (Loc.isInvalid())
  2419. CurLoc = SourceLocation();
  2420. }
  2421. unsigned LineNo = getLineNumber(Loc);
  2422. unsigned ScopeLine = 0;
  2423. DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
  2424. getOrCreateFunctionType(D, FnType, Unit),
  2425. false /*internalLinkage*/, true /*definition*/,
  2426. ScopeLine, Flags, CGM.getLangOpts().Optimize,
  2427. TParamsArray.get(), getFunctionDeclaration(D));
  2428. }
  2429. void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
  2430. // Update our current location
  2431. setLocation(Loc);
  2432. if (CurLoc.isInvalid() || CurLoc.isMacroID())
  2433. return;
  2434. llvm::MDNode *Scope = LexicalBlockStack.back();
  2435. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2436. getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
  2437. }
  2438. void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
  2439. llvm::MDNode *Back = nullptr;
  2440. if (!LexicalBlockStack.empty())
  2441. Back = LexicalBlockStack.back().get();
  2442. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
  2443. cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
  2444. getColumnNumber(CurLoc)));
  2445. }
  2446. void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
  2447. SourceLocation Loc) {
  2448. // Set our current location.
  2449. setLocation(Loc);
  2450. // Emit a line table change for the current location inside the new scope.
  2451. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2452. getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
  2453. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2454. return;
  2455. // Create a new lexical block and push it on the stack.
  2456. CreateLexicalBlock(Loc);
  2457. }
  2458. void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
  2459. SourceLocation Loc) {
  2460. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2461. // Provide an entry in the line table for the end of the block.
  2462. EmitLocation(Builder, Loc);
  2463. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2464. return;
  2465. LexicalBlockStack.pop_back();
  2466. }
  2467. void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
  2468. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2469. unsigned RCount = FnBeginRegionCount.back();
  2470. assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
  2471. // Pop all regions for this function.
  2472. while (LexicalBlockStack.size() != RCount) {
  2473. // Provide an entry in the line table for the end of the block.
  2474. EmitLocation(Builder, CurLoc);
  2475. LexicalBlockStack.pop_back();
  2476. }
  2477. FnBeginRegionCount.pop_back();
  2478. }
  2479. llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
  2480. uint64_t *XOffset) {
  2481. SmallVector<llvm::Metadata *, 5> EltTys;
  2482. QualType FType;
  2483. uint64_t FieldSize, FieldOffset;
  2484. unsigned FieldAlign;
  2485. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2486. QualType Type = VD->getType();
  2487. FieldOffset = 0;
  2488. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2489. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  2490. EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
  2491. FType = CGM.getContext().IntTy;
  2492. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  2493. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  2494. bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
  2495. if (HasCopyAndDispose) {
  2496. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2497. EltTys.push_back(
  2498. CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
  2499. EltTys.push_back(
  2500. CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
  2501. }
  2502. bool HasByrefExtendedLayout;
  2503. Qualifiers::ObjCLifetime Lifetime;
  2504. if (CGM.getContext().getByrefLifetime(Type, Lifetime,
  2505. HasByrefExtendedLayout) &&
  2506. HasByrefExtendedLayout) {
  2507. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2508. EltTys.push_back(
  2509. CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
  2510. }
  2511. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2512. if (Align > CGM.getContext().toCharUnitsFromBits(
  2513. CGM.getTarget().getPointerAlign(0))) {
  2514. CharUnits FieldOffsetInBytes =
  2515. CGM.getContext().toCharUnitsFromBits(FieldOffset);
  2516. CharUnits AlignedOffsetInBytes =
  2517. FieldOffsetInBytes.RoundUpToAlignment(Align);
  2518. CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
  2519. if (NumPaddingBytes.isPositive()) {
  2520. llvm::APInt pad(32, NumPaddingBytes.getQuantity());
  2521. FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
  2522. pad, ArrayType::Normal, 0);
  2523. EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
  2524. }
  2525. }
  2526. FType = Type;
  2527. llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
  2528. FieldSize = CGM.getContext().getTypeSize(FType);
  2529. FieldAlign = CGM.getContext().toBits(Align);
  2530. *XOffset = FieldOffset;
  2531. FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
  2532. FieldAlign, FieldOffset, 0, FieldTy);
  2533. EltTys.push_back(FieldTy);
  2534. FieldOffset += FieldSize;
  2535. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  2536. unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
  2537. return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
  2538. nullptr, Elements);
  2539. }
  2540. void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
  2541. llvm::Optional<unsigned> ArgNo,
  2542. CGBuilderTy &Builder) {
  2543. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2544. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2545. bool Unwritten =
  2546. VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
  2547. cast<Decl>(VD->getDeclContext())->isImplicit());
  2548. llvm::DIFile *Unit = nullptr;
  2549. if (!Unwritten)
  2550. Unit = getOrCreateFile(VD->getLocation());
  2551. llvm::DIType *Ty;
  2552. uint64_t XOffset = 0;
  2553. if (VD->hasAttr<BlocksAttr>())
  2554. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2555. else
  2556. Ty = getOrCreateType(VD->getType(), Unit);
  2557. // If there is no debug info for this type then do not emit debug info
  2558. // for this variable.
  2559. if (!Ty)
  2560. return;
  2561. // Get location information.
  2562. unsigned Line = 0;
  2563. unsigned Column = 0;
  2564. if (!Unwritten) {
  2565. Line = getLineNumber(VD->getLocation());
  2566. Column = getColumnNumber(VD->getLocation());
  2567. }
  2568. SmallVector<int64_t, 9> Expr;
  2569. unsigned Flags = 0;
  2570. if (VD->isImplicit())
  2571. Flags |= llvm::DINode::FlagArtificial;
  2572. // If this is the first argument and it is implicit then
  2573. // give it an object pointer flag.
  2574. // FIXME: There has to be a better way to do this, but for static
  2575. // functions there won't be an implicit param at arg1 and
  2576. // otherwise it is 'self' or 'this'.
  2577. if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
  2578. Flags |= llvm::DINode::FlagObjectPointer;
  2579. if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
  2580. if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
  2581. !VD->getType()->isPointerType())
  2582. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2583. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  2584. StringRef Name = VD->getName();
  2585. if (!Name.empty()) {
  2586. if (VD->hasAttr<BlocksAttr>()) {
  2587. CharUnits offset = CharUnits::fromQuantity(32);
  2588. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2589. // offset of __forwarding field
  2590. offset = CGM.getContext().toCharUnitsFromBits(
  2591. CGM.getTarget().getPointerWidth(0));
  2592. Expr.push_back(offset.getQuantity());
  2593. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2594. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2595. // offset of x field
  2596. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2597. Expr.push_back(offset.getQuantity());
  2598. // Create the descriptor for the variable.
  2599. auto *D = ArgNo
  2600. ? DBuilder.createParameterVariable(Scope, VD->getName(),
  2601. *ArgNo, Unit, Line, Ty)
  2602. : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
  2603. Line, Ty);
  2604. // Insert an llvm.dbg.declare into the current block.
  2605. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2606. llvm::DebugLoc::get(Line, Column, Scope),
  2607. Builder.GetInsertBlock());
  2608. return;
  2609. } else if (isa<VariableArrayType>(VD->getType()))
  2610. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2611. } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
  2612. // If VD is an anonymous union then Storage represents value for
  2613. // all union fields.
  2614. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  2615. if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
  2616. // GDB has trouble finding local variables in anonymous unions, so we emit
  2617. // artifical local variables for each of the members.
  2618. //
  2619. // FIXME: Remove this code as soon as GDB supports this.
  2620. // The debug info verifier in LLVM operates based on the assumption that a
  2621. // variable has the same size as its storage and we had to disable the check
  2622. // for artificial variables.
  2623. for (const auto *Field : RD->fields()) {
  2624. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2625. StringRef FieldName = Field->getName();
  2626. // Ignore unnamed fields. Do not ignore unnamed records.
  2627. if (FieldName.empty() && !isa<RecordType>(Field->getType()))
  2628. continue;
  2629. // Use VarDecl's Tag, Scope and Line number.
  2630. auto *D = DBuilder.createAutoVariable(
  2631. Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
  2632. Flags | llvm::DINode::FlagArtificial);
  2633. // Insert an llvm.dbg.declare into the current block.
  2634. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2635. llvm::DebugLoc::get(Line, Column, Scope),
  2636. Builder.GetInsertBlock());
  2637. }
  2638. }
  2639. }
  2640. // Create the descriptor for the variable.
  2641. auto *D =
  2642. ArgNo
  2643. ? DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line,
  2644. Ty, CGM.getLangOpts().Optimize,
  2645. Flags)
  2646. : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
  2647. CGM.getLangOpts().Optimize, Flags);
  2648. // Insert an llvm.dbg.declare into the current block.
  2649. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2650. llvm::DebugLoc::get(Line, Column, Scope),
  2651. Builder.GetInsertBlock());
  2652. }
  2653. void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
  2654. llvm::Value *Storage,
  2655. CGBuilderTy &Builder) {
  2656. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2657. EmitDeclare(VD, Storage, llvm::None, Builder);
  2658. }
  2659. llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
  2660. llvm::DIType *Ty) {
  2661. llvm::DIType *CachedTy = getTypeOrNull(QualTy);
  2662. if (CachedTy)
  2663. Ty = CachedTy;
  2664. return DBuilder.createObjectPointerType(Ty);
  2665. }
  2666. void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
  2667. const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
  2668. const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
  2669. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2670. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2671. if (Builder.GetInsertBlock() == nullptr)
  2672. return;
  2673. bool isByRef = VD->hasAttr<BlocksAttr>();
  2674. uint64_t XOffset = 0;
  2675. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2676. llvm::DIType *Ty;
  2677. if (isByRef)
  2678. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2679. else
  2680. Ty = getOrCreateType(VD->getType(), Unit);
  2681. // Self is passed along as an implicit non-arg variable in a
  2682. // block. Mark it as the object pointer.
  2683. if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
  2684. Ty = CreateSelfType(VD->getType(), Ty);
  2685. // Get location information.
  2686. unsigned Line = getLineNumber(VD->getLocation());
  2687. unsigned Column = getColumnNumber(VD->getLocation());
  2688. const llvm::DataLayout &target = CGM.getDataLayout();
  2689. CharUnits offset = CharUnits::fromQuantity(
  2690. target.getStructLayout(blockInfo.StructureType)
  2691. ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
  2692. SmallVector<int64_t, 9> addr;
  2693. if (isa<llvm::AllocaInst>(Storage))
  2694. addr.push_back(llvm::dwarf::DW_OP_deref);
  2695. addr.push_back(llvm::dwarf::DW_OP_plus);
  2696. addr.push_back(offset.getQuantity());
  2697. if (isByRef) {
  2698. addr.push_back(llvm::dwarf::DW_OP_deref);
  2699. addr.push_back(llvm::dwarf::DW_OP_plus);
  2700. // offset of __forwarding field
  2701. offset =
  2702. CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
  2703. addr.push_back(offset.getQuantity());
  2704. addr.push_back(llvm::dwarf::DW_OP_deref);
  2705. addr.push_back(llvm::dwarf::DW_OP_plus);
  2706. // offset of x field
  2707. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2708. addr.push_back(offset.getQuantity());
  2709. }
  2710. // Create the descriptor for the variable.
  2711. auto *D = DBuilder.createAutoVariable(
  2712. cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
  2713. Line, Ty);
  2714. // Insert an llvm.dbg.declare into the current block.
  2715. auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
  2716. if (InsertPoint)
  2717. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  2718. InsertPoint);
  2719. else
  2720. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  2721. Builder.GetInsertBlock());
  2722. }
  2723. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
  2724. unsigned ArgNo,
  2725. CGBuilderTy &Builder) {
  2726. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2727. EmitDeclare(VD, AI, ArgNo, Builder);
  2728. }
  2729. namespace {
  2730. struct BlockLayoutChunk {
  2731. uint64_t OffsetInBits;
  2732. const BlockDecl::Capture *Capture;
  2733. };
  2734. bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
  2735. return l.OffsetInBits < r.OffsetInBits;
  2736. }
  2737. }
  2738. void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  2739. llvm::Value *Arg,
  2740. unsigned ArgNo,
  2741. llvm::Value *LocalAddr,
  2742. CGBuilderTy &Builder) {
  2743. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2744. ASTContext &C = CGM.getContext();
  2745. const BlockDecl *blockDecl = block.getBlockDecl();
  2746. // Collect some general information about the block's location.
  2747. SourceLocation loc = blockDecl->getCaretLocation();
  2748. llvm::DIFile *tunit = getOrCreateFile(loc);
  2749. unsigned line = getLineNumber(loc);
  2750. unsigned column = getColumnNumber(loc);
  2751. // Build the debug-info type for the block literal.
  2752. getDeclContextDescriptor(blockDecl);
  2753. const llvm::StructLayout *blockLayout =
  2754. CGM.getDataLayout().getStructLayout(block.StructureType);
  2755. SmallVector<llvm::Metadata *, 16> fields;
  2756. fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
  2757. blockLayout->getElementOffsetInBits(0),
  2758. tunit, tunit));
  2759. fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
  2760. blockLayout->getElementOffsetInBits(1),
  2761. tunit, tunit));
  2762. fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
  2763. blockLayout->getElementOffsetInBits(2),
  2764. tunit, tunit));
  2765. auto *FnTy = block.getBlockExpr()->getFunctionType();
  2766. auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
  2767. fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
  2768. blockLayout->getElementOffsetInBits(3),
  2769. tunit, tunit));
  2770. fields.push_back(createFieldType(
  2771. "__descriptor", C.getPointerType(block.NeedsCopyDispose
  2772. ? C.getBlockDescriptorExtendedType()
  2773. : C.getBlockDescriptorType()),
  2774. 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
  2775. // We want to sort the captures by offset, not because DWARF
  2776. // requires this, but because we're paranoid about debuggers.
  2777. SmallVector<BlockLayoutChunk, 8> chunks;
  2778. // 'this' capture.
  2779. if (blockDecl->capturesCXXThis()) {
  2780. BlockLayoutChunk chunk;
  2781. chunk.OffsetInBits =
  2782. blockLayout->getElementOffsetInBits(block.CXXThisIndex);
  2783. chunk.Capture = nullptr;
  2784. chunks.push_back(chunk);
  2785. }
  2786. // Variable captures.
  2787. for (const auto &capture : blockDecl->captures()) {
  2788. const VarDecl *variable = capture.getVariable();
  2789. const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
  2790. // Ignore constant captures.
  2791. if (captureInfo.isConstant())
  2792. continue;
  2793. BlockLayoutChunk chunk;
  2794. chunk.OffsetInBits =
  2795. blockLayout->getElementOffsetInBits(captureInfo.getIndex());
  2796. chunk.Capture = &capture;
  2797. chunks.push_back(chunk);
  2798. }
  2799. // Sort by offset.
  2800. llvm::array_pod_sort(chunks.begin(), chunks.end());
  2801. for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
  2802. e = chunks.end();
  2803. i != e; ++i) {
  2804. uint64_t offsetInBits = i->OffsetInBits;
  2805. const BlockDecl::Capture *capture = i->Capture;
  2806. // If we have a null capture, this must be the C++ 'this' capture.
  2807. if (!capture) {
  2808. const CXXMethodDecl *method =
  2809. cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
  2810. QualType type = method->getThisType(C);
  2811. fields.push_back(createFieldType("this", type, 0, loc, AS_public,
  2812. offsetInBits, tunit, tunit));
  2813. continue;
  2814. }
  2815. const VarDecl *variable = capture->getVariable();
  2816. StringRef name = variable->getName();
  2817. llvm::DIType *fieldType;
  2818. if (capture->isByRef()) {
  2819. TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
  2820. // FIXME: this creates a second copy of this type!
  2821. uint64_t xoffset;
  2822. fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
  2823. fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
  2824. fieldType =
  2825. DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
  2826. PtrInfo.Align, offsetInBits, 0, fieldType);
  2827. } else {
  2828. fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
  2829. offsetInBits, tunit, tunit);
  2830. }
  2831. fields.push_back(fieldType);
  2832. }
  2833. SmallString<36> typeName;
  2834. llvm::raw_svector_ostream(typeName) << "__block_literal_"
  2835. << CGM.getUniqueBlockCount();
  2836. llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
  2837. llvm::DIType *type = DBuilder.createStructType(
  2838. tunit, typeName.str(), tunit, line,
  2839. CGM.getContext().toBits(block.BlockSize),
  2840. CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
  2841. type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
  2842. // Get overall information about the block.
  2843. unsigned flags = llvm::DINode::FlagArtificial;
  2844. auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
  2845. // Create the descriptor for the parameter.
  2846. auto *debugVar = DBuilder.createParameterVariable(
  2847. scope, Arg->getName(), ArgNo, tunit, line, type,
  2848. CGM.getLangOpts().Optimize, flags);
  2849. if (LocalAddr) {
  2850. // Insert an llvm.dbg.value into the current block.
  2851. DBuilder.insertDbgValueIntrinsic(
  2852. LocalAddr, 0, debugVar, DBuilder.createExpression(),
  2853. llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
  2854. }
  2855. // Insert an llvm.dbg.declare into the current block.
  2856. DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
  2857. llvm::DebugLoc::get(line, column, scope),
  2858. Builder.GetInsertBlock());
  2859. }
  2860. llvm::DIDerivedType *
  2861. CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
  2862. if (!D->isStaticDataMember())
  2863. return nullptr;
  2864. auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
  2865. if (MI != StaticDataMemberCache.end()) {
  2866. assert(MI->second && "Static data member declaration should still exist");
  2867. return MI->second;
  2868. }
  2869. // If the member wasn't found in the cache, lazily construct and add it to the
  2870. // type (used when a limited form of the type is emitted).
  2871. auto DC = D->getDeclContext();
  2872. auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
  2873. return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
  2874. }
  2875. llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
  2876. const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
  2877. StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
  2878. llvm::DIGlobalVariable *GV = nullptr;
  2879. for (const auto *Field : RD->fields()) {
  2880. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2881. StringRef FieldName = Field->getName();
  2882. // Ignore unnamed fields, but recurse into anonymous records.
  2883. if (FieldName.empty()) {
  2884. const RecordType *RT = dyn_cast<RecordType>(Field->getType());
  2885. if (RT)
  2886. GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
  2887. Var, DContext);
  2888. continue;
  2889. }
  2890. // Use VarDecl's Tag, Scope and Line number.
  2891. GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
  2892. LineNo, FieldTy,
  2893. Var->hasInternalLinkage(), Var, nullptr);
  2894. }
  2895. return GV;
  2896. }
  2897. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  2898. const VarDecl *D) {
  2899. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2900. // Create global variable debug descriptor.
  2901. llvm::DIFile *Unit = nullptr;
  2902. llvm::DIScope *DContext = nullptr;
  2903. unsigned LineNo;
  2904. StringRef DeclName, LinkageName;
  2905. QualType T;
  2906. collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
  2907. // Attempt to store one global variable for the declaration - even if we
  2908. // emit a lot of fields.
  2909. llvm::DIGlobalVariable *GV = nullptr;
  2910. // If this is an anonymous union then we'll want to emit a global
  2911. // variable for each member of the anonymous union so that it's possible
  2912. // to find the name of any field in the union.
  2913. if (T->isUnionType() && DeclName.empty()) {
  2914. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  2915. assert(RD->isAnonymousStructOrUnion() &&
  2916. "unnamed non-anonymous struct or union?");
  2917. GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
  2918. } else {
  2919. GV = DBuilder.createGlobalVariable(
  2920. DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
  2921. Var->hasInternalLinkage(), Var,
  2922. getOrCreateStaticDataMemberDeclarationOrNull(D));
  2923. }
  2924. DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
  2925. }
  2926. void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
  2927. llvm::Constant *Init) {
  2928. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2929. // Create the descriptor for the variable.
  2930. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2931. StringRef Name = VD->getName();
  2932. llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
  2933. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
  2934. const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
  2935. assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
  2936. Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
  2937. }
  2938. // Do not use global variables for enums.
  2939. //
  2940. // FIXME: why not?
  2941. if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
  2942. return;
  2943. // Do not emit separate definitions for function local const/statics.
  2944. if (isa<FunctionDecl>(VD->getDeclContext()))
  2945. return;
  2946. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  2947. auto *VarD = cast<VarDecl>(VD);
  2948. if (VarD->isStaticDataMember()) {
  2949. auto *RD = cast<RecordDecl>(VarD->getDeclContext());
  2950. getDeclContextDescriptor(VarD);
  2951. // Ensure that the type is retained even though it's otherwise unreferenced.
  2952. RetainedTypes.push_back(
  2953. CGM.getContext().getRecordType(RD).getAsOpaquePtr());
  2954. return;
  2955. }
  2956. llvm::DIScope *DContext = getDeclContextDescriptor(VD);
  2957. auto &GV = DeclCache[VD];
  2958. if (GV)
  2959. return;
  2960. GV.reset(DBuilder.createGlobalVariable(
  2961. DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
  2962. true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
  2963. }
  2964. llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
  2965. if (!LexicalBlockStack.empty())
  2966. return LexicalBlockStack.back();
  2967. llvm::DIScope *Mod = getParentModuleOrNull(D);
  2968. return getContextDescriptor(D, Mod ? Mod : TheCU);
  2969. }
  2970. void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
  2971. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2972. return;
  2973. const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
  2974. if (!NSDecl->isAnonymousNamespace() ||
  2975. CGM.getCodeGenOpts().DebugExplicitImport) {
  2976. DBuilder.createImportedModule(
  2977. getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
  2978. getOrCreateNameSpace(NSDecl),
  2979. getLineNumber(UD.getLocation()));
  2980. }
  2981. }
  2982. void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
  2983. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2984. return;
  2985. assert(UD.shadow_size() &&
  2986. "We shouldn't be codegening an invalid UsingDecl containing no decls");
  2987. // Emitting one decl is sufficient - debuggers can detect that this is an
  2988. // overloaded name & provide lookup for all the overloads.
  2989. const UsingShadowDecl &USD = **UD.shadow_begin();
  2990. if (llvm::DINode *Target =
  2991. getDeclarationOrDefinition(USD.getUnderlyingDecl()))
  2992. DBuilder.createImportedDeclaration(
  2993. getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
  2994. getLineNumber(USD.getLocation()));
  2995. }
  2996. void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
  2997. if (Module *M = ID.getImportedModule()) {
  2998. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  2999. DBuilder.createImportedDeclaration(
  3000. getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
  3001. getOrCreateModuleRef(Info, DebugTypeExtRefs),
  3002. getLineNumber(ID.getLocation()));
  3003. }
  3004. }
  3005. llvm::DIImportedEntity *
  3006. CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
  3007. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  3008. return nullptr;
  3009. auto &VH = NamespaceAliasCache[&NA];
  3010. if (VH)
  3011. return cast<llvm::DIImportedEntity>(VH);
  3012. llvm::DIImportedEntity *R;
  3013. if (const NamespaceAliasDecl *Underlying =
  3014. dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
  3015. // This could cache & dedup here rather than relying on metadata deduping.
  3016. R = DBuilder.createImportedDeclaration(
  3017. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  3018. EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
  3019. NA.getName());
  3020. else
  3021. R = DBuilder.createImportedDeclaration(
  3022. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  3023. getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
  3024. getLineNumber(NA.getLocation()), NA.getName());
  3025. VH.reset(R);
  3026. return R;
  3027. }
  3028. llvm::DINamespace *
  3029. CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
  3030. NSDecl = NSDecl->getCanonicalDecl();
  3031. auto I = NameSpaceCache.find(NSDecl);
  3032. if (I != NameSpaceCache.end())
  3033. return cast<llvm::DINamespace>(I->second);
  3034. unsigned LineNo = getLineNumber(NSDecl->getLocation());
  3035. llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
  3036. llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
  3037. llvm::DINamespace *NS =
  3038. DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
  3039. NameSpaceCache[NSDecl].reset(NS);
  3040. return NS;
  3041. }
  3042. void CGDebugInfo::setDwoId(uint64_t Signature) {
  3043. assert(TheCU && "no main compile unit");
  3044. TheCU->setDWOId(Signature);
  3045. }
  3046. void CGDebugInfo::finalize() {
  3047. // Creating types might create further types - invalidating the current
  3048. // element and the size(), so don't cache/reference them.
  3049. for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
  3050. ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
  3051. llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
  3052. ? CreateTypeDefinition(E.Type, E.Unit)
  3053. : E.Decl;
  3054. DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
  3055. }
  3056. for (auto p : ReplaceMap) {
  3057. assert(p.second);
  3058. auto *Ty = cast<llvm::DIType>(p.second);
  3059. assert(Ty->isForwardDecl());
  3060. auto it = TypeCache.find(p.first);
  3061. assert(it != TypeCache.end());
  3062. assert(it->second);
  3063. DBuilder.replaceTemporary(llvm::TempDIType(Ty),
  3064. cast<llvm::DIType>(it->second));
  3065. }
  3066. for (const auto &p : FwdDeclReplaceMap) {
  3067. assert(p.second);
  3068. llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
  3069. llvm::Metadata *Repl;
  3070. auto it = DeclCache.find(p.first);
  3071. // If there has been no definition for the declaration, call RAUW
  3072. // with ourselves, that will destroy the temporary MDNode and
  3073. // replace it with a standard one, avoiding leaking memory.
  3074. if (it == DeclCache.end())
  3075. Repl = p.second;
  3076. else
  3077. Repl = it->second;
  3078. DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
  3079. }
  3080. // We keep our own list of retained types, because we need to look
  3081. // up the final type in the type cache.
  3082. for (auto &RT : RetainedTypes)
  3083. if (auto MD = TypeCache[RT])
  3084. DBuilder.retainType(cast<llvm::DIType>(MD));
  3085. DBuilder.finalize();
  3086. }
  3087. void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
  3088. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  3089. return;
  3090. if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
  3091. // Don't ignore in case of explicit cast where it is referenced indirectly.
  3092. DBuilder.retainType(DieTy);
  3093. }