CGDebugInfo.cpp 129 KB

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