CGDebugInfo.cpp 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569
  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. (RD->isExternallyVisible() || !RD->getName().empty()))
  1352. return true;
  1353. if (DebugKind > CodeGenOptions::LimitedDebugInfo)
  1354. return false;
  1355. if (!LangOpts.CPlusPlus)
  1356. return false;
  1357. if (!RD->isCompleteDefinitionRequired())
  1358. return true;
  1359. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1360. if (!CXXDecl)
  1361. return false;
  1362. if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
  1363. return true;
  1364. TemplateSpecializationKind Spec = TSK_Undeclared;
  1365. if (const ClassTemplateSpecializationDecl *SD =
  1366. dyn_cast<ClassTemplateSpecializationDecl>(RD))
  1367. Spec = SD->getSpecializationKind();
  1368. if (Spec == TSK_ExplicitInstantiationDeclaration &&
  1369. hasExplicitMemberDefinition(CXXDecl->method_begin(),
  1370. CXXDecl->method_end()))
  1371. return true;
  1372. return false;
  1373. }
  1374. llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
  1375. RecordDecl *RD = Ty->getDecl();
  1376. llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
  1377. if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
  1378. CGM.getLangOpts())) {
  1379. if (!T)
  1380. T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
  1381. return T;
  1382. }
  1383. return CreateTypeDefinition(Ty);
  1384. }
  1385. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
  1386. RecordDecl *RD = Ty->getDecl();
  1387. // Get overall information about the record type for the debug info.
  1388. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  1389. // Records and classes and unions can all be recursive. To handle them, we
  1390. // first generate a debug descriptor for the struct as a forward declaration.
  1391. // Then (if it is a definition) we go through and get debug info for all of
  1392. // its members. Finally, we create a descriptor for the complete type (which
  1393. // may refer to the forward decl if the struct is recursive) and replace all
  1394. // uses of the forward declaration with the final definition.
  1395. llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
  1396. const RecordDecl *D = RD->getDefinition();
  1397. if (!D || !D->isCompleteDefinition())
  1398. return FwdDecl;
  1399. if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
  1400. CollectContainingType(CXXDecl, FwdDecl);
  1401. // Push the struct on region stack.
  1402. LexicalBlockStack.emplace_back(&*FwdDecl);
  1403. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1404. // Convert all the elements.
  1405. SmallVector<llvm::Metadata *, 16> EltTys;
  1406. // what about nested types?
  1407. // Note: The split of CXXDecl information here is intentional, the
  1408. // gdb tests will depend on a certain ordering at printout. The debug
  1409. // information offsets are still correct if we merge them all together
  1410. // though.
  1411. const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
  1412. if (CXXDecl) {
  1413. CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
  1414. CollectVTableInfo(CXXDecl, DefUnit, EltTys);
  1415. }
  1416. // Collect data fields (including static variables and any initializers).
  1417. CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
  1418. if (CXXDecl)
  1419. CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
  1420. LexicalBlockStack.pop_back();
  1421. RegionMap.erase(Ty->getDecl());
  1422. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1423. DBuilder.replaceArrays(FwdDecl, Elements);
  1424. if (FwdDecl->isTemporary())
  1425. FwdDecl =
  1426. llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
  1427. RegionMap[Ty->getDecl()].reset(FwdDecl);
  1428. return FwdDecl;
  1429. }
  1430. llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
  1431. llvm::DIFile *Unit) {
  1432. // Ignore protocols.
  1433. return getOrCreateType(Ty->getBaseType(), Unit);
  1434. }
  1435. /// \return true if Getter has the default name for the property PD.
  1436. static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
  1437. const ObjCMethodDecl *Getter) {
  1438. assert(PD);
  1439. if (!Getter)
  1440. return true;
  1441. assert(Getter->getDeclName().isObjCZeroArgSelector());
  1442. return PD->getName() ==
  1443. Getter->getDeclName().getObjCSelector().getNameForSlot(0);
  1444. }
  1445. /// \return true if Setter has the default name for the property PD.
  1446. static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
  1447. const ObjCMethodDecl *Setter) {
  1448. assert(PD);
  1449. if (!Setter)
  1450. return true;
  1451. assert(Setter->getDeclName().isObjCOneArgSelector());
  1452. return SelectorTable::constructSetterName(PD->getName()) ==
  1453. Setter->getDeclName().getObjCSelector().getNameForSlot(0);
  1454. }
  1455. llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
  1456. llvm::DIFile *Unit) {
  1457. ObjCInterfaceDecl *ID = Ty->getDecl();
  1458. if (!ID)
  1459. return nullptr;
  1460. // Return a forward declaration if this type was imported from a clang module.
  1461. if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition())
  1462. return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
  1463. ID->getName(),
  1464. getDeclContextDescriptor(ID), Unit, 0);
  1465. // Get overall information about the record type for the debug info.
  1466. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1467. unsigned Line = getLineNumber(ID->getLocation());
  1468. auto RuntimeLang =
  1469. static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
  1470. // If this is just a forward declaration return a special forward-declaration
  1471. // debug type since we won't be able to lay out the entire type.
  1472. ObjCInterfaceDecl *Def = ID->getDefinition();
  1473. if (!Def || !Def->getImplementation()) {
  1474. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  1475. llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
  1476. llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
  1477. DefUnit, Line, RuntimeLang);
  1478. ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
  1479. return FwdDecl;
  1480. }
  1481. return CreateTypeDefinition(Ty, Unit);
  1482. }
  1483. llvm::DIModule *
  1484. CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
  1485. bool CreateSkeletonCU) {
  1486. // Use the Module pointer as the key into the cache. This is a
  1487. // nullptr if the "Module" is a PCH, which is safe because we don't
  1488. // support chained PCH debug info, so there can only be a single PCH.
  1489. const Module *M = Mod.getModuleOrNull();
  1490. auto ModRef = ModuleCache.find(M);
  1491. if (ModRef != ModuleCache.end())
  1492. return cast<llvm::DIModule>(ModRef->second);
  1493. // Macro definitions that were defined with "-D" on the command line.
  1494. SmallString<128> ConfigMacros;
  1495. {
  1496. llvm::raw_svector_ostream OS(ConfigMacros);
  1497. const auto &PPOpts = CGM.getPreprocessorOpts();
  1498. unsigned I = 0;
  1499. // Translate the macro definitions back into a commmand line.
  1500. for (auto &M : PPOpts.Macros) {
  1501. if (++I > 1)
  1502. OS << " ";
  1503. const std::string &Macro = M.first;
  1504. bool Undef = M.second;
  1505. OS << "\"-" << (Undef ? 'U' : 'D');
  1506. for (char c : Macro)
  1507. switch (c) {
  1508. case '\\' : OS << "\\\\"; break;
  1509. case '"' : OS << "\\\""; break;
  1510. default: OS << c;
  1511. }
  1512. OS << '\"';
  1513. }
  1514. }
  1515. bool IsRootModule = M ? !M->Parent : true;
  1516. if (CreateSkeletonCU && IsRootModule) {
  1517. // PCH files don't have a signature field in the control block,
  1518. // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
  1519. uint64_t Signature = Mod.getSignature() ? Mod.getSignature() : ~1ULL;
  1520. llvm::DIBuilder DIB(CGM.getModule());
  1521. DIB.createCompileUnit(TheCU->getSourceLanguage(), Mod.getModuleName(),
  1522. Mod.getPath(), TheCU->getProducer(), true,
  1523. StringRef(), 0, Mod.getASTFile(),
  1524. llvm::DIBuilder::FullDebug, Signature);
  1525. DIB.finalize();
  1526. }
  1527. llvm::DIModule *Parent =
  1528. IsRootModule ? nullptr
  1529. : getOrCreateModuleRef(
  1530. ExternalASTSource::ASTSourceDescriptor(*M->Parent),
  1531. CreateSkeletonCU);
  1532. llvm::DIModule *DIMod =
  1533. DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
  1534. Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
  1535. ModuleCache[M].reset(DIMod);
  1536. return DIMod;
  1537. }
  1538. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
  1539. llvm::DIFile *Unit) {
  1540. ObjCInterfaceDecl *ID = Ty->getDecl();
  1541. llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
  1542. unsigned Line = getLineNumber(ID->getLocation());
  1543. unsigned RuntimeLang = TheCU->getSourceLanguage();
  1544. // Bit size, align and offset of the type.
  1545. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1546. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1547. unsigned Flags = 0;
  1548. if (ID->getImplementation())
  1549. Flags |= llvm::DINode::FlagObjcClassComplete;
  1550. llvm::DIScope *Mod = getParentModuleOrNull(ID);
  1551. llvm::DICompositeType *RealDecl = DBuilder.createStructType(
  1552. Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
  1553. nullptr, llvm::DINodeArray(), RuntimeLang);
  1554. QualType QTy(Ty, 0);
  1555. TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
  1556. // Push the struct on region stack.
  1557. LexicalBlockStack.emplace_back(RealDecl);
  1558. RegionMap[Ty->getDecl()].reset(RealDecl);
  1559. // Convert all the elements.
  1560. SmallVector<llvm::Metadata *, 16> EltTys;
  1561. ObjCInterfaceDecl *SClass = ID->getSuperClass();
  1562. if (SClass) {
  1563. llvm::DIType *SClassTy =
  1564. getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
  1565. if (!SClassTy)
  1566. return nullptr;
  1567. llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
  1568. EltTys.push_back(InhTag);
  1569. }
  1570. // Create entries for all of the properties.
  1571. auto AddProperty = [&](const ObjCPropertyDecl *PD) {
  1572. SourceLocation Loc = PD->getLocation();
  1573. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1574. unsigned PLine = getLineNumber(Loc);
  1575. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1576. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1577. llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
  1578. PD->getName(), PUnit, PLine,
  1579. hasDefaultGetterName(PD, Getter) ? ""
  1580. : getSelectorName(PD->getGetterName()),
  1581. hasDefaultSetterName(PD, Setter) ? ""
  1582. : getSelectorName(PD->getSetterName()),
  1583. PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
  1584. EltTys.push_back(PropertyNode);
  1585. };
  1586. {
  1587. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  1588. for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
  1589. for (auto *PD : ClassExt->properties()) {
  1590. PropertySet.insert(PD->getIdentifier());
  1591. AddProperty(PD);
  1592. }
  1593. for (const auto *PD : ID->properties()) {
  1594. // Don't emit duplicate metadata for properties that were already in a
  1595. // class extension.
  1596. if (!PropertySet.insert(PD->getIdentifier()).second)
  1597. continue;
  1598. AddProperty(PD);
  1599. }
  1600. }
  1601. const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
  1602. unsigned FieldNo = 0;
  1603. for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
  1604. Field = Field->getNextIvar(), ++FieldNo) {
  1605. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  1606. if (!FieldTy)
  1607. return nullptr;
  1608. StringRef FieldName = Field->getName();
  1609. // Ignore unnamed fields.
  1610. if (FieldName.empty())
  1611. continue;
  1612. // Get the location for the field.
  1613. llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
  1614. unsigned FieldLine = getLineNumber(Field->getLocation());
  1615. QualType FType = Field->getType();
  1616. uint64_t FieldSize = 0;
  1617. unsigned FieldAlign = 0;
  1618. if (!FType->isIncompleteArrayType()) {
  1619. // Bit size, align and offset of the type.
  1620. FieldSize = Field->isBitField()
  1621. ? Field->getBitWidthValue(CGM.getContext())
  1622. : CGM.getContext().getTypeSize(FType);
  1623. FieldAlign = CGM.getContext().getTypeAlign(FType);
  1624. }
  1625. uint64_t FieldOffset;
  1626. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  1627. // We don't know the runtime offset of an ivar if we're using the
  1628. // non-fragile ABI. For bitfields, use the bit offset into the first
  1629. // byte of storage of the bitfield. For other fields, use zero.
  1630. if (Field->isBitField()) {
  1631. FieldOffset =
  1632. CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
  1633. FieldOffset %= CGM.getContext().getCharWidth();
  1634. } else {
  1635. FieldOffset = 0;
  1636. }
  1637. } else {
  1638. FieldOffset = RL.getFieldOffset(FieldNo);
  1639. }
  1640. unsigned Flags = 0;
  1641. if (Field->getAccessControl() == ObjCIvarDecl::Protected)
  1642. Flags = llvm::DINode::FlagProtected;
  1643. else if (Field->getAccessControl() == ObjCIvarDecl::Private)
  1644. Flags = llvm::DINode::FlagPrivate;
  1645. else if (Field->getAccessControl() == ObjCIvarDecl::Public)
  1646. Flags = llvm::DINode::FlagPublic;
  1647. llvm::MDNode *PropertyNode = nullptr;
  1648. if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
  1649. if (ObjCPropertyImplDecl *PImpD =
  1650. ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
  1651. if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
  1652. SourceLocation Loc = PD->getLocation();
  1653. llvm::DIFile *PUnit = getOrCreateFile(Loc);
  1654. unsigned PLine = getLineNumber(Loc);
  1655. ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
  1656. ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
  1657. PropertyNode = DBuilder.createObjCProperty(
  1658. PD->getName(), PUnit, PLine,
  1659. hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
  1660. PD->getGetterName()),
  1661. hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
  1662. PD->getSetterName()),
  1663. PD->getPropertyAttributes(),
  1664. getOrCreateType(PD->getType(), PUnit));
  1665. }
  1666. }
  1667. }
  1668. FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
  1669. FieldSize, FieldAlign, FieldOffset, Flags,
  1670. FieldTy, PropertyNode);
  1671. EltTys.push_back(FieldTy);
  1672. }
  1673. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  1674. DBuilder.replaceArrays(RealDecl, Elements);
  1675. LexicalBlockStack.pop_back();
  1676. return RealDecl;
  1677. }
  1678. llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
  1679. llvm::DIFile *Unit) {
  1680. llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
  1681. int64_t Count = Ty->getNumElements();
  1682. if (Count == 0)
  1683. // If number of elements are not known then this is an unbounded array.
  1684. // Use Count == -1 to express such arrays.
  1685. Count = -1;
  1686. llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
  1687. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
  1688. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  1689. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  1690. return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
  1691. }
  1692. llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
  1693. uint64_t Size;
  1694. uint64_t Align;
  1695. // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
  1696. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
  1697. Size = 0;
  1698. Align =
  1699. CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
  1700. } else if (Ty->isIncompleteArrayType()) {
  1701. Size = 0;
  1702. if (Ty->getElementType()->isIncompleteType())
  1703. Align = 0;
  1704. else
  1705. Align = CGM.getContext().getTypeAlign(Ty->getElementType());
  1706. } else if (Ty->isIncompleteType()) {
  1707. Size = 0;
  1708. Align = 0;
  1709. } else {
  1710. // Size and align of the whole array, not the element type.
  1711. Size = CGM.getContext().getTypeSize(Ty);
  1712. Align = CGM.getContext().getTypeAlign(Ty);
  1713. }
  1714. // Add the dimensions of the array. FIXME: This loses CV qualifiers from
  1715. // interior arrays, do we care? Why aren't nested arrays represented the
  1716. // obvious/recursive way?
  1717. SmallVector<llvm::Metadata *, 8> Subscripts;
  1718. QualType EltTy(Ty, 0);
  1719. while ((Ty = dyn_cast<ArrayType>(EltTy))) {
  1720. // If the number of elements is known, then count is that number. Otherwise,
  1721. // it's -1. This allows us to represent a subrange with an array of 0
  1722. // elements, like this:
  1723. //
  1724. // struct foo {
  1725. // int x[0];
  1726. // };
  1727. int64_t Count = -1; // Count == -1 is an unbounded array.
  1728. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
  1729. Count = CAT->getSize().getZExtValue();
  1730. // FIXME: Verify this is right for VLAs.
  1731. Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
  1732. EltTy = Ty->getElementType();
  1733. }
  1734. llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
  1735. return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
  1736. SubscriptArray);
  1737. }
  1738. llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
  1739. llvm::DIFile *Unit) {
  1740. return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
  1741. Ty->getPointeeType(), Unit);
  1742. }
  1743. llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
  1744. llvm::DIFile *Unit) {
  1745. return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
  1746. Ty->getPointeeType(), Unit);
  1747. }
  1748. llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
  1749. llvm::DIFile *U) {
  1750. uint64_t Size =
  1751. !Ty->isIncompleteType() ? CGM.getContext().getTypeSize(Ty) : 0;
  1752. llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
  1753. if (Ty->isMemberDataPointerType())
  1754. return DBuilder.createMemberPointerType(
  1755. getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
  1756. const FunctionProtoType *FPT =
  1757. Ty->getPointeeType()->getAs<FunctionProtoType>();
  1758. return DBuilder.createMemberPointerType(
  1759. getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
  1760. Ty->getClass(), FPT->getTypeQuals())),
  1761. FPT, U),
  1762. ClassType, Size);
  1763. }
  1764. llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
  1765. // Ignore the atomic wrapping
  1766. // FIXME: What is the correct representation?
  1767. return getOrCreateType(Ty->getValueType(), U);
  1768. }
  1769. llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
  1770. llvm::DIFile *U) {
  1771. return getOrCreateType(Ty->getElementType(), U);
  1772. }
  1773. llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
  1774. const EnumDecl *ED = Ty->getDecl();
  1775. uint64_t Size = 0;
  1776. uint64_t Align = 0;
  1777. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1778. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1779. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1780. }
  1781. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1782. bool isImportedFromModule =
  1783. DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
  1784. // If this is just a forward declaration, construct an appropriately
  1785. // marked node and just return it.
  1786. if (isImportedFromModule || !ED->getDefinition()) {
  1787. llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
  1788. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  1789. unsigned Line = getLineNumber(ED->getLocation());
  1790. StringRef EDName = ED->getName();
  1791. llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
  1792. llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
  1793. 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
  1794. ReplaceMap.emplace_back(
  1795. std::piecewise_construct, std::make_tuple(Ty),
  1796. std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
  1797. return RetTy;
  1798. }
  1799. return CreateTypeDefinition(Ty);
  1800. }
  1801. llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
  1802. const EnumDecl *ED = Ty->getDecl();
  1803. uint64_t Size = 0;
  1804. uint64_t Align = 0;
  1805. if (!ED->getTypeForDecl()->isIncompleteType()) {
  1806. Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
  1807. Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
  1808. }
  1809. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  1810. // Create elements for each enumerator.
  1811. SmallVector<llvm::Metadata *, 16> Enumerators;
  1812. ED = ED->getDefinition();
  1813. for (const auto *Enum : ED->enumerators()) {
  1814. Enumerators.push_back(DBuilder.createEnumerator(
  1815. Enum->getName(), Enum->getInitVal().getSExtValue()));
  1816. }
  1817. // Return a CompositeType for the enum itself.
  1818. llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
  1819. llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
  1820. unsigned Line = getLineNumber(ED->getLocation());
  1821. llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
  1822. llvm::DIType *ClassTy =
  1823. ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
  1824. return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
  1825. Line, Size, Align, EltArray, ClassTy,
  1826. FullName);
  1827. }
  1828. static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
  1829. Qualifiers Quals;
  1830. do {
  1831. Qualifiers InnerQuals = T.getLocalQualifiers();
  1832. // Qualifiers::operator+() doesn't like it if you add a Qualifier
  1833. // that is already there.
  1834. Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
  1835. Quals += InnerQuals;
  1836. QualType LastT = T;
  1837. switch (T->getTypeClass()) {
  1838. default:
  1839. return C.getQualifiedType(T.getTypePtr(), Quals);
  1840. case Type::TemplateSpecialization: {
  1841. const auto *Spec = cast<TemplateSpecializationType>(T);
  1842. if (Spec->isTypeAlias())
  1843. return C.getQualifiedType(T.getTypePtr(), Quals);
  1844. T = Spec->desugar();
  1845. break;
  1846. }
  1847. case Type::TypeOfExpr:
  1848. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  1849. break;
  1850. case Type::TypeOf:
  1851. T = cast<TypeOfType>(T)->getUnderlyingType();
  1852. break;
  1853. case Type::Decltype:
  1854. T = cast<DecltypeType>(T)->getUnderlyingType();
  1855. break;
  1856. case Type::UnaryTransform:
  1857. T = cast<UnaryTransformType>(T)->getUnderlyingType();
  1858. break;
  1859. case Type::Attributed:
  1860. T = cast<AttributedType>(T)->getEquivalentType();
  1861. break;
  1862. case Type::Elaborated:
  1863. T = cast<ElaboratedType>(T)->getNamedType();
  1864. break;
  1865. case Type::Paren:
  1866. T = cast<ParenType>(T)->getInnerType();
  1867. break;
  1868. case Type::SubstTemplateTypeParm:
  1869. T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
  1870. break;
  1871. case Type::Auto:
  1872. QualType DT = cast<AutoType>(T)->getDeducedType();
  1873. assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
  1874. T = DT;
  1875. break;
  1876. }
  1877. assert(T != LastT && "Type unwrapping failed to unwrap!");
  1878. (void)LastT;
  1879. } while (true);
  1880. }
  1881. llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
  1882. // Unwrap the type as needed for debug information.
  1883. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  1884. auto it = TypeCache.find(Ty.getAsOpaquePtr());
  1885. if (it != TypeCache.end()) {
  1886. // Verify that the debug info still exists.
  1887. if (llvm::Metadata *V = it->second)
  1888. return cast<llvm::DIType>(V);
  1889. }
  1890. return nullptr;
  1891. }
  1892. void CGDebugInfo::completeTemplateDefinition(
  1893. const ClassTemplateSpecializationDecl &SD) {
  1894. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  1895. return;
  1896. completeClassData(&SD);
  1897. // In case this type has no member function definitions being emitted, ensure
  1898. // it is retained
  1899. RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
  1900. }
  1901. llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
  1902. if (Ty.isNull())
  1903. return nullptr;
  1904. // Unwrap the type as needed for debug information.
  1905. Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
  1906. if (auto *T = getTypeOrNull(Ty))
  1907. return T;
  1908. llvm::DIType *Res = CreateTypeNode(Ty, Unit);
  1909. void* TyPtr = Ty.getAsOpaquePtr();
  1910. // And update the type cache.
  1911. TypeCache[TyPtr].reset(Res);
  1912. return Res;
  1913. }
  1914. llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
  1915. // A forward declaration inside a module header does not belong to the module.
  1916. if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
  1917. return nullptr;
  1918. if (DebugTypeExtRefs && D->isFromASTFile()) {
  1919. // Record a reference to an imported clang module or precompiled header.
  1920. auto *Reader = CGM.getContext().getExternalSource();
  1921. auto Idx = D->getOwningModuleID();
  1922. auto Info = Reader->getSourceDescriptor(Idx);
  1923. if (Info)
  1924. return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
  1925. } else if (ClangModuleMap) {
  1926. // We are building a clang module or a precompiled header.
  1927. //
  1928. // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
  1929. // and it wouldn't be necessary to specify the parent scope
  1930. // because the type is already unique by definition (it would look
  1931. // like the output of -fno-standalone-debug). On the other hand,
  1932. // the parent scope helps a consumer to quickly locate the object
  1933. // file where the type's definition is located, so it might be
  1934. // best to make this behavior a command line or debugger tuning
  1935. // option.
  1936. FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
  1937. if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) {
  1938. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  1939. return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
  1940. }
  1941. }
  1942. return nullptr;
  1943. }
  1944. llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
  1945. // Handle qualifiers, which recursively handles what they refer to.
  1946. if (Ty.hasLocalQualifiers())
  1947. return CreateQualifiedType(Ty, Unit);
  1948. // Work out details of type.
  1949. switch (Ty->getTypeClass()) {
  1950. #define TYPE(Class, Base)
  1951. #define ABSTRACT_TYPE(Class, Base)
  1952. #define NON_CANONICAL_TYPE(Class, Base)
  1953. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1954. #include "clang/AST/TypeNodes.def"
  1955. llvm_unreachable("Dependent types cannot show up in debug information");
  1956. case Type::ExtVector:
  1957. case Type::Vector:
  1958. return CreateType(cast<VectorType>(Ty), Unit);
  1959. case Type::ObjCObjectPointer:
  1960. return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
  1961. case Type::ObjCObject:
  1962. return CreateType(cast<ObjCObjectType>(Ty), Unit);
  1963. case Type::ObjCInterface:
  1964. return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
  1965. case Type::Builtin:
  1966. return CreateType(cast<BuiltinType>(Ty));
  1967. case Type::Complex:
  1968. return CreateType(cast<ComplexType>(Ty));
  1969. case Type::Pointer:
  1970. return CreateType(cast<PointerType>(Ty), Unit);
  1971. case Type::Adjusted:
  1972. case Type::Decayed:
  1973. // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
  1974. return CreateType(
  1975. cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
  1976. case Type::BlockPointer:
  1977. return CreateType(cast<BlockPointerType>(Ty), Unit);
  1978. case Type::Typedef:
  1979. return CreateType(cast<TypedefType>(Ty), Unit);
  1980. case Type::Record:
  1981. return CreateType(cast<RecordType>(Ty));
  1982. case Type::Enum:
  1983. return CreateEnumType(cast<EnumType>(Ty));
  1984. case Type::FunctionProto:
  1985. case Type::FunctionNoProto:
  1986. return CreateType(cast<FunctionType>(Ty), Unit);
  1987. case Type::ConstantArray:
  1988. case Type::VariableArray:
  1989. case Type::IncompleteArray:
  1990. return CreateType(cast<ArrayType>(Ty), Unit);
  1991. case Type::LValueReference:
  1992. return CreateType(cast<LValueReferenceType>(Ty), Unit);
  1993. case Type::RValueReference:
  1994. return CreateType(cast<RValueReferenceType>(Ty), Unit);
  1995. case Type::MemberPointer:
  1996. return CreateType(cast<MemberPointerType>(Ty), Unit);
  1997. case Type::Atomic:
  1998. return CreateType(cast<AtomicType>(Ty), Unit);
  1999. case Type::Pipe:
  2000. return CreateType(cast<PipeType>(Ty), Unit);
  2001. case Type::TemplateSpecialization:
  2002. return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
  2003. case Type::Auto:
  2004. case Type::Attributed:
  2005. case Type::Elaborated:
  2006. case Type::Paren:
  2007. case Type::SubstTemplateTypeParm:
  2008. case Type::TypeOfExpr:
  2009. case Type::TypeOf:
  2010. case Type::Decltype:
  2011. case Type::UnaryTransform:
  2012. case Type::PackExpansion:
  2013. break;
  2014. }
  2015. llvm_unreachable("type should have been unwrapped!");
  2016. }
  2017. llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
  2018. llvm::DIFile *Unit) {
  2019. QualType QTy(Ty, 0);
  2020. auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
  2021. // We may have cached a forward decl when we could have created
  2022. // a non-forward decl. Go ahead and create a non-forward decl
  2023. // now.
  2024. if (T && !T->isForwardDecl())
  2025. return T;
  2026. // Otherwise create the type.
  2027. llvm::DICompositeType *Res = CreateLimitedType(Ty);
  2028. // Propagate members from the declaration to the definition
  2029. // CreateType(const RecordType*) will overwrite this with the members in the
  2030. // correct order if the full type is needed.
  2031. DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
  2032. // And update the type cache.
  2033. TypeCache[QTy.getAsOpaquePtr()].reset(Res);
  2034. return Res;
  2035. }
  2036. // TODO: Currently used for context chains when limiting debug info.
  2037. llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
  2038. RecordDecl *RD = Ty->getDecl();
  2039. // Get overall information about the record type for the debug info.
  2040. llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
  2041. unsigned Line = getLineNumber(RD->getLocation());
  2042. StringRef RDName = getClassName(RD);
  2043. llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
  2044. // If we ended up creating the type during the context chain construction,
  2045. // just return that.
  2046. auto *T = cast_or_null<llvm::DICompositeType>(
  2047. getTypeOrNull(CGM.getContext().getRecordType(RD)));
  2048. if (T && (!T->isForwardDecl() || !RD->getDefinition()))
  2049. return T;
  2050. // If this is just a forward or incomplete declaration, construct an
  2051. // appropriately marked node and just return it.
  2052. const RecordDecl *D = RD->getDefinition();
  2053. if (!D || !D->isCompleteDefinition())
  2054. return getOrCreateRecordFwdDecl(Ty, RDContext);
  2055. uint64_t Size = CGM.getContext().getTypeSize(Ty);
  2056. uint64_t Align = CGM.getContext().getTypeAlign(Ty);
  2057. SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
  2058. llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
  2059. getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
  2060. FullName);
  2061. RegionMap[Ty->getDecl()].reset(RealDecl);
  2062. TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
  2063. if (const ClassTemplateSpecializationDecl *TSpecial =
  2064. dyn_cast<ClassTemplateSpecializationDecl>(RD))
  2065. DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
  2066. CollectCXXTemplateParams(TSpecial, DefUnit));
  2067. return RealDecl;
  2068. }
  2069. void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
  2070. llvm::DICompositeType *RealDecl) {
  2071. // A class's primary base or the class itself contains the vtable.
  2072. llvm::DICompositeType *ContainingType = nullptr;
  2073. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  2074. if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
  2075. // Seek non-virtual primary base root.
  2076. while (1) {
  2077. const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
  2078. const CXXRecordDecl *PBT = BRL.getPrimaryBase();
  2079. if (PBT && !BRL.isPrimaryBaseVirtual())
  2080. PBase = PBT;
  2081. else
  2082. break;
  2083. }
  2084. ContainingType = cast<llvm::DICompositeType>(
  2085. getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
  2086. getOrCreateFile(RD->getLocation())));
  2087. } else if (RD->isDynamicClass())
  2088. ContainingType = RealDecl;
  2089. DBuilder.replaceVTableHolder(RealDecl, ContainingType);
  2090. }
  2091. llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
  2092. StringRef Name, uint64_t *Offset) {
  2093. llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
  2094. uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
  2095. unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
  2096. llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
  2097. FieldAlign, *Offset, 0, FieldTy);
  2098. *Offset += FieldSize;
  2099. return Ty;
  2100. }
  2101. void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
  2102. StringRef &Name,
  2103. StringRef &LinkageName,
  2104. llvm::DIScope *&FDContext,
  2105. llvm::DINodeArray &TParamsArray,
  2106. unsigned &Flags) {
  2107. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2108. Name = getFunctionName(FD);
  2109. // Use mangled name as linkage name for C/C++ functions.
  2110. if (FD->hasPrototype()) {
  2111. LinkageName = CGM.getMangledName(GD);
  2112. Flags |= llvm::DINode::FlagPrototyped;
  2113. }
  2114. // No need to replicate the linkage name if it isn't different from the
  2115. // subprogram name, no need to have it at all unless coverage is enabled or
  2116. // debug is set to more than just line tables.
  2117. if (LinkageName == Name ||
  2118. (!CGM.getCodeGenOpts().EmitGcovArcs &&
  2119. !CGM.getCodeGenOpts().EmitGcovNotes &&
  2120. DebugKind <= CodeGenOptions::DebugLineTablesOnly))
  2121. LinkageName = StringRef();
  2122. if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
  2123. if (const NamespaceDecl *NSDecl =
  2124. dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
  2125. FDContext = getOrCreateNameSpace(NSDecl);
  2126. else if (const RecordDecl *RDecl =
  2127. dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
  2128. llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
  2129. FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
  2130. }
  2131. // Collect template parameters.
  2132. TParamsArray = CollectFunctionTemplateParams(FD, Unit);
  2133. }
  2134. }
  2135. void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
  2136. unsigned &LineNo, QualType &T,
  2137. StringRef &Name, StringRef &LinkageName,
  2138. llvm::DIScope *&VDContext) {
  2139. Unit = getOrCreateFile(VD->getLocation());
  2140. LineNo = getLineNumber(VD->getLocation());
  2141. setLocation(VD->getLocation());
  2142. T = VD->getType();
  2143. if (T->isIncompleteArrayType()) {
  2144. // CodeGen turns int[] into int[1] so we'll do the same here.
  2145. llvm::APInt ConstVal(32, 1);
  2146. QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
  2147. T = CGM.getContext().getConstantArrayType(ET, ConstVal,
  2148. ArrayType::Normal, 0);
  2149. }
  2150. Name = VD->getName();
  2151. if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
  2152. !isa<ObjCMethodDecl>(VD->getDeclContext()))
  2153. LinkageName = CGM.getMangledName(VD);
  2154. if (LinkageName == Name)
  2155. LinkageName = StringRef();
  2156. // Since we emit declarations (DW_AT_members) for static members, place the
  2157. // definition of those static members in the namespace they were declared in
  2158. // in the source code (the lexical decl context).
  2159. // FIXME: Generalize this for even non-member global variables where the
  2160. // declaration and definition may have different lexical decl contexts, once
  2161. // we have support for emitting declarations of (non-member) global variables.
  2162. const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
  2163. : VD->getDeclContext();
  2164. // When a record type contains an in-line initialization of a static data
  2165. // member, and the record type is marked as __declspec(dllexport), an implicit
  2166. // definition of the member will be created in the record context. DWARF
  2167. // doesn't seem to have a nice way to describe this in a form that consumers
  2168. // are likely to understand, so fake the "normal" situation of a definition
  2169. // outside the class by putting it in the global scope.
  2170. if (DC->isRecord())
  2171. DC = CGM.getContext().getTranslationUnitDecl();
  2172. llvm::DIScope *Mod = getParentModuleOrNull(VD);
  2173. VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
  2174. }
  2175. llvm::DISubprogram *
  2176. CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
  2177. llvm::DINodeArray TParamsArray;
  2178. StringRef Name, LinkageName;
  2179. unsigned Flags = 0;
  2180. SourceLocation Loc = FD->getLocation();
  2181. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2182. llvm::DIScope *DContext = Unit;
  2183. unsigned Line = getLineNumber(Loc);
  2184. collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
  2185. TParamsArray, Flags);
  2186. // Build function type.
  2187. SmallVector<QualType, 16> ArgTypes;
  2188. for (const ParmVarDecl *Parm: FD->parameters())
  2189. ArgTypes.push_back(Parm->getType());
  2190. QualType FnType =
  2191. CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
  2192. FunctionProtoType::ExtProtoInfo());
  2193. llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
  2194. DContext, Name, LinkageName, Unit, Line,
  2195. getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
  2196. /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
  2197. TParamsArray.get(), getFunctionDeclaration(FD));
  2198. const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
  2199. FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
  2200. std::make_tuple(CanonDecl),
  2201. std::make_tuple(SP));
  2202. return SP;
  2203. }
  2204. llvm::DIGlobalVariable *
  2205. CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
  2206. QualType T;
  2207. StringRef Name, LinkageName;
  2208. SourceLocation Loc = VD->getLocation();
  2209. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2210. llvm::DIScope *DContext = Unit;
  2211. unsigned Line = getLineNumber(Loc);
  2212. collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
  2213. auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
  2214. DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
  2215. !VD->isExternallyVisible(), nullptr, nullptr);
  2216. FwdDeclReplaceMap.emplace_back(
  2217. std::piecewise_construct,
  2218. std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
  2219. std::make_tuple(static_cast<llvm::Metadata *>(GV)));
  2220. return GV;
  2221. }
  2222. llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
  2223. // We only need a declaration (not a definition) of the type - so use whatever
  2224. // we would otherwise do to get a type for a pointee. (forward declarations in
  2225. // limited debug info, full definitions (if the type definition is available)
  2226. // in unlimited debug info)
  2227. if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
  2228. return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
  2229. getOrCreateFile(TD->getLocation()));
  2230. auto I = DeclCache.find(D->getCanonicalDecl());
  2231. if (I != DeclCache.end())
  2232. return dyn_cast_or_null<llvm::DINode>(I->second);
  2233. // No definition for now. Emit a forward definition that might be
  2234. // merged with a potential upcoming definition.
  2235. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  2236. return getFunctionForwardDeclaration(FD);
  2237. else if (const auto *VD = dyn_cast<VarDecl>(D))
  2238. return getGlobalVariableForwardDeclaration(VD);
  2239. return nullptr;
  2240. }
  2241. llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
  2242. if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2243. return nullptr;
  2244. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  2245. if (!FD)
  2246. return nullptr;
  2247. // Setup context.
  2248. auto *S = getDeclContextDescriptor(D);
  2249. auto MI = SPCache.find(FD->getCanonicalDecl());
  2250. if (MI == SPCache.end()) {
  2251. if (const CXXMethodDecl *MD =
  2252. dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
  2253. return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
  2254. cast<llvm::DICompositeType>(S));
  2255. }
  2256. }
  2257. if (MI != SPCache.end()) {
  2258. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2259. if (SP && !SP->isDefinition())
  2260. return SP;
  2261. }
  2262. for (auto NextFD : FD->redecls()) {
  2263. auto MI = SPCache.find(NextFD->getCanonicalDecl());
  2264. if (MI != SPCache.end()) {
  2265. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
  2266. if (SP && !SP->isDefinition())
  2267. return SP;
  2268. }
  2269. }
  2270. return nullptr;
  2271. }
  2272. // getOrCreateFunctionType - Construct type. If it is a c++ method, include
  2273. // implicit parameter "this".
  2274. llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
  2275. QualType FnType,
  2276. llvm::DIFile *F) {
  2277. if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2278. // Create fake but valid subroutine type. Otherwise -verify would fail, and
  2279. // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
  2280. return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
  2281. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  2282. return getOrCreateMethodType(Method, F);
  2283. if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
  2284. // Add "self" and "_cmd"
  2285. SmallVector<llvm::Metadata *, 16> Elts;
  2286. // First element is always return type. For 'void' functions it is NULL.
  2287. QualType ResultTy = OMethod->getReturnType();
  2288. // Replace the instancetype keyword with the actual type.
  2289. if (ResultTy == CGM.getContext().getObjCInstanceType())
  2290. ResultTy = CGM.getContext().getPointerType(
  2291. QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
  2292. Elts.push_back(getOrCreateType(ResultTy, F));
  2293. // "self" pointer is always first argument.
  2294. QualType SelfDeclTy;
  2295. if (auto *SelfDecl = OMethod->getSelfDecl())
  2296. SelfDeclTy = SelfDecl->getType();
  2297. else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
  2298. if (FPT->getNumParams() > 1)
  2299. SelfDeclTy = FPT->getParamType(0);
  2300. if (!SelfDeclTy.isNull())
  2301. Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
  2302. // "_cmd" pointer is always second argument.
  2303. Elts.push_back(DBuilder.createArtificialType(
  2304. getOrCreateType(CGM.getContext().getObjCSelType(), F)));
  2305. // Get rest of the arguments.
  2306. for (const auto *PI : OMethod->params())
  2307. Elts.push_back(getOrCreateType(PI->getType(), F));
  2308. // Variadic methods need a special marker at the end of the type list.
  2309. if (OMethod->isVariadic())
  2310. Elts.push_back(DBuilder.createUnspecifiedParameter());
  2311. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
  2312. return DBuilder.createSubroutineType(EltTypeArray);
  2313. }
  2314. // Handle variadic function types; they need an additional
  2315. // unspecified parameter.
  2316. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2317. if (FD->isVariadic()) {
  2318. SmallVector<llvm::Metadata *, 16> EltTys;
  2319. EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
  2320. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
  2321. for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
  2322. EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
  2323. EltTys.push_back(DBuilder.createUnspecifiedParameter());
  2324. llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
  2325. return DBuilder.createSubroutineType(EltTypeArray);
  2326. }
  2327. return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
  2328. }
  2329. void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
  2330. SourceLocation ScopeLoc, QualType FnType,
  2331. llvm::Function *Fn, CGBuilderTy &Builder) {
  2332. StringRef Name;
  2333. StringRef LinkageName;
  2334. FnBeginRegionCount.push_back(LexicalBlockStack.size());
  2335. const Decl *D = GD.getDecl();
  2336. bool HasDecl = (D != nullptr);
  2337. unsigned Flags = 0;
  2338. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2339. llvm::DIScope *FDContext = Unit;
  2340. llvm::DINodeArray TParamsArray;
  2341. if (!HasDecl) {
  2342. // Use llvm function name.
  2343. LinkageName = Fn->getName();
  2344. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2345. // If there is a subprogram for this function available then use it.
  2346. auto FI = SPCache.find(FD->getCanonicalDecl());
  2347. if (FI != SPCache.end()) {
  2348. auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
  2349. if (SP && SP->isDefinition()) {
  2350. LexicalBlockStack.emplace_back(SP);
  2351. RegionMap[D].reset(SP);
  2352. return;
  2353. }
  2354. }
  2355. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2356. TParamsArray, Flags);
  2357. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2358. Name = getObjCMethodName(OMD);
  2359. Flags |= llvm::DINode::FlagPrototyped;
  2360. } else {
  2361. // Use llvm function name.
  2362. Name = Fn->getName();
  2363. Flags |= llvm::DINode::FlagPrototyped;
  2364. }
  2365. if (!Name.empty() && Name[0] == '\01')
  2366. Name = Name.substr(1);
  2367. if (!HasDecl || D->isImplicit()) {
  2368. Flags |= llvm::DINode::FlagArtificial;
  2369. // Artificial functions without a location should not silently reuse CurLoc.
  2370. if (Loc.isInvalid())
  2371. CurLoc = SourceLocation();
  2372. }
  2373. unsigned LineNo = getLineNumber(Loc);
  2374. unsigned ScopeLine = getLineNumber(ScopeLoc);
  2375. // FIXME: The function declaration we're constructing here is mostly reusing
  2376. // declarations from CXXMethodDecl and not constructing new ones for arbitrary
  2377. // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
  2378. // all subprograms instead of the actual context since subprogram definitions
  2379. // are emitted as CU level entities by the backend.
  2380. llvm::DISubprogram *SP = DBuilder.createFunction(
  2381. FDContext, Name, LinkageName, Unit, LineNo,
  2382. getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
  2383. true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
  2384. TParamsArray.get(), getFunctionDeclaration(D));
  2385. Fn->setSubprogram(SP);
  2386. // We might get here with a VarDecl in the case we're generating
  2387. // code for the initialization of globals. Do not record these decls
  2388. // as they will overwrite the actual VarDecl Decl in the cache.
  2389. if (HasDecl && isa<FunctionDecl>(D))
  2390. DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
  2391. // Push the function onto the lexical block stack.
  2392. LexicalBlockStack.emplace_back(SP);
  2393. if (HasDecl)
  2394. RegionMap[D].reset(SP);
  2395. }
  2396. void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
  2397. QualType FnType) {
  2398. StringRef Name;
  2399. StringRef LinkageName;
  2400. const Decl *D = GD.getDecl();
  2401. if (!D)
  2402. return;
  2403. unsigned Flags = 0;
  2404. llvm::DIFile *Unit = getOrCreateFile(Loc);
  2405. llvm::DIScope *FDContext = getDeclContextDescriptor(D);
  2406. llvm::DINodeArray TParamsArray;
  2407. if (isa<FunctionDecl>(D)) {
  2408. // If there is a DISubprogram for this function available then use it.
  2409. collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
  2410. TParamsArray, Flags);
  2411. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  2412. Name = getObjCMethodName(OMD);
  2413. Flags |= llvm::DINode::FlagPrototyped;
  2414. } else {
  2415. llvm_unreachable("not a function or ObjC method");
  2416. }
  2417. if (!Name.empty() && Name[0] == '\01')
  2418. Name = Name.substr(1);
  2419. if (D->isImplicit()) {
  2420. Flags |= llvm::DINode::FlagArtificial;
  2421. // Artificial functions without a location should not silently reuse CurLoc.
  2422. if (Loc.isInvalid())
  2423. CurLoc = SourceLocation();
  2424. }
  2425. unsigned LineNo = getLineNumber(Loc);
  2426. unsigned ScopeLine = 0;
  2427. DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
  2428. getOrCreateFunctionType(D, FnType, Unit),
  2429. false /*internalLinkage*/, true /*definition*/,
  2430. ScopeLine, Flags, CGM.getLangOpts().Optimize,
  2431. TParamsArray.get(), getFunctionDeclaration(D));
  2432. }
  2433. void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
  2434. // Update our current location
  2435. setLocation(Loc);
  2436. if (CurLoc.isInvalid() || CurLoc.isMacroID())
  2437. return;
  2438. llvm::MDNode *Scope = LexicalBlockStack.back();
  2439. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2440. getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
  2441. }
  2442. void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
  2443. llvm::MDNode *Back = nullptr;
  2444. if (!LexicalBlockStack.empty())
  2445. Back = LexicalBlockStack.back().get();
  2446. LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
  2447. cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
  2448. getColumnNumber(CurLoc)));
  2449. }
  2450. void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
  2451. SourceLocation Loc) {
  2452. // Set our current location.
  2453. setLocation(Loc);
  2454. // Emit a line table change for the current location inside the new scope.
  2455. Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
  2456. getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
  2457. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2458. return;
  2459. // Create a new lexical block and push it on the stack.
  2460. CreateLexicalBlock(Loc);
  2461. }
  2462. void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
  2463. SourceLocation Loc) {
  2464. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2465. // Provide an entry in the line table for the end of the block.
  2466. EmitLocation(Builder, Loc);
  2467. if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
  2468. return;
  2469. LexicalBlockStack.pop_back();
  2470. }
  2471. void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
  2472. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2473. unsigned RCount = FnBeginRegionCount.back();
  2474. assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
  2475. // Pop all regions for this function.
  2476. while (LexicalBlockStack.size() != RCount) {
  2477. // Provide an entry in the line table for the end of the block.
  2478. EmitLocation(Builder, CurLoc);
  2479. LexicalBlockStack.pop_back();
  2480. }
  2481. FnBeginRegionCount.pop_back();
  2482. }
  2483. llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
  2484. uint64_t *XOffset) {
  2485. SmallVector<llvm::Metadata *, 5> EltTys;
  2486. QualType FType;
  2487. uint64_t FieldSize, FieldOffset;
  2488. unsigned FieldAlign;
  2489. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2490. QualType Type = VD->getType();
  2491. FieldOffset = 0;
  2492. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2493. EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
  2494. EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
  2495. FType = CGM.getContext().IntTy;
  2496. EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
  2497. EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
  2498. bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
  2499. if (HasCopyAndDispose) {
  2500. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2501. EltTys.push_back(
  2502. CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
  2503. EltTys.push_back(
  2504. CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
  2505. }
  2506. bool HasByrefExtendedLayout;
  2507. Qualifiers::ObjCLifetime Lifetime;
  2508. if (CGM.getContext().getByrefLifetime(Type, Lifetime,
  2509. HasByrefExtendedLayout) &&
  2510. HasByrefExtendedLayout) {
  2511. FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
  2512. EltTys.push_back(
  2513. CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
  2514. }
  2515. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2516. if (Align > CGM.getContext().toCharUnitsFromBits(
  2517. CGM.getTarget().getPointerAlign(0))) {
  2518. CharUnits FieldOffsetInBytes =
  2519. CGM.getContext().toCharUnitsFromBits(FieldOffset);
  2520. CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
  2521. CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
  2522. if (NumPaddingBytes.isPositive()) {
  2523. llvm::APInt pad(32, NumPaddingBytes.getQuantity());
  2524. FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
  2525. pad, ArrayType::Normal, 0);
  2526. EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
  2527. }
  2528. }
  2529. FType = Type;
  2530. llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
  2531. FieldSize = CGM.getContext().getTypeSize(FType);
  2532. FieldAlign = CGM.getContext().toBits(Align);
  2533. *XOffset = FieldOffset;
  2534. FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
  2535. FieldAlign, FieldOffset, 0, FieldTy);
  2536. EltTys.push_back(FieldTy);
  2537. FieldOffset += FieldSize;
  2538. llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
  2539. unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
  2540. return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
  2541. nullptr, Elements);
  2542. }
  2543. void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
  2544. llvm::Optional<unsigned> ArgNo,
  2545. CGBuilderTy &Builder) {
  2546. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2547. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2548. bool Unwritten =
  2549. VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
  2550. cast<Decl>(VD->getDeclContext())->isImplicit());
  2551. llvm::DIFile *Unit = nullptr;
  2552. if (!Unwritten)
  2553. Unit = getOrCreateFile(VD->getLocation());
  2554. llvm::DIType *Ty;
  2555. uint64_t XOffset = 0;
  2556. if (VD->hasAttr<BlocksAttr>())
  2557. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2558. else
  2559. Ty = getOrCreateType(VD->getType(), Unit);
  2560. // If there is no debug info for this type then do not emit debug info
  2561. // for this variable.
  2562. if (!Ty)
  2563. return;
  2564. // Get location information.
  2565. unsigned Line = 0;
  2566. unsigned Column = 0;
  2567. if (!Unwritten) {
  2568. Line = getLineNumber(VD->getLocation());
  2569. Column = getColumnNumber(VD->getLocation());
  2570. }
  2571. SmallVector<int64_t, 9> Expr;
  2572. unsigned Flags = 0;
  2573. if (VD->isImplicit())
  2574. Flags |= llvm::DINode::FlagArtificial;
  2575. // If this is the first argument and it is implicit then
  2576. // give it an object pointer flag.
  2577. // FIXME: There has to be a better way to do this, but for static
  2578. // functions there won't be an implicit param at arg1 and
  2579. // otherwise it is 'self' or 'this'.
  2580. if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
  2581. Flags |= llvm::DINode::FlagObjectPointer;
  2582. if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
  2583. if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
  2584. !VD->getType()->isPointerType())
  2585. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2586. auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
  2587. StringRef Name = VD->getName();
  2588. if (!Name.empty()) {
  2589. if (VD->hasAttr<BlocksAttr>()) {
  2590. CharUnits offset = CharUnits::fromQuantity(32);
  2591. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2592. // offset of __forwarding field
  2593. offset = CGM.getContext().toCharUnitsFromBits(
  2594. CGM.getTarget().getPointerWidth(0));
  2595. Expr.push_back(offset.getQuantity());
  2596. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2597. Expr.push_back(llvm::dwarf::DW_OP_plus);
  2598. // offset of x field
  2599. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2600. Expr.push_back(offset.getQuantity());
  2601. // Create the descriptor for the variable.
  2602. auto *D = ArgNo
  2603. ? DBuilder.createParameterVariable(Scope, VD->getName(),
  2604. *ArgNo, Unit, Line, Ty)
  2605. : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
  2606. Line, Ty);
  2607. // Insert an llvm.dbg.declare into the current block.
  2608. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2609. llvm::DebugLoc::get(Line, Column, Scope),
  2610. Builder.GetInsertBlock());
  2611. return;
  2612. } else if (isa<VariableArrayType>(VD->getType()))
  2613. Expr.push_back(llvm::dwarf::DW_OP_deref);
  2614. } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
  2615. // If VD is an anonymous union then Storage represents value for
  2616. // all union fields.
  2617. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  2618. if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
  2619. // GDB has trouble finding local variables in anonymous unions, so we emit
  2620. // artifical local variables for each of the members.
  2621. //
  2622. // FIXME: Remove this code as soon as GDB supports this.
  2623. // The debug info verifier in LLVM operates based on the assumption that a
  2624. // variable has the same size as its storage and we had to disable the check
  2625. // for artificial variables.
  2626. for (const auto *Field : RD->fields()) {
  2627. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2628. StringRef FieldName = Field->getName();
  2629. // Ignore unnamed fields. Do not ignore unnamed records.
  2630. if (FieldName.empty() && !isa<RecordType>(Field->getType()))
  2631. continue;
  2632. // Use VarDecl's Tag, Scope and Line number.
  2633. auto *D = DBuilder.createAutoVariable(
  2634. Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
  2635. Flags | llvm::DINode::FlagArtificial);
  2636. // Insert an llvm.dbg.declare into the current block.
  2637. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2638. llvm::DebugLoc::get(Line, Column, Scope),
  2639. Builder.GetInsertBlock());
  2640. }
  2641. }
  2642. }
  2643. // Create the descriptor for the variable.
  2644. auto *D =
  2645. ArgNo
  2646. ? DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line,
  2647. Ty, CGM.getLangOpts().Optimize,
  2648. Flags)
  2649. : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
  2650. CGM.getLangOpts().Optimize, Flags);
  2651. // Insert an llvm.dbg.declare into the current block.
  2652. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
  2653. llvm::DebugLoc::get(Line, Column, Scope),
  2654. Builder.GetInsertBlock());
  2655. }
  2656. void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
  2657. llvm::Value *Storage,
  2658. CGBuilderTy &Builder) {
  2659. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2660. EmitDeclare(VD, Storage, llvm::None, Builder);
  2661. }
  2662. llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
  2663. llvm::DIType *Ty) {
  2664. llvm::DIType *CachedTy = getTypeOrNull(QualTy);
  2665. if (CachedTy)
  2666. Ty = CachedTy;
  2667. return DBuilder.createObjectPointerType(Ty);
  2668. }
  2669. void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
  2670. const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
  2671. const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
  2672. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2673. assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
  2674. if (Builder.GetInsertBlock() == nullptr)
  2675. return;
  2676. bool isByRef = VD->hasAttr<BlocksAttr>();
  2677. uint64_t XOffset = 0;
  2678. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2679. llvm::DIType *Ty;
  2680. if (isByRef)
  2681. Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
  2682. else
  2683. Ty = getOrCreateType(VD->getType(), Unit);
  2684. // Self is passed along as an implicit non-arg variable in a
  2685. // block. Mark it as the object pointer.
  2686. if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
  2687. Ty = CreateSelfType(VD->getType(), Ty);
  2688. // Get location information.
  2689. unsigned Line = getLineNumber(VD->getLocation());
  2690. unsigned Column = getColumnNumber(VD->getLocation());
  2691. const llvm::DataLayout &target = CGM.getDataLayout();
  2692. CharUnits offset = CharUnits::fromQuantity(
  2693. target.getStructLayout(blockInfo.StructureType)
  2694. ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
  2695. SmallVector<int64_t, 9> addr;
  2696. if (isa<llvm::AllocaInst>(Storage))
  2697. addr.push_back(llvm::dwarf::DW_OP_deref);
  2698. addr.push_back(llvm::dwarf::DW_OP_plus);
  2699. addr.push_back(offset.getQuantity());
  2700. if (isByRef) {
  2701. addr.push_back(llvm::dwarf::DW_OP_deref);
  2702. addr.push_back(llvm::dwarf::DW_OP_plus);
  2703. // offset of __forwarding field
  2704. offset =
  2705. CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
  2706. addr.push_back(offset.getQuantity());
  2707. addr.push_back(llvm::dwarf::DW_OP_deref);
  2708. addr.push_back(llvm::dwarf::DW_OP_plus);
  2709. // offset of x field
  2710. offset = CGM.getContext().toCharUnitsFromBits(XOffset);
  2711. addr.push_back(offset.getQuantity());
  2712. }
  2713. // Create the descriptor for the variable.
  2714. auto *D = DBuilder.createAutoVariable(
  2715. cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
  2716. Line, Ty);
  2717. // Insert an llvm.dbg.declare into the current block.
  2718. auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
  2719. if (InsertPoint)
  2720. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  2721. InsertPoint);
  2722. else
  2723. DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
  2724. Builder.GetInsertBlock());
  2725. }
  2726. void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
  2727. unsigned ArgNo,
  2728. CGBuilderTy &Builder) {
  2729. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2730. EmitDeclare(VD, AI, ArgNo, Builder);
  2731. }
  2732. namespace {
  2733. struct BlockLayoutChunk {
  2734. uint64_t OffsetInBits;
  2735. const BlockDecl::Capture *Capture;
  2736. };
  2737. bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
  2738. return l.OffsetInBits < r.OffsetInBits;
  2739. }
  2740. }
  2741. void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
  2742. llvm::Value *Arg,
  2743. unsigned ArgNo,
  2744. llvm::Value *LocalAddr,
  2745. CGBuilderTy &Builder) {
  2746. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2747. ASTContext &C = CGM.getContext();
  2748. const BlockDecl *blockDecl = block.getBlockDecl();
  2749. // Collect some general information about the block's location.
  2750. SourceLocation loc = blockDecl->getCaretLocation();
  2751. llvm::DIFile *tunit = getOrCreateFile(loc);
  2752. unsigned line = getLineNumber(loc);
  2753. unsigned column = getColumnNumber(loc);
  2754. // Build the debug-info type for the block literal.
  2755. getDeclContextDescriptor(blockDecl);
  2756. const llvm::StructLayout *blockLayout =
  2757. CGM.getDataLayout().getStructLayout(block.StructureType);
  2758. SmallVector<llvm::Metadata *, 16> fields;
  2759. fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
  2760. blockLayout->getElementOffsetInBits(0),
  2761. tunit, tunit));
  2762. fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
  2763. blockLayout->getElementOffsetInBits(1),
  2764. tunit, tunit));
  2765. fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
  2766. blockLayout->getElementOffsetInBits(2),
  2767. tunit, tunit));
  2768. auto *FnTy = block.getBlockExpr()->getFunctionType();
  2769. auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
  2770. fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
  2771. blockLayout->getElementOffsetInBits(3),
  2772. tunit, tunit));
  2773. fields.push_back(createFieldType(
  2774. "__descriptor", C.getPointerType(block.NeedsCopyDispose
  2775. ? C.getBlockDescriptorExtendedType()
  2776. : C.getBlockDescriptorType()),
  2777. 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
  2778. // We want to sort the captures by offset, not because DWARF
  2779. // requires this, but because we're paranoid about debuggers.
  2780. SmallVector<BlockLayoutChunk, 8> chunks;
  2781. // 'this' capture.
  2782. if (blockDecl->capturesCXXThis()) {
  2783. BlockLayoutChunk chunk;
  2784. chunk.OffsetInBits =
  2785. blockLayout->getElementOffsetInBits(block.CXXThisIndex);
  2786. chunk.Capture = nullptr;
  2787. chunks.push_back(chunk);
  2788. }
  2789. // Variable captures.
  2790. for (const auto &capture : blockDecl->captures()) {
  2791. const VarDecl *variable = capture.getVariable();
  2792. const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
  2793. // Ignore constant captures.
  2794. if (captureInfo.isConstant())
  2795. continue;
  2796. BlockLayoutChunk chunk;
  2797. chunk.OffsetInBits =
  2798. blockLayout->getElementOffsetInBits(captureInfo.getIndex());
  2799. chunk.Capture = &capture;
  2800. chunks.push_back(chunk);
  2801. }
  2802. // Sort by offset.
  2803. llvm::array_pod_sort(chunks.begin(), chunks.end());
  2804. for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
  2805. e = chunks.end();
  2806. i != e; ++i) {
  2807. uint64_t offsetInBits = i->OffsetInBits;
  2808. const BlockDecl::Capture *capture = i->Capture;
  2809. // If we have a null capture, this must be the C++ 'this' capture.
  2810. if (!capture) {
  2811. const CXXMethodDecl *method =
  2812. cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
  2813. QualType type = method->getThisType(C);
  2814. fields.push_back(createFieldType("this", type, 0, loc, AS_public,
  2815. offsetInBits, tunit, tunit));
  2816. continue;
  2817. }
  2818. const VarDecl *variable = capture->getVariable();
  2819. StringRef name = variable->getName();
  2820. llvm::DIType *fieldType;
  2821. if (capture->isByRef()) {
  2822. TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
  2823. // FIXME: this creates a second copy of this type!
  2824. uint64_t xoffset;
  2825. fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
  2826. fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
  2827. fieldType =
  2828. DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
  2829. PtrInfo.Align, offsetInBits, 0, fieldType);
  2830. } else {
  2831. fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
  2832. offsetInBits, tunit, tunit);
  2833. }
  2834. fields.push_back(fieldType);
  2835. }
  2836. SmallString<36> typeName;
  2837. llvm::raw_svector_ostream(typeName) << "__block_literal_"
  2838. << CGM.getUniqueBlockCount();
  2839. llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
  2840. llvm::DIType *type = DBuilder.createStructType(
  2841. tunit, typeName.str(), tunit, line,
  2842. CGM.getContext().toBits(block.BlockSize),
  2843. CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
  2844. type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
  2845. // Get overall information about the block.
  2846. unsigned flags = llvm::DINode::FlagArtificial;
  2847. auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
  2848. // Create the descriptor for the parameter.
  2849. auto *debugVar = DBuilder.createParameterVariable(
  2850. scope, Arg->getName(), ArgNo, tunit, line, type,
  2851. CGM.getLangOpts().Optimize, flags);
  2852. if (LocalAddr) {
  2853. // Insert an llvm.dbg.value into the current block.
  2854. DBuilder.insertDbgValueIntrinsic(
  2855. LocalAddr, 0, debugVar, DBuilder.createExpression(),
  2856. llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
  2857. }
  2858. // Insert an llvm.dbg.declare into the current block.
  2859. DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
  2860. llvm::DebugLoc::get(line, column, scope),
  2861. Builder.GetInsertBlock());
  2862. }
  2863. llvm::DIDerivedType *
  2864. CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
  2865. if (!D->isStaticDataMember())
  2866. return nullptr;
  2867. auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
  2868. if (MI != StaticDataMemberCache.end()) {
  2869. assert(MI->second && "Static data member declaration should still exist");
  2870. return MI->second;
  2871. }
  2872. // If the member wasn't found in the cache, lazily construct and add it to the
  2873. // type (used when a limited form of the type is emitted).
  2874. auto DC = D->getDeclContext();
  2875. auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
  2876. return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
  2877. }
  2878. llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
  2879. const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
  2880. StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
  2881. llvm::DIGlobalVariable *GV = nullptr;
  2882. for (const auto *Field : RD->fields()) {
  2883. llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
  2884. StringRef FieldName = Field->getName();
  2885. // Ignore unnamed fields, but recurse into anonymous records.
  2886. if (FieldName.empty()) {
  2887. const RecordType *RT = dyn_cast<RecordType>(Field->getType());
  2888. if (RT)
  2889. GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
  2890. Var, DContext);
  2891. continue;
  2892. }
  2893. // Use VarDecl's Tag, Scope and Line number.
  2894. GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
  2895. LineNo, FieldTy,
  2896. Var->hasInternalLinkage(), Var, nullptr);
  2897. }
  2898. return GV;
  2899. }
  2900. void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
  2901. const VarDecl *D) {
  2902. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2903. // Create global variable debug descriptor.
  2904. llvm::DIFile *Unit = nullptr;
  2905. llvm::DIScope *DContext = nullptr;
  2906. unsigned LineNo;
  2907. StringRef DeclName, LinkageName;
  2908. QualType T;
  2909. collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
  2910. // Attempt to store one global variable for the declaration - even if we
  2911. // emit a lot of fields.
  2912. llvm::DIGlobalVariable *GV = nullptr;
  2913. // If this is an anonymous union then we'll want to emit a global
  2914. // variable for each member of the anonymous union so that it's possible
  2915. // to find the name of any field in the union.
  2916. if (T->isUnionType() && DeclName.empty()) {
  2917. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  2918. assert(RD->isAnonymousStructOrUnion() &&
  2919. "unnamed non-anonymous struct or union?");
  2920. GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
  2921. } else {
  2922. GV = DBuilder.createGlobalVariable(
  2923. DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
  2924. Var->hasInternalLinkage(), Var,
  2925. getOrCreateStaticDataMemberDeclarationOrNull(D));
  2926. }
  2927. DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
  2928. }
  2929. void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
  2930. llvm::Constant *Init) {
  2931. assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
  2932. // Create the descriptor for the variable.
  2933. llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
  2934. StringRef Name = VD->getName();
  2935. llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
  2936. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
  2937. const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
  2938. assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
  2939. Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
  2940. }
  2941. // Do not use global variables for enums.
  2942. //
  2943. // FIXME: why not?
  2944. if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
  2945. return;
  2946. // Do not emit separate definitions for function local const/statics.
  2947. if (isa<FunctionDecl>(VD->getDeclContext()))
  2948. return;
  2949. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  2950. auto *VarD = cast<VarDecl>(VD);
  2951. if (VarD->isStaticDataMember()) {
  2952. auto *RD = cast<RecordDecl>(VarD->getDeclContext());
  2953. getDeclContextDescriptor(VarD);
  2954. // Ensure that the type is retained even though it's otherwise unreferenced.
  2955. RetainedTypes.push_back(
  2956. CGM.getContext().getRecordType(RD).getAsOpaquePtr());
  2957. return;
  2958. }
  2959. llvm::DIScope *DContext = getDeclContextDescriptor(VD);
  2960. auto &GV = DeclCache[VD];
  2961. if (GV)
  2962. return;
  2963. GV.reset(DBuilder.createGlobalVariable(
  2964. DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
  2965. true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
  2966. }
  2967. llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
  2968. if (!LexicalBlockStack.empty())
  2969. return LexicalBlockStack.back();
  2970. llvm::DIScope *Mod = getParentModuleOrNull(D);
  2971. return getContextDescriptor(D, Mod ? Mod : TheCU);
  2972. }
  2973. void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
  2974. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2975. return;
  2976. const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
  2977. if (!NSDecl->isAnonymousNamespace() ||
  2978. CGM.getCodeGenOpts().DebugExplicitImport) {
  2979. DBuilder.createImportedModule(
  2980. getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
  2981. getOrCreateNameSpace(NSDecl),
  2982. getLineNumber(UD.getLocation()));
  2983. }
  2984. }
  2985. void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
  2986. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  2987. return;
  2988. assert(UD.shadow_size() &&
  2989. "We shouldn't be codegening an invalid UsingDecl containing no decls");
  2990. // Emitting one decl is sufficient - debuggers can detect that this is an
  2991. // overloaded name & provide lookup for all the overloads.
  2992. const UsingShadowDecl &USD = **UD.shadow_begin();
  2993. if (llvm::DINode *Target =
  2994. getDeclarationOrDefinition(USD.getUnderlyingDecl()))
  2995. DBuilder.createImportedDeclaration(
  2996. getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
  2997. getLineNumber(USD.getLocation()));
  2998. }
  2999. void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
  3000. if (Module *M = ID.getImportedModule()) {
  3001. auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
  3002. DBuilder.createImportedDeclaration(
  3003. getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
  3004. getOrCreateModuleRef(Info, DebugTypeExtRefs),
  3005. getLineNumber(ID.getLocation()));
  3006. }
  3007. }
  3008. llvm::DIImportedEntity *
  3009. CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
  3010. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  3011. return nullptr;
  3012. auto &VH = NamespaceAliasCache[&NA];
  3013. if (VH)
  3014. return cast<llvm::DIImportedEntity>(VH);
  3015. llvm::DIImportedEntity *R;
  3016. if (const NamespaceAliasDecl *Underlying =
  3017. dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
  3018. // This could cache & dedup here rather than relying on metadata deduping.
  3019. R = DBuilder.createImportedDeclaration(
  3020. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  3021. EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
  3022. NA.getName());
  3023. else
  3024. R = DBuilder.createImportedDeclaration(
  3025. getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
  3026. getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
  3027. getLineNumber(NA.getLocation()), NA.getName());
  3028. VH.reset(R);
  3029. return R;
  3030. }
  3031. llvm::DINamespace *
  3032. CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
  3033. NSDecl = NSDecl->getCanonicalDecl();
  3034. auto I = NameSpaceCache.find(NSDecl);
  3035. if (I != NameSpaceCache.end())
  3036. return cast<llvm::DINamespace>(I->second);
  3037. unsigned LineNo = getLineNumber(NSDecl->getLocation());
  3038. llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
  3039. llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
  3040. llvm::DINamespace *NS =
  3041. DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
  3042. NameSpaceCache[NSDecl].reset(NS);
  3043. return NS;
  3044. }
  3045. void CGDebugInfo::setDwoId(uint64_t Signature) {
  3046. assert(TheCU && "no main compile unit");
  3047. TheCU->setDWOId(Signature);
  3048. }
  3049. void CGDebugInfo::finalize() {
  3050. // Creating types might create further types - invalidating the current
  3051. // element and the size(), so don't cache/reference them.
  3052. for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
  3053. ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
  3054. llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
  3055. ? CreateTypeDefinition(E.Type, E.Unit)
  3056. : E.Decl;
  3057. DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
  3058. }
  3059. for (auto p : ReplaceMap) {
  3060. assert(p.second);
  3061. auto *Ty = cast<llvm::DIType>(p.second);
  3062. assert(Ty->isForwardDecl());
  3063. auto it = TypeCache.find(p.first);
  3064. assert(it != TypeCache.end());
  3065. assert(it->second);
  3066. DBuilder.replaceTemporary(llvm::TempDIType(Ty),
  3067. cast<llvm::DIType>(it->second));
  3068. }
  3069. for (const auto &p : FwdDeclReplaceMap) {
  3070. assert(p.second);
  3071. llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
  3072. llvm::Metadata *Repl;
  3073. auto it = DeclCache.find(p.first);
  3074. // If there has been no definition for the declaration, call RAUW
  3075. // with ourselves, that will destroy the temporary MDNode and
  3076. // replace it with a standard one, avoiding leaking memory.
  3077. if (it == DeclCache.end())
  3078. Repl = p.second;
  3079. else
  3080. Repl = it->second;
  3081. DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
  3082. }
  3083. // We keep our own list of retained types, because we need to look
  3084. // up the final type in the type cache.
  3085. for (auto &RT : RetainedTypes)
  3086. if (auto MD = TypeCache[RT])
  3087. DBuilder.retainType(cast<llvm::DIType>(MD));
  3088. DBuilder.finalize();
  3089. }
  3090. void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
  3091. if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
  3092. return;
  3093. if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
  3094. // Don't ignore in case of explicit cast where it is referenced indirectly.
  3095. DBuilder.retainType(DieTy);
  3096. }