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