CGDebugInfo.cpp 132 KB

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