CodeGenModule.cpp 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs 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 per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CGHLSLRuntime.h" // HLSL Change
  21. #include "CGOpenMPRuntime.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenPGO.h"
  24. #include "CodeGenTBAA.h"
  25. #include "CoverageMappingGen.h"
  26. #include "TargetInfo.h"
  27. #include "clang/AST/ASTContext.h"
  28. #include "clang/AST/CharUnits.h"
  29. #include "clang/AST/DeclCXX.h"
  30. #include "clang/AST/DeclObjC.h"
  31. #include "clang/AST/DeclTemplate.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/RecordLayout.h"
  34. #include "clang/AST/RecursiveASTVisitor.h"
  35. #include "clang/Basic/Builtins.h"
  36. #include "clang/Basic/CharInfo.h"
  37. #include "clang/Basic/Diagnostic.h"
  38. #include "clang/Basic/Module.h"
  39. #include "clang/Basic/SourceManager.h"
  40. #include "clang/Basic/TargetInfo.h"
  41. #include "clang/Basic/Version.h"
  42. #include "clang/Frontend/CodeGenOptions.h"
  43. #include "clang/Sema/SemaDiagnostic.h"
  44. #include "llvm/ADT/APSInt.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include "llvm/IR/CallSite.h"
  47. #include "llvm/IR/CallingConv.h"
  48. #include "llvm/IR/DataLayout.h"
  49. #include "llvm/IR/Intrinsics.h"
  50. #include "llvm/IR/LLVMContext.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/ProfileData/InstrProfReader.h"
  53. #include "llvm/Support/ConvertUTF.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "dxc/HLSL/DxilConstants.h" // HLSL Change
  56. using namespace clang;
  57. using namespace CodeGen;
  58. static const char AnnotationSection[] = "llvm.metadata";
  59. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  60. switch (CGM.getTarget().getCXXABI().getKind()) {
  61. case TargetCXXABI::GenericAArch64:
  62. case TargetCXXABI::GenericARM:
  63. case TargetCXXABI::iOS:
  64. case TargetCXXABI::iOS64:
  65. case TargetCXXABI::GenericMIPS:
  66. case TargetCXXABI::GenericItanium:
  67. return CreateItaniumCXXABI(CGM);
  68. case TargetCXXABI::Microsoft:
  69. return CreateMicrosoftCXXABI(CGM);
  70. }
  71. llvm_unreachable("invalid C++ ABI kind");
  72. }
  73. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  74. const PreprocessorOptions &PPO,
  75. const CodeGenOptions &CGO, llvm::Module &M,
  76. const llvm::DataLayout &TD,
  77. DiagnosticsEngine &diags,
  78. CoverageSourceInfo *CoverageInfo)
  79. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  80. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  81. TheDataLayout(TD), Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  82. VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr),
  83. Types(*this), VTables(*this), ObjCRuntime(nullptr),
  84. OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr),
  85. HLSLRuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr), // HLSL Change
  86. NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
  87. CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
  88. NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
  89. NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
  90. BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
  91. GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
  92. LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
  93. // Initialize the type cache.
  94. llvm::LLVMContext &LLVMContext = M.getContext();
  95. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  96. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  97. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  98. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  99. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  100. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  101. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  102. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  103. PointerAlignInBytes =
  104. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  105. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  106. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  107. Int8PtrTy = Int8Ty->getPointerTo(0);
  108. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  109. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  110. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  111. if (LangOpts.ObjC1)
  112. createObjCRuntime();
  113. if (LangOpts.OpenCL)
  114. createOpenCLRuntime();
  115. if (LangOpts.OpenMP)
  116. createOpenMPRuntime();
  117. if (LangOpts.CUDA)
  118. createCUDARuntime();
  119. // HLSL Change Starts
  120. std::unique_ptr<CGHLSLRuntime> RuntimePtr;
  121. std::unique_ptr<CodeGenTBAA> TBAAPtr;
  122. std::unique_ptr<CGDebugInfo> DebugInfoPtr;
  123. if (LangOpts.HLSL) {
  124. createHLSLRuntime();
  125. RuntimePtr.reset(HLSLRuntime);
  126. }
  127. // HLSL Change Ends
  128. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  129. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  130. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  131. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  132. getCXXABI().getMangleContext());
  133. TBAAPtr.reset(TBAA); // HLSL Change
  134. // If debug info or coverage generation is enabled, create the CGDebugInfo
  135. // object.
  136. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  137. CodeGenOpts.EmitGcovArcs ||
  138. CodeGenOpts.EmitGcovNotes)
  139. DebugInfo = new CGDebugInfo(*this);
  140. DebugInfoPtr.reset(DebugInfo); // HLSL Change
  141. Block.GlobalUniqueCount = 0;
  142. #if 0 // HLSL Change Starts - no ARC support
  143. if (C.getLangOpts().ObjCAutoRefCount)
  144. ARCData = new ARCEntrypoints();
  145. RRData = new RREntrypoints();
  146. #endif // HLSL Change Ends - no ARC support
  147. if (!CodeGenOpts.InstrProfileInput.empty()) {
  148. auto ReaderOrErr =
  149. llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
  150. if (std::error_code EC = ReaderOrErr.getError()) {
  151. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  152. "Could not read profile %0: %1");
  153. getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput
  154. << EC.message();
  155. } else
  156. PGOReader = std::move(ReaderOrErr.get());
  157. }
  158. // If coverage mapping generation is enabled, create the
  159. // CoverageMappingModuleGen object.
  160. if (CodeGenOpts.CoverageMapping)
  161. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  162. // HLSL Change Starts - release acquired pointers
  163. RuntimePtr.release();
  164. TBAAPtr.release();
  165. DebugInfoPtr.release();
  166. // HLSL Change Ends
  167. }
  168. CodeGenModule::~CodeGenModule() {
  169. delete ObjCRuntime;
  170. delete OpenCLRuntime;
  171. delete OpenMPRuntime;
  172. delete CUDARuntime;
  173. delete HLSLRuntime; // HLSL Change
  174. TheTargetCodeGenInfo.reset(nullptr); // HLSL Change
  175. delete TBAA;
  176. delete DebugInfo;
  177. delete ARCData;
  178. delete RRData;
  179. }
  180. void CodeGenModule::createObjCRuntime() {
  181. #if 0 // HLSL Change - no ObjC support
  182. // This is just isGNUFamily(), but we want to force implementors of
  183. // new ABIs to decide how best to do this.
  184. switch (LangOpts.ObjCRuntime.getKind()) {
  185. case ObjCRuntime::GNUstep:
  186. case ObjCRuntime::GCC:
  187. case ObjCRuntime::ObjFW:
  188. ObjCRuntime = CreateGNUObjCRuntime(*this);
  189. return;
  190. case ObjCRuntime::FragileMacOSX:
  191. case ObjCRuntime::MacOSX:
  192. case ObjCRuntime::iOS:
  193. ObjCRuntime = CreateMacObjCRuntime(*this);
  194. return;
  195. }
  196. llvm_unreachable("bad runtime kind");
  197. #endif // HLSL Change - no ObjC support
  198. }
  199. void CodeGenModule::createOpenCLRuntime() {
  200. #if 0 // HLSL Change - no OpenCL support
  201. OpenCLRuntime = new CGOpenCLRuntime(*this);
  202. #endif // HLSL Change - no OpenCL support
  203. }
  204. void CodeGenModule::createOpenMPRuntime() {
  205. #if 0 // HLSL Change - no OpenMP support
  206. OpenMPRuntime = new CGOpenMPRuntime(*this);
  207. #endif // HLSL Change - no OpenMP support
  208. }
  209. void CodeGenModule::createCUDARuntime() {
  210. #if 0 // HLSL Change - no CUDA support
  211. CUDARuntime = CreateNVCUDARuntime(*this);
  212. #endif // HLSL Change - no CUDA support
  213. }
  214. // HLSL Change Starts
  215. void CodeGenModule::createHLSLRuntime() {
  216. HLSLRuntime = CreateMSHLSLRuntime(*this);
  217. }
  218. void CodeGenModule::FinishCodeGen() {
  219. HLSLRuntime->FinishCodeGen();
  220. }
  221. // HLSL Change Ends
  222. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  223. Replacements[Name] = C;
  224. }
  225. void CodeGenModule::applyReplacements() {
  226. for (auto &I : Replacements) {
  227. StringRef MangledName = I.first();
  228. llvm::Constant *Replacement = I.second;
  229. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  230. if (!Entry)
  231. continue;
  232. auto *OldF = cast<llvm::Function>(Entry);
  233. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  234. if (!NewF) {
  235. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  236. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  237. } else {
  238. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  239. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  240. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  241. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  242. }
  243. }
  244. // Replace old with new, but keep the old order.
  245. OldF->replaceAllUsesWith(Replacement);
  246. if (NewF) {
  247. NewF->removeFromParent();
  248. OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
  249. }
  250. OldF->eraseFromParent();
  251. }
  252. }
  253. // This is only used in aliases that we created and we know they have a
  254. // linear structure.
  255. static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
  256. llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
  257. const llvm::Constant *C = &GA;
  258. for (;;) {
  259. C = C->stripPointerCasts();
  260. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  261. return GO;
  262. // stripPointerCasts will not walk over weak aliases.
  263. auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
  264. if (!GA2)
  265. return nullptr;
  266. if (!Visited.insert(GA2).second)
  267. return nullptr;
  268. C = GA2->getAliasee();
  269. }
  270. }
  271. void CodeGenModule::checkAliases() {
  272. // Check if the constructed aliases are well formed. It is really unfortunate
  273. // that we have to do this in CodeGen, but we only construct mangled names
  274. // and aliases during codegen.
  275. bool Error = false;
  276. DiagnosticsEngine &Diags = getDiags();
  277. for (const GlobalDecl &GD : Aliases) {
  278. const auto *D = cast<ValueDecl>(GD.getDecl());
  279. const AliasAttr *AA = D->getAttr<AliasAttr>();
  280. StringRef MangledName = getMangledName(GD);
  281. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  282. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  283. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  284. if (!GV) {
  285. Error = true;
  286. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  287. } else if (GV->isDeclaration()) {
  288. Error = true;
  289. Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
  290. }
  291. llvm::Constant *Aliasee = Alias->getAliasee();
  292. llvm::GlobalValue *AliaseeGV;
  293. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  294. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  295. else
  296. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  297. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  298. StringRef AliasSection = SA->getName();
  299. if (AliasSection != AliaseeGV->getSection())
  300. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  301. << AliasSection;
  302. }
  303. // We have to handle alias to weak aliases in here. LLVM itself disallows
  304. // this since the object semantics would not match the IL one. For
  305. // compatibility with gcc we implement it by just pointing the alias
  306. // to its aliasee's aliasee. We also warn, since the user is probably
  307. // expecting the link to be weak.
  308. if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
  309. if (GA->mayBeOverridden()) {
  310. Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
  311. << GV->getName() << GA->getName();
  312. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  313. GA->getAliasee(), Alias->getType());
  314. Alias->setAliasee(Aliasee);
  315. }
  316. }
  317. }
  318. if (!Error)
  319. return;
  320. for (const GlobalDecl &GD : Aliases) {
  321. StringRef MangledName = getMangledName(GD);
  322. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  323. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  324. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  325. Alias->eraseFromParent();
  326. }
  327. }
  328. void CodeGenModule::clear() {
  329. DeferredDeclsToEmit.clear();
  330. if (OpenMPRuntime)
  331. OpenMPRuntime->clear();
  332. }
  333. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  334. StringRef MainFile) {
  335. if (!hasDiagnostics())
  336. return;
  337. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  338. if (MainFile.empty())
  339. MainFile = "<stdin>";
  340. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  341. } else
  342. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  343. << Mismatched;
  344. }
  345. void CodeGenModule::Release() {
  346. EmitDeferred();
  347. applyReplacements();
  348. checkAliases();
  349. EmitCXXGlobalInitFunc();
  350. EmitCXXGlobalDtorFunc();
  351. EmitCXXThreadLocalInitFunc();
  352. if (ObjCRuntime)
  353. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  354. AddGlobalCtor(ObjCInitFunction);
  355. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  356. CUDARuntime) {
  357. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  358. AddGlobalCtor(CudaCtorFunction);
  359. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  360. AddGlobalDtor(CudaDtorFunction);
  361. }
  362. if (PGOReader && PGOStats.hasDiagnostics())
  363. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  364. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  365. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  366. EmitGlobalAnnotations();
  367. EmitStaticExternCAliases();
  368. EmitDeferredUnusedCoverageMappings();
  369. if (CoverageMapping)
  370. CoverageMapping->emit();
  371. emitLLVMUsed();
  372. if (CodeGenOpts.Autolink &&
  373. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  374. EmitModuleLinkOptions();
  375. }
  376. if (CodeGenOpts.DwarfVersion)
  377. // We actually want the latest version when there are conflicts.
  378. // We can change from Warning to Latest if such mode is supported.
  379. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  380. CodeGenOpts.DwarfVersion);
  381. if (DebugInfo)
  382. // We support a single version in the linked module. The LLVM
  383. // parser will drop debug info with a different version number
  384. // (and warn about it, too).
  385. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  386. llvm::DEBUG_METADATA_VERSION);
  387. // We need to record the widths of enums and wchar_t, so that we can generate
  388. // the correct build attributes in the ARM backend.
  389. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  390. if ( Arch == llvm::Triple::arm
  391. || Arch == llvm::Triple::armeb
  392. || Arch == llvm::Triple::thumb
  393. || Arch == llvm::Triple::thumbeb) {
  394. // Width of wchar_t in bytes
  395. uint64_t WCharWidth =
  396. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  397. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  398. // The minimum width of an enum in bytes
  399. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  400. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  401. }
  402. // HLSL Change Starts
  403. if (Context.getLangOpts().HLSL) {
  404. FinishCodeGen();
  405. }
  406. // HLSL Change Ends
  407. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  408. llvm::PICLevel::Level PL = llvm::PICLevel::Default;
  409. switch (PLevel) {
  410. case 0: break;
  411. case 1: PL = llvm::PICLevel::Small; break;
  412. case 2: PL = llvm::PICLevel::Large; break;
  413. default: llvm_unreachable("Invalid PIC Level");
  414. }
  415. getModule().setPICLevel(PL);
  416. }
  417. SimplifyPersonality();
  418. if (getCodeGenOpts().EmitDeclMetadata)
  419. EmitDeclMetadata();
  420. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  421. EmitCoverageFile();
  422. if (DebugInfo)
  423. DebugInfo->finalize();
  424. EmitVersionIdentMetadata();
  425. EmitTargetMetadata();
  426. }
  427. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  428. // Make sure that this type is translated.
  429. Types.UpdateCompletedType(TD);
  430. }
  431. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  432. if (!TBAA)
  433. return nullptr;
  434. return TBAA->getTBAAInfo(QTy);
  435. }
  436. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  437. if (!TBAA)
  438. return nullptr;
  439. return TBAA->getTBAAInfoForVTablePtr();
  440. }
  441. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  442. if (!TBAA)
  443. return nullptr;
  444. return TBAA->getTBAAStructInfo(QTy);
  445. }
  446. llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
  447. if (!TBAA)
  448. return nullptr;
  449. return TBAA->getTBAAStructTypeInfo(QTy);
  450. }
  451. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  452. llvm::MDNode *AccessN,
  453. uint64_t O) {
  454. if (!TBAA)
  455. return nullptr;
  456. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  457. }
  458. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  459. /// and struct-path aware TBAA, the tag has the same format:
  460. /// base type, access type and offset.
  461. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  462. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  463. llvm::MDNode *TBAAInfo,
  464. bool ConvertTypeToTag) {
  465. if (ConvertTypeToTag && TBAA)
  466. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  467. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  468. else
  469. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  470. }
  471. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  472. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  473. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  474. }
  475. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  476. /// specified stmt yet.
  477. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  478. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  479. "cannot compile this %0 yet");
  480. std::string Msg = Type;
  481. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  482. << Msg << S->getSourceRange();
  483. }
  484. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  485. /// specified decl yet.
  486. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  487. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  488. "cannot compile this %0 yet");
  489. std::string Msg = Type;
  490. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  491. }
  492. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  493. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  494. }
  495. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  496. const NamedDecl *D) const {
  497. // Internal definitions always have default visibility.
  498. if (GV->hasLocalLinkage()) {
  499. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  500. return;
  501. }
  502. // Set visibility for definitions.
  503. LinkageInfo LV = D->getLinkageAndVisibility();
  504. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  505. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  506. }
  507. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  508. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  509. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  510. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  511. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  512. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  513. }
  514. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  515. CodeGenOptions::TLSModel M) {
  516. switch (M) {
  517. case CodeGenOptions::GeneralDynamicTLSModel:
  518. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  519. case CodeGenOptions::LocalDynamicTLSModel:
  520. return llvm::GlobalVariable::LocalDynamicTLSModel;
  521. case CodeGenOptions::InitialExecTLSModel:
  522. return llvm::GlobalVariable::InitialExecTLSModel;
  523. case CodeGenOptions::LocalExecTLSModel:
  524. return llvm::GlobalVariable::LocalExecTLSModel;
  525. }
  526. llvm_unreachable("Invalid TLS model!");
  527. }
  528. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  529. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  530. llvm::GlobalValue::ThreadLocalMode TLM;
  531. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  532. // Override the TLS model if it is explicitly specified.
  533. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  534. TLM = GetLLVMTLSModel(Attr->getModel());
  535. }
  536. GV->setThreadLocalMode(TLM);
  537. }
  538. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  539. StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
  540. if (!FoundStr.empty())
  541. return FoundStr;
  542. const auto *ND = cast<NamedDecl>(GD.getDecl());
  543. // HLSL Change Starts
  544. if (ND->getKind() == Decl::Function &&
  545. ND->getNameAsString() == CodeGenOpts.HLSLEntryFunction) {
  546. return CodeGenOpts.HLSLEntryFunction;
  547. }
  548. // HLSL Change Ends
  549. SmallString<256> Buffer;
  550. StringRef Str;
  551. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  552. llvm::raw_svector_ostream Out(Buffer);
  553. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  554. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  555. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  556. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  557. else
  558. getCXXABI().getMangleContext().mangleName(ND, Out);
  559. Str = Out.str();
  560. } else {
  561. IdentifierInfo *II = ND->getIdentifier();
  562. assert(II && "Attempt to mangle unnamed decl.");
  563. Str = II->getName();
  564. }
  565. // Keep the first result in the case of a mangling collision.
  566. auto Result = Manglings.insert(std::make_pair(Str, GD));
  567. return FoundStr = Result.first->first();
  568. }
  569. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  570. const BlockDecl *BD) {
  571. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  572. const Decl *D = GD.getDecl();
  573. SmallString<256> Buffer;
  574. llvm::raw_svector_ostream Out(Buffer);
  575. if (!D)
  576. MangleCtx.mangleGlobalBlock(BD,
  577. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  578. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  579. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  580. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  581. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  582. else
  583. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  584. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  585. return Result.first->first();
  586. }
  587. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  588. return getModule().getNamedValue(Name);
  589. }
  590. /// AddGlobalCtor - Add a function to the list that will be called before
  591. /// main() runs.
  592. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  593. llvm::Constant *AssociatedData) {
  594. // FIXME: Type coercion of void()* types.
  595. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  596. }
  597. /// AddGlobalDtor - Add a function to the list that will be called
  598. /// when the module is unloaded.
  599. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  600. // FIXME: Type coercion of void()* types.
  601. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  602. }
  603. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  604. // Ctor function type is void()*.
  605. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  606. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  607. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  608. llvm::StructType *CtorStructTy = llvm::StructType::get(
  609. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  610. // Construct the constructor and destructor arrays.
  611. SmallVector<llvm::Constant *, 8> Ctors;
  612. for (const auto &I : Fns) {
  613. llvm::Constant *S[] = {
  614. llvm::ConstantInt::get(Int32Ty, I.Priority, false),
  615. llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
  616. (I.AssociatedData
  617. ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
  618. : llvm::Constant::getNullValue(VoidPtrTy))};
  619. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  620. }
  621. if (!Ctors.empty()) {
  622. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  623. new llvm::GlobalVariable(TheModule, AT, false,
  624. llvm::GlobalValue::AppendingLinkage,
  625. llvm::ConstantArray::get(AT, Ctors),
  626. GlobalName);
  627. }
  628. }
  629. llvm::GlobalValue::LinkageTypes
  630. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  631. const auto *D = cast<FunctionDecl>(GD.getDecl());
  632. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  633. if (isa<CXXDestructorDecl>(D) &&
  634. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  635. GD.getDtorType())) {
  636. // Destructor variants in the Microsoft C++ ABI are always internal or
  637. // linkonce_odr thunks emitted on an as-needed basis.
  638. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  639. : llvm::GlobalValue::LinkOnceODRLinkage;
  640. }
  641. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  642. }
  643. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  644. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  645. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  646. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  647. // Don't dllexport/import destructor thunks.
  648. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  649. return;
  650. }
  651. }
  652. if (FD->hasAttr<DLLImportAttr>())
  653. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  654. else if (FD->hasAttr<DLLExportAttr>())
  655. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  656. else
  657. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  658. }
  659. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  660. llvm::Function *F) {
  661. setNonAliasAttributes(D, F);
  662. }
  663. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  664. const CGFunctionInfo &Info,
  665. llvm::Function *F) {
  666. unsigned CallingConv;
  667. AttributeListType AttributeList;
  668. ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
  669. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  670. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  671. // HLSL Change Begins
  672. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  673. getHLSLRuntime().AddHLSLFunctionInfo(F, FD);
  674. // HLSL Change Ends
  675. }
  676. /// Determines whether the language options require us to model
  677. /// unwind exceptions. We treat -fexceptions as mandating this
  678. /// except under the fragile ObjC ABI with only ObjC exceptions
  679. /// enabled. This means, for example, that C with -fexceptions
  680. /// enables this.
  681. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  682. // If exceptions are completely disabled, obviously this is false.
  683. if (!LangOpts.Exceptions) return false;
  684. // If C++ exceptions are enabled, this is true.
  685. if (LangOpts.CXXExceptions) return true;
  686. // If ObjC exceptions are enabled, this depends on the ABI.
  687. if (LangOpts.ObjCExceptions) {
  688. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  689. }
  690. return true;
  691. }
  692. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  693. llvm::Function *F) {
  694. llvm::AttrBuilder B;
  695. if (CodeGenOpts.UnwindTables)
  696. B.addAttribute(llvm::Attribute::UWTable);
  697. if (!hasUnwindExceptions(LangOpts))
  698. B.addAttribute(llvm::Attribute::NoUnwind);
  699. if (D->hasAttr<NakedAttr>()) {
  700. // Naked implies noinline: we should not be inlining such functions.
  701. B.addAttribute(llvm::Attribute::Naked);
  702. B.addAttribute(llvm::Attribute::NoInline);
  703. } else if (D->hasAttr<NoDuplicateAttr>()) {
  704. B.addAttribute(llvm::Attribute::NoDuplicate);
  705. } else if (D->hasAttr<NoInlineAttr>()) {
  706. B.addAttribute(llvm::Attribute::NoInline);
  707. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  708. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  709. llvm::Attribute::NoInline)) {
  710. // (noinline wins over always_inline, and we can't specify both in IR)
  711. B.addAttribute(llvm::Attribute::AlwaysInline);
  712. }
  713. if (D->hasAttr<ColdAttr>()) {
  714. if (!D->hasAttr<OptimizeNoneAttr>())
  715. B.addAttribute(llvm::Attribute::OptimizeForSize);
  716. B.addAttribute(llvm::Attribute::Cold);
  717. }
  718. if (D->hasAttr<MinSizeAttr>())
  719. B.addAttribute(llvm::Attribute::MinSize);
  720. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  721. B.addAttribute(llvm::Attribute::StackProtect);
  722. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  723. B.addAttribute(llvm::Attribute::StackProtectStrong);
  724. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  725. B.addAttribute(llvm::Attribute::StackProtectReq);
  726. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  727. llvm::AttributeSet::get(
  728. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  729. if (D->hasAttr<OptimizeNoneAttr>()) {
  730. // OptimizeNone implies noinline; we should not be inlining such functions.
  731. F->addFnAttr(llvm::Attribute::OptimizeNone);
  732. F->addFnAttr(llvm::Attribute::NoInline);
  733. // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
  734. assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
  735. "OptimizeNone and OptimizeForSize on same function!");
  736. assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
  737. "OptimizeNone and MinSize on same function!");
  738. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  739. "OptimizeNone and AlwaysInline on same function!");
  740. // Attribute 'inlinehint' has no effect on 'optnone' functions.
  741. // Explicitly remove it from the set of function attributes.
  742. F->removeFnAttr(llvm::Attribute::InlineHint);
  743. }
  744. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  745. F->setUnnamedAddr(true);
  746. else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
  747. if (MD->isVirtual())
  748. F->setUnnamedAddr(true);
  749. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  750. if (alignment)
  751. F->setAlignment(alignment);
  752. // C++ ABI requires 2-byte alignment for member functions.
  753. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  754. F->setAlignment(2);
  755. }
  756. void CodeGenModule::SetCommonAttributes(const Decl *D,
  757. llvm::GlobalValue *GV) {
  758. if (const auto *ND = dyn_cast<NamedDecl>(D))
  759. setGlobalVisibility(GV, ND);
  760. else
  761. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  762. if (D->hasAttr<UsedAttr>())
  763. addUsedGlobal(GV);
  764. }
  765. void CodeGenModule::setAliasAttributes(const Decl *D,
  766. llvm::GlobalValue *GV) {
  767. SetCommonAttributes(D, GV);
  768. // Process the dllexport attribute based on whether the original definition
  769. // (not necessarily the aliasee) was exported.
  770. if (D->hasAttr<DLLExportAttr>())
  771. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  772. }
  773. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  774. llvm::GlobalObject *GO) {
  775. SetCommonAttributes(D, GO);
  776. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  777. GO->setSection(SA->getName());
  778. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  779. }
  780. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  781. llvm::Function *F,
  782. const CGFunctionInfo &FI) {
  783. SetLLVMFunctionAttributes(D, FI, F);
  784. SetLLVMFunctionAttributesForDefinition(D, F);
  785. F->setLinkage(llvm::Function::InternalLinkage);
  786. setNonAliasAttributes(D, F);
  787. }
  788. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  789. const NamedDecl *ND) {
  790. // Set linkage and visibility in case we never see a definition.
  791. LinkageInfo LV = ND->getLinkageAndVisibility();
  792. if (LV.getLinkage() != ExternalLinkage) {
  793. // Don't set internal linkage on declarations.
  794. } else {
  795. if (ND->hasAttr<DLLImportAttr>()) {
  796. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  797. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  798. } else if (ND->hasAttr<DLLExportAttr>()) {
  799. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  800. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  801. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  802. // "extern_weak" is overloaded in LLVM; we probably should have
  803. // separate linkage types for this.
  804. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  805. }
  806. // Set visibility on a declaration only if it's explicit.
  807. if (LV.isVisibilityExplicit())
  808. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  809. }
  810. }
  811. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  812. bool IsIncompleteFunction,
  813. bool IsThunk) {
  814. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  815. // If this is an intrinsic function, set the function's attributes
  816. // to the intrinsic's attributes.
  817. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  818. return;
  819. }
  820. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  821. if (!IsIncompleteFunction)
  822. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  823. // Add the Returned attribute for "this", except for iOS 5 and earlier
  824. // where substantial code, including the libstdc++ dylib, was compiled with
  825. // GCC and does not actually return "this".
  826. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  827. !(getTarget().getTriple().isiOS() &&
  828. getTarget().getTriple().isOSVersionLT(6))) {
  829. assert(!F->arg_empty() &&
  830. F->arg_begin()->getType()
  831. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  832. "unexpected this return");
  833. F->addAttribute(1, llvm::Attribute::Returned);
  834. }
  835. // Only a few attributes are set on declarations; these may later be
  836. // overridden by a definition.
  837. setLinkageAndVisibilityForGV(F, FD);
  838. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  839. F->setSection(SA->getName());
  840. // A replaceable global allocation function does not act like a builtin by
  841. // default, only if it is invoked by a new-expression or delete-expression.
  842. if (FD->isReplaceableGlobalAllocationFunction())
  843. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  844. llvm::Attribute::NoBuiltin);
  845. }
  846. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  847. assert(!GV->isDeclaration() &&
  848. "Only globals with definition can force usage.");
  849. LLVMUsed.emplace_back(GV);
  850. }
  851. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  852. assert(!GV->isDeclaration() &&
  853. "Only globals with definition can force usage.");
  854. LLVMCompilerUsed.emplace_back(GV);
  855. }
  856. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  857. std::vector<llvm::WeakVH> &List) {
  858. // Don't create llvm.used if there is no need.
  859. if (List.empty())
  860. return;
  861. // Convert List to what ConstantArray needs.
  862. SmallVector<llvm::Constant*, 8> UsedArray;
  863. UsedArray.resize(List.size());
  864. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  865. UsedArray[i] =
  866. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  867. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  868. }
  869. if (UsedArray.empty())
  870. return;
  871. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  872. auto *GV = new llvm::GlobalVariable(
  873. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  874. llvm::ConstantArray::get(ATy, UsedArray), Name);
  875. GV->setSection("llvm.metadata");
  876. }
  877. void CodeGenModule::emitLLVMUsed() {
  878. emitUsed(*this, "llvm.used", LLVMUsed);
  879. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  880. }
  881. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  882. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  883. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  884. }
  885. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  886. llvm::SmallString<32> Opt;
  887. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  888. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  889. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  890. }
  891. void CodeGenModule::AddDependentLib(StringRef Lib) {
  892. llvm::SmallString<24> Opt;
  893. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  894. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  895. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  896. }
  897. /// \brief Add link options implied by the given module, including modules
  898. /// it depends on, using a postorder walk.
  899. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  900. SmallVectorImpl<llvm::Metadata *> &Metadata,
  901. llvm::SmallPtrSet<Module *, 16> &Visited) {
  902. // Import this module's parent.
  903. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  904. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  905. }
  906. // Import this module's dependencies.
  907. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  908. if (Visited.insert(Mod->Imports[I - 1]).second)
  909. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  910. }
  911. // Add linker options to link against the libraries/frameworks
  912. // described by this module.
  913. llvm::LLVMContext &Context = CGM.getLLVMContext();
  914. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  915. // Link against a framework. Frameworks are currently Darwin only, so we
  916. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  917. if (Mod->LinkLibraries[I-1].IsFramework) {
  918. llvm::Metadata *Args[2] = {
  919. llvm::MDString::get(Context, "-framework"),
  920. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  921. Metadata.push_back(llvm::MDNode::get(Context, Args));
  922. continue;
  923. }
  924. // Link against a library.
  925. llvm::SmallString<24> Opt;
  926. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  927. Mod->LinkLibraries[I-1].Library, Opt);
  928. auto *OptString = llvm::MDString::get(Context, Opt);
  929. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  930. }
  931. }
  932. void CodeGenModule::EmitModuleLinkOptions() {
  933. // Collect the set of all of the modules we want to visit to emit link
  934. // options, which is essentially the imported modules and all of their
  935. // non-explicit child modules.
  936. llvm::SetVector<clang::Module *> LinkModules;
  937. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  938. SmallVector<clang::Module *, 16> Stack;
  939. // Seed the stack with imported modules.
  940. for (Module *M : ImportedModules)
  941. if (Visited.insert(M).second)
  942. Stack.push_back(M);
  943. // Find all of the modules to import, making a little effort to prune
  944. // non-leaf modules.
  945. while (!Stack.empty()) {
  946. clang::Module *Mod = Stack.pop_back_val();
  947. bool AnyChildren = false;
  948. // Visit the submodules of this module.
  949. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  950. SubEnd = Mod->submodule_end();
  951. Sub != SubEnd; ++Sub) {
  952. // Skip explicit children; they need to be explicitly imported to be
  953. // linked against.
  954. if ((*Sub)->IsExplicit)
  955. continue;
  956. if (Visited.insert(*Sub).second) {
  957. Stack.push_back(*Sub);
  958. AnyChildren = true;
  959. }
  960. }
  961. // We didn't find any children, so add this module to the list of
  962. // modules to link against.
  963. if (!AnyChildren) {
  964. LinkModules.insert(Mod);
  965. }
  966. }
  967. // Add link options for all of the imported modules in reverse topological
  968. // order. We don't do anything to try to order import link flags with respect
  969. // to linker options inserted by things like #pragma comment().
  970. SmallVector<llvm::Metadata *, 16> MetadataArgs;
  971. Visited.clear();
  972. for (Module *M : LinkModules)
  973. if (Visited.insert(M).second)
  974. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  975. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  976. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  977. // Add the linker options metadata flag.
  978. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  979. llvm::MDNode::get(getLLVMContext(),
  980. LinkerOptionsMetadata));
  981. }
  982. void CodeGenModule::EmitDeferred() {
  983. // Emit code for any potentially referenced deferred decls. Since a
  984. // previously unused static decl may become used during the generation of code
  985. // for a static function, iterate until no changes are made.
  986. if (!DeferredVTables.empty()) {
  987. EmitDeferredVTables();
  988. // Emitting a v-table doesn't directly cause more v-tables to
  989. // become deferred, although it can cause functions to be
  990. // emitted that then need those v-tables.
  991. assert(DeferredVTables.empty());
  992. }
  993. // Stop if we're out of both deferred v-tables and deferred declarations.
  994. if (DeferredDeclsToEmit.empty())
  995. return;
  996. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  997. // work, it will not interfere with this.
  998. std::vector<DeferredGlobal> CurDeclsToEmit;
  999. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1000. for (DeferredGlobal &G : CurDeclsToEmit) {
  1001. GlobalDecl D = G.GD;
  1002. llvm::GlobalValue *GV = G.GV;
  1003. G.GV = nullptr;
  1004. assert(!GV || GV == GetGlobalValue(getMangledName(D)));
  1005. if (!GV)
  1006. GV = GetGlobalValue(getMangledName(D));
  1007. // Check to see if we've already emitted this. This is necessary
  1008. // for a couple of reasons: first, decls can end up in the
  1009. // deferred-decls queue multiple times, and second, decls can end
  1010. // up with definitions in unusual ways (e.g. by an extern inline
  1011. // function acquiring a strong function redefinition). Just
  1012. // ignore these cases.
  1013. if (GV && !GV->isDeclaration())
  1014. continue;
  1015. // Otherwise, emit the definition and move on to the next one.
  1016. EmitGlobalDefinition(D, GV);
  1017. // If we found out that we need to emit more decls, do that recursively.
  1018. // This has the advantage that the decls are emitted in a DFS and related
  1019. // ones are close together, which is convenient for testing.
  1020. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1021. EmitDeferred();
  1022. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1023. }
  1024. }
  1025. }
  1026. void CodeGenModule::EmitGlobalAnnotations() {
  1027. if (Annotations.empty())
  1028. return;
  1029. // Create a new global variable for the ConstantStruct in the Module.
  1030. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1031. Annotations[0]->getType(), Annotations.size()), Annotations);
  1032. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1033. llvm::GlobalValue::AppendingLinkage,
  1034. Array, "llvm.global.annotations");
  1035. gv->setSection(AnnotationSection);
  1036. }
  1037. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1038. llvm::Constant *&AStr = AnnotationStrings[Str];
  1039. if (AStr)
  1040. return AStr;
  1041. // Not found yet, create a new global.
  1042. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1043. auto *gv =
  1044. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1045. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1046. gv->setSection(AnnotationSection);
  1047. gv->setUnnamedAddr(true);
  1048. AStr = gv;
  1049. return gv;
  1050. }
  1051. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1052. SourceManager &SM = getContext().getSourceManager();
  1053. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1054. if (PLoc.isValid())
  1055. return EmitAnnotationString(PLoc.getFilename());
  1056. return EmitAnnotationString(SM.getBufferName(Loc));
  1057. }
  1058. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1059. SourceManager &SM = getContext().getSourceManager();
  1060. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1061. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1062. SM.getExpansionLineNumber(L);
  1063. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1064. }
  1065. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1066. const AnnotateAttr *AA,
  1067. SourceLocation L) {
  1068. // Get the globals for file name, annotation, and the line number.
  1069. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1070. *UnitGV = EmitAnnotationUnit(L),
  1071. *LineNoCst = EmitAnnotationLineNo(L);
  1072. // Create the ConstantStruct for the global annotation.
  1073. llvm::Constant *Fields[4] = {
  1074. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1075. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1076. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1077. LineNoCst
  1078. };
  1079. return llvm::ConstantStruct::getAnon(Fields);
  1080. }
  1081. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1082. llvm::GlobalValue *GV) {
  1083. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1084. // Get the struct elements for these annotations.
  1085. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1086. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1087. }
  1088. bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
  1089. SourceLocation Loc) const {
  1090. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1091. // Blacklist by function name.
  1092. if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
  1093. return true;
  1094. // Blacklist by location.
  1095. if (!Loc.isInvalid())
  1096. return SanitizerBL.isBlacklistedLocation(Loc);
  1097. // If location is unknown, this may be a compiler-generated function. Assume
  1098. // it's located in the main file.
  1099. auto &SM = Context.getSourceManager();
  1100. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1101. return SanitizerBL.isBlacklistedFile(MainFile->getName());
  1102. }
  1103. return false;
  1104. }
  1105. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1106. SourceLocation Loc, QualType Ty,
  1107. StringRef Category) const {
  1108. // For now globals can be blacklisted only in ASan and KASan.
  1109. if (!LangOpts.Sanitize.hasOneOf(
  1110. SanitizerKind::Address | SanitizerKind::KernelAddress))
  1111. return false;
  1112. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1113. if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
  1114. return true;
  1115. if (SanitizerBL.isBlacklistedLocation(Loc, Category))
  1116. return true;
  1117. // Check global type.
  1118. if (!Ty.isNull()) {
  1119. // Drill down the array types: if global variable of a fixed type is
  1120. // blacklisted, we also don't instrument arrays of them.
  1121. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1122. Ty = AT->getElementType();
  1123. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1124. // We allow to blacklist only record types (classes, structs etc.)
  1125. if (Ty->isRecordType()) {
  1126. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1127. if (SanitizerBL.isBlacklistedType(TypeStr, Category))
  1128. return true;
  1129. }
  1130. }
  1131. return false;
  1132. }
  1133. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1134. // Never defer when EmitAllDecls is specified.
  1135. if (LangOpts.EmitAllDecls)
  1136. return true;
  1137. return getContext().DeclMustBeEmitted(Global);
  1138. }
  1139. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1140. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1141. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1142. // Implicit template instantiations may change linkage if they are later
  1143. // explicitly instantiated, so they should not be emitted eagerly.
  1144. return false;
  1145. // OACR error 6287
  1146. #pragma prefast(disable: __WARNING_ZEROLOGICALANDLOSINGSIDEEFFECTS, "language options are constants, by design")
  1147. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1148. // codegen for global variables, because they may be marked as threadprivate.
  1149. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1150. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1151. return false;
  1152. return true;
  1153. }
  1154. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  1155. const CXXUuidofExpr* E) {
  1156. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1157. // well-formed.
  1158. StringRef Uuid = E->getUuidAsStringRef(Context);
  1159. std::string Name = "_GUID_" + Uuid.lower();
  1160. std::replace(Name.begin(), Name.end(), '-', '_');
  1161. // Look for an existing global.
  1162. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1163. return GV;
  1164. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1165. assert(Init && "failed to initialize as constant");
  1166. auto *GV = new llvm::GlobalVariable(
  1167. getModule(), Init->getType(),
  1168. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1169. if (supportsCOMDAT())
  1170. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1171. return GV;
  1172. }
  1173. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1174. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1175. assert(AA && "No alias?");
  1176. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1177. // See if there is already something with the target's name in the module.
  1178. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1179. if (Entry) {
  1180. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1181. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1182. }
  1183. llvm::Constant *Aliasee;
  1184. if (isa<llvm::FunctionType>(DeclTy))
  1185. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1186. GlobalDecl(cast<FunctionDecl>(VD)),
  1187. /*ForVTable=*/false);
  1188. else
  1189. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1190. llvm::PointerType::getUnqual(DeclTy),
  1191. nullptr);
  1192. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1193. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1194. WeakRefReferences.insert(F);
  1195. return Aliasee;
  1196. }
  1197. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1198. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1199. // Weak references don't produce any output by themselves.
  1200. if (Global->hasAttr<WeakRefAttr>())
  1201. return;
  1202. // If this is an alias definition (which otherwise looks like a declaration)
  1203. // emit it now.
  1204. if (Global->hasAttr<AliasAttr>())
  1205. return EmitAliasDefinition(GD);
  1206. // If this is CUDA, be selective about which declarations we emit.
  1207. if (LangOpts.CUDA) {
  1208. if (LangOpts.CUDAIsDevice) {
  1209. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1210. !Global->hasAttr<CUDAGlobalAttr>() &&
  1211. !Global->hasAttr<CUDAConstantAttr>() &&
  1212. !Global->hasAttr<CUDASharedAttr>())
  1213. return;
  1214. } else {
  1215. if (!Global->hasAttr<CUDAHostAttr>() && (
  1216. Global->hasAttr<CUDADeviceAttr>() ||
  1217. Global->hasAttr<CUDAConstantAttr>() ||
  1218. Global->hasAttr<CUDASharedAttr>()))
  1219. return;
  1220. }
  1221. }
  1222. // Ignore declarations, they will be emitted on their first use.
  1223. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1224. // Forward declarations are emitted lazily on first use.
  1225. if (!FD->doesThisDeclarationHaveABody()) {
  1226. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1227. return;
  1228. StringRef MangledName = getMangledName(GD);
  1229. // Compute the function info and LLVM type.
  1230. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1231. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1232. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1233. /*DontDefer=*/false);
  1234. return;
  1235. }
  1236. } else {
  1237. const auto *VD = cast<VarDecl>(Global);
  1238. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1239. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1240. !Context.isMSStaticDataMemberInlineDefinition(VD))
  1241. return;
  1242. }
  1243. // Defer code generation to first use when possible, e.g. if this is an inline
  1244. // function. If the global must always be emitted, do it eagerly if possible
  1245. // to benefit from cache locality.
  1246. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1247. // Emit the definition if it can't be deferred.
  1248. EmitGlobalDefinition(GD);
  1249. return;
  1250. }
  1251. // If we're deferring emission of a C++ variable with an
  1252. // initializer, remember the order in which it appeared in the file.
  1253. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1254. cast<VarDecl>(Global)->hasInit()) {
  1255. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1256. CXXGlobalInits.push_back(nullptr);
  1257. }
  1258. StringRef MangledName = getMangledName(GD);
  1259. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
  1260. // The value has already been used and should therefore be emitted.
  1261. addDeferredDeclToEmit(GV, GD);
  1262. } else if (MustBeEmitted(Global)) {
  1263. // The value must be emitted, but cannot be emitted eagerly.
  1264. assert(!MayBeEmittedEagerly(Global));
  1265. addDeferredDeclToEmit(/*GV=*/nullptr, GD);
  1266. } else {
  1267. // Otherwise, remember that we saw a deferred decl with this name. The
  1268. // first use of the mangled name will cause it to move into
  1269. // DeferredDeclsToEmit.
  1270. DeferredDecls[MangledName] = GD;
  1271. }
  1272. }
  1273. namespace {
  1274. struct FunctionIsDirectlyRecursive :
  1275. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1276. const StringRef Name;
  1277. const Builtin::Context &BI;
  1278. bool Result;
  1279. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1280. Name(N), BI(C), Result(false) {
  1281. }
  1282. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1283. bool TraverseCallExpr(CallExpr *E) {
  1284. const FunctionDecl *FD = E->getDirectCallee();
  1285. if (!FD)
  1286. return true;
  1287. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1288. if (Attr && Name == Attr->getLabel()) {
  1289. Result = true;
  1290. return false;
  1291. }
  1292. unsigned BuiltinID = FD->getBuiltinID();
  1293. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1294. return true;
  1295. StringRef BuiltinName = BI.GetName(BuiltinID);
  1296. if (BuiltinName.startswith("__builtin_") &&
  1297. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1298. Result = true;
  1299. return false;
  1300. }
  1301. return true;
  1302. }
  1303. };
  1304. }
  1305. // isTriviallyRecursive - Check if this function calls another
  1306. // decl that, because of the asm attribute or the other decl being a builtin,
  1307. // ends up pointing to itself.
  1308. bool
  1309. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1310. StringRef Name;
  1311. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1312. // asm labels are a special kind of mangling we have to support.
  1313. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1314. if (!Attr)
  1315. return false;
  1316. Name = Attr->getLabel();
  1317. } else {
  1318. Name = FD->getName();
  1319. }
  1320. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1321. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1322. return Walker.Result;
  1323. }
  1324. bool
  1325. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1326. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1327. return true;
  1328. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1329. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1330. return false;
  1331. // PR9614. Avoid cases where the source code is lying to us. An available
  1332. // externally function should have an equivalent function somewhere else,
  1333. // but a function that calls itself is clearly not equivalent to the real
  1334. // implementation.
  1335. // This happens in glibc's btowc and in some configure checks.
  1336. return !isTriviallyRecursive(F);
  1337. }
  1338. /// If the type for the method's class was generated by
  1339. /// CGDebugInfo::createContextChain(), the cache contains only a
  1340. /// limited DIType without any declarations. Since EmitFunctionStart()
  1341. /// needs to find the canonical declaration for each method, we need
  1342. /// to construct the complete type prior to emitting the method.
  1343. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1344. if (!D->isInstance())
  1345. return;
  1346. if (CGDebugInfo *DI = getModuleDebugInfo())
  1347. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  1348. const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
  1349. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1350. }
  1351. }
  1352. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1353. const auto *D = cast<ValueDecl>(GD.getDecl());
  1354. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1355. Context.getSourceManager(),
  1356. "Generating code for declaration");
  1357. if (isa<FunctionDecl>(D)) {
  1358. // At -O0, don't generate IR for functions with available_externally
  1359. // linkage.
  1360. if (!shouldEmitFunction(GD))
  1361. return;
  1362. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1363. CompleteDIClassType(Method);
  1364. // Make sure to emit the definition(s) before we emit the thunks.
  1365. // This is necessary for the generation of certain thunks.
  1366. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1367. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1368. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1369. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1370. else
  1371. EmitGlobalFunctionDefinition(GD, GV);
  1372. if (Method->isVirtual())
  1373. getVTables().EmitThunks(GD);
  1374. return;
  1375. }
  1376. return EmitGlobalFunctionDefinition(GD, GV);
  1377. }
  1378. if (const auto *VD = dyn_cast<VarDecl>(D))
  1379. return EmitGlobalVarDefinition(VD);
  1380. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1381. }
  1382. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1383. /// module, create and return an llvm Function with the specified type. If there
  1384. /// is something in the module with the specified name, return it potentially
  1385. /// bitcasted to the right type.
  1386. ///
  1387. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1388. /// to set the attributes on the function when it is first created.
  1389. llvm::Constant *
  1390. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1391. llvm::Type *Ty,
  1392. GlobalDecl GD, bool ForVTable,
  1393. bool DontDefer, bool IsThunk,
  1394. llvm::AttributeSet ExtraAttrs) {
  1395. const Decl *D = GD.getDecl();
  1396. // Lookup the entry, lazily creating it if necessary.
  1397. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1398. if (Entry) {
  1399. if (WeakRefReferences.erase(Entry)) {
  1400. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1401. if (FD && !FD->hasAttr<WeakAttr>())
  1402. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1403. }
  1404. // Handle dropped DLL attributes.
  1405. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1406. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1407. if (Entry->getType()->getElementType() == Ty)
  1408. return Entry;
  1409. // Make sure the result is of the correct type.
  1410. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1411. }
  1412. // This function doesn't have a complete type (for example, the return
  1413. // type is an incomplete struct). Use a fake type instead, and make
  1414. // sure not to try to set attributes.
  1415. bool IsIncompleteFunction = false;
  1416. llvm::FunctionType *FTy;
  1417. if (isa<llvm::FunctionType>(Ty)) {
  1418. FTy = cast<llvm::FunctionType>(Ty);
  1419. } else {
  1420. FTy = llvm::FunctionType::get(VoidTy, false);
  1421. IsIncompleteFunction = true;
  1422. }
  1423. // HLSL Change: unique_ptr for F
  1424. llvm::Function *F = llvm::Function::Create(FTy,
  1425. llvm::Function::ExternalLinkage,
  1426. MangledName, &getModule());
  1427. assert(F->getName() == MangledName && "name was uniqued!");
  1428. if (D)
  1429. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  1430. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1431. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1432. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1433. llvm::AttributeSet::get(VMContext,
  1434. llvm::AttributeSet::FunctionIndex,
  1435. B));
  1436. }
  1437. if (!DontDefer) {
  1438. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1439. // each other bottoming out with the base dtor. Therefore we emit non-base
  1440. // dtors on usage, even if there is no dtor definition in the TU.
  1441. if (D && isa<CXXDestructorDecl>(D) &&
  1442. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1443. GD.getDtorType()))
  1444. addDeferredDeclToEmit(F, GD);
  1445. // This is the first use or definition of a mangled name. If there is a
  1446. // deferred decl with this name, remember that we need to emit it at the end
  1447. // of the file.
  1448. auto DDI = DeferredDecls.find(MangledName);
  1449. if (DDI != DeferredDecls.end()) {
  1450. // Move the potentially referenced deferred decl to the
  1451. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1452. // don't need it anymore).
  1453. addDeferredDeclToEmit(F, DDI->second);
  1454. DeferredDecls.erase(DDI);
  1455. // Otherwise, there are cases we have to worry about where we're
  1456. // using a declaration for which we must emit a definition but where
  1457. // we might not find a top-level definition:
  1458. // - member functions defined inline in their classes
  1459. // - friend functions defined inline in some class
  1460. // - special member functions with implicit definitions
  1461. // If we ever change our AST traversal to walk into class methods,
  1462. // this will be unnecessary.
  1463. //
  1464. // We also don't emit a definition for a function if it's going to be an
  1465. // entry in a vtable, unless it's already marked as used.
  1466. } else if (getLangOpts().CPlusPlus && D) {
  1467. // Look for a declaration that's lexically in a record.
  1468. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1469. FD = FD->getPreviousDecl()) {
  1470. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1471. if (FD->doesThisDeclarationHaveABody()) {
  1472. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1473. break;
  1474. }
  1475. }
  1476. }
  1477. }
  1478. }
  1479. // Make sure the result is of the requested type.
  1480. if (!IsIncompleteFunction) {
  1481. assert(F->getType()->getElementType() == Ty);
  1482. return F;
  1483. }
  1484. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1485. return llvm::ConstantExpr::getBitCast(F, PTy);
  1486. }
  1487. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1488. /// non-null, then this function will use the specified type if it has to
  1489. /// create it (this occurs when we see a definition of the function).
  1490. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1491. llvm::Type *Ty,
  1492. bool ForVTable,
  1493. bool DontDefer) {
  1494. // If there was no specific requested type, just convert it now.
  1495. if (!Ty)
  1496. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1497. StringRef MangledName = getMangledName(GD);
  1498. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
  1499. }
  1500. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1501. /// type and name.
  1502. llvm::Constant *
  1503. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1504. StringRef Name,
  1505. llvm::AttributeSet ExtraAttrs) {
  1506. llvm::Constant *C =
  1507. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1508. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1509. if (auto *F = dyn_cast<llvm::Function>(C))
  1510. if (F->empty())
  1511. F->setCallingConv(getRuntimeCC());
  1512. return C;
  1513. }
  1514. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1515. /// type and name.
  1516. llvm::Constant *
  1517. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
  1518. StringRef Name,
  1519. llvm::AttributeSet ExtraAttrs) {
  1520. llvm::Constant *C =
  1521. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1522. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1523. if (auto *F = dyn_cast<llvm::Function>(C))
  1524. if (F->empty())
  1525. F->setCallingConv(getBuiltinCC());
  1526. return C;
  1527. }
  1528. /// isTypeConstant - Determine whether an object of this type can be emitted
  1529. /// as a constant.
  1530. ///
  1531. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1532. /// will not be considered. The caller will need to verify that the object is
  1533. /// not written to during its construction.
  1534. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1535. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1536. return false;
  1537. if (Context.getLangOpts().CPlusPlus) {
  1538. if (const CXXRecordDecl *Record
  1539. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1540. return ExcludeCtor && !Record->hasMutableFields() &&
  1541. Record->hasTrivialDestructor();
  1542. }
  1543. return true;
  1544. }
  1545. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1546. /// create and return an llvm GlobalVariable with the specified type. If there
  1547. /// is something in the module with the specified name, return it potentially
  1548. /// bitcasted to the right type.
  1549. ///
  1550. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1551. /// to set the attributes on the global when it is first created.
  1552. llvm::Constant *
  1553. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1554. llvm::PointerType *Ty,
  1555. const VarDecl *D) {
  1556. // Lookup the entry, lazily creating it if necessary.
  1557. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1558. if (Entry) {
  1559. if (WeakRefReferences.erase(Entry)) {
  1560. if (D && !D->hasAttr<WeakAttr>())
  1561. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1562. }
  1563. // Handle dropped DLL attributes.
  1564. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1565. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1566. if (Entry->getType() == Ty)
  1567. return Entry;
  1568. // Make sure the result is of the correct type.
  1569. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  1570. // HLSL Change Begins
  1571. // TODO: do we put address space in type?
  1572. if (LangOpts.HLSL) return Entry;
  1573. else
  1574. // HLSL Change Ends
  1575. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1576. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1577. }
  1578. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1579. auto *GV = new llvm::GlobalVariable(
  1580. getModule(), Ty->getElementType(), false,
  1581. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1582. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1583. // This is the first use or definition of a mangled name. If there is a
  1584. // deferred decl with this name, remember that we need to emit it at the end
  1585. // of the file.
  1586. auto DDI = DeferredDecls.find(MangledName);
  1587. if (DDI != DeferredDecls.end()) {
  1588. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1589. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1590. addDeferredDeclToEmit(GV, DDI->second);
  1591. DeferredDecls.erase(DDI);
  1592. }
  1593. // Handle things which are present even on external declarations.
  1594. if (D) {
  1595. // FIXME: This code is overly simple and should be merged with other global
  1596. // handling.
  1597. GV->setConstant(isTypeConstant(D->getType(), false));
  1598. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1599. setLinkageAndVisibilityForGV(GV, D);
  1600. if (D->getTLSKind()) {
  1601. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1602. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1603. setTLSMode(GV, *D);
  1604. }
  1605. // If required by the ABI, treat declarations of static data members with
  1606. // inline initializers as definitions.
  1607. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  1608. EmitGlobalVarDefinition(D);
  1609. }
  1610. // Handle XCore specific ABI requirements.
  1611. if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
  1612. D->getLanguageLinkage() == CLanguageLinkage &&
  1613. D->getType().isConstant(Context) &&
  1614. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  1615. GV->setSection(".cp.rodata");
  1616. }
  1617. if (AddrSpace != Ty->getAddressSpace() && !LangOpts.HLSL) // HLSL Change -TODO: do we put address space in type?
  1618. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  1619. return GV;
  1620. }
  1621. llvm::GlobalVariable *
  1622. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1623. llvm::Type *Ty,
  1624. llvm::GlobalValue::LinkageTypes Linkage) {
  1625. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1626. llvm::GlobalVariable *OldGV = nullptr;
  1627. if (GV) {
  1628. // Check if the variable has the right type.
  1629. if (GV->getType()->getElementType() == Ty)
  1630. return GV;
  1631. // Because C++ name mangling, the only way we can end up with an already
  1632. // existing global with the same name is if it has been declared extern "C".
  1633. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1634. OldGV = GV;
  1635. }
  1636. // Create a new variable.
  1637. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1638. Linkage, nullptr, Name);
  1639. if (OldGV) {
  1640. // Replace occurrences of the old variable if needed.
  1641. GV->takeName(OldGV);
  1642. if (!OldGV->use_empty()) {
  1643. llvm::Constant *NewPtrForOldDecl =
  1644. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1645. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1646. }
  1647. OldGV->eraseFromParent();
  1648. }
  1649. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  1650. !GV->hasAvailableExternallyLinkage())
  1651. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1652. return GV;
  1653. }
  1654. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1655. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1656. /// then it will be created with the specified type instead of whatever the
  1657. /// normal requested type would be.
  1658. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1659. llvm::Type *Ty) {
  1660. assert(D->hasGlobalStorage() && "Not a global variable");
  1661. QualType ASTTy = D->getType();
  1662. if (!Ty)
  1663. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1664. llvm::PointerType *PTy =
  1665. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1666. StringRef MangledName = getMangledName(D);
  1667. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1668. }
  1669. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1670. /// specified type and name.
  1671. llvm::Constant *
  1672. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1673. StringRef Name) {
  1674. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  1675. }
  1676. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1677. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1678. if (!MustBeEmitted(D)) {
  1679. // If we have not seen a reference to this variable yet, place it
  1680. // into the deferred declarations table to be emitted if needed
  1681. // later.
  1682. StringRef MangledName = getMangledName(D);
  1683. if (!GetGlobalValue(MangledName)) {
  1684. DeferredDecls[MangledName] = D;
  1685. return;
  1686. }
  1687. }
  1688. // The tentative definition is the only definition.
  1689. EmitGlobalVarDefinition(D);
  1690. }
  1691. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1692. return Context.toCharUnitsFromBits(
  1693. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1694. }
  1695. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1696. unsigned AddrSpace) {
  1697. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  1698. if (D->hasAttr<CUDAConstantAttr>())
  1699. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1700. else if (D->hasAttr<CUDASharedAttr>())
  1701. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1702. else
  1703. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1704. }
  1705. // HLSL Change Begins
  1706. if (LangOpts.HLSL) {
  1707. if (D->hasAttr<HLSLGroupSharedAttr>())
  1708. AddrSpace = getContext().getTargetAddressSpace(hlsl::DXIL::kTGSMAddrSpace);
  1709. }
  1710. // HLSL Change Ends
  1711. return AddrSpace;
  1712. }
  1713. template<typename SomeDecl>
  1714. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  1715. llvm::GlobalValue *GV) {
  1716. if (!getLangOpts().CPlusPlus)
  1717. return;
  1718. // Must have 'used' attribute, or else inline assembly can't rely on
  1719. // the name existing.
  1720. if (!D->template hasAttr<UsedAttr>())
  1721. return;
  1722. // Must have internal linkage and an ordinary name.
  1723. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  1724. return;
  1725. // Must be in an extern "C" context. Entities declared directly within
  1726. // a record are not extern "C" even if the record is in such a context.
  1727. const SomeDecl *First = D->getFirstDecl();
  1728. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  1729. return;
  1730. // OK, this is an internal linkage entity inside an extern "C" linkage
  1731. // specification. Make a note of that so we can give it the "expected"
  1732. // mangled name if nothing else is using that name.
  1733. std::pair<StaticExternCMap::iterator, bool> R =
  1734. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  1735. // If we have multiple internal linkage entities with the same name
  1736. // in extern "C" regions, none of them gets that name.
  1737. if (!R.second)
  1738. R.first->second = nullptr;
  1739. }
  1740. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  1741. if (!CGM.supportsCOMDAT())
  1742. return false;
  1743. if (D.hasAttr<SelectAnyAttr>())
  1744. return true;
  1745. GVALinkage Linkage;
  1746. if (auto *VD = dyn_cast<VarDecl>(&D))
  1747. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  1748. else
  1749. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  1750. switch (Linkage) {
  1751. case GVA_Internal:
  1752. case GVA_AvailableExternally:
  1753. case GVA_StrongExternal:
  1754. return false;
  1755. case GVA_DiscardableODR:
  1756. case GVA_StrongODR:
  1757. return true;
  1758. }
  1759. llvm_unreachable("No such linkage");
  1760. }
  1761. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  1762. llvm::GlobalObject &GO) {
  1763. if (!shouldBeInCOMDAT(*this, D))
  1764. return;
  1765. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  1766. }
  1767. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1768. llvm::Constant *Init = nullptr;
  1769. QualType ASTTy = D->getType();
  1770. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1771. bool NeedsGlobalCtor = false;
  1772. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1773. const VarDecl *InitDecl;
  1774. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1775. if (!InitExpr) {
  1776. // This is a tentative definition; tentative definitions are
  1777. // implicitly initialized with { 0 }.
  1778. //
  1779. // Note that tentative definitions are only emitted at the end of
  1780. // a translation unit, so they should never have incomplete
  1781. // type. In addition, EmitTentativeDefinition makes sure that we
  1782. // never attempt to emit a tentative definition if a real one
  1783. // exists. A use may still exists, however, so we still may need
  1784. // to do a RAUW.
  1785. // HLSL Change Starts
  1786. // Allow incomplete type.
  1787. if (getLangOpts().HLSL && ASTTy->isIncompleteType()) {
  1788. if (hlsl::IsIncompleteHLSLResourceArrayType(getContext(), ASTTy)) {
  1789. llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
  1790. llvm::Constant *Entry = GetAddrOfGlobalVar(D, Ty);
  1791. // Entry is now either a Function or GlobalVariable.
  1792. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1793. // Emit global variable debug information.
  1794. if (CGDebugInfo *DI = getModuleDebugInfo())
  1795. if (getCodeGenOpts().getDebugInfo() >=
  1796. CodeGenOptions::LimitedDebugInfo)
  1797. DI->EmitGlobalVariable(GV, D);
  1798. return;
  1799. }
  1800. }
  1801. // HLSL Change Ends
  1802. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1803. Init = EmitNullConstant(D->getType());
  1804. } else {
  1805. initializedGlobalDecl = GlobalDecl(D);
  1806. Init = EmitConstantInit(*InitDecl);
  1807. if (!Init) {
  1808. QualType T = InitExpr->getType();
  1809. if (D->getType()->isReferenceType())
  1810. T = D->getType();
  1811. if (getLangOpts().CPlusPlus) {
  1812. Init = EmitNullConstant(T);
  1813. NeedsGlobalCtor = true;
  1814. // HLSL Change Begins.
  1815. if (getLangOpts().HLSL && D->isExternallyVisible()) {
  1816. // For global constant with init, the init will be ignored.
  1817. // Warning here.
  1818. unsigned DiagID = Diags.getCustomDiagID(
  1819. DiagnosticsEngine::Warning,
  1820. "Initializer of external global will be ignored");
  1821. Diags.Report(D->getLocation(), DiagID);
  1822. // Don't create global ctor for it.
  1823. NeedsGlobalCtor = false;
  1824. }
  1825. // HLSL Change Ends.
  1826. } else {
  1827. ErrorUnsupported(D, "static initializer");
  1828. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1829. }
  1830. } else {
  1831. // We don't need an initializer, so remove the entry for the delayed
  1832. // initializer position (just in case this entry was delayed) if we
  1833. // also don't need to register a destructor.
  1834. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1835. DelayedCXXInitPosition.erase(D);
  1836. // HLSL Change Begins.
  1837. if (getLangOpts().HLSL && D->isExternallyVisible() && !D->isStaticDataMember()) {
  1838. // For global constant with init, the init will be ignored.
  1839. Init = EmitNullConstant(D->getType());
  1840. unsigned DiagID = Diags.getCustomDiagID(
  1841. DiagnosticsEngine::Warning,
  1842. "Initializer of external global will be ignored");
  1843. Diags.Report(D->getLocation(), DiagID);
  1844. }
  1845. // HLSL Change Ends.
  1846. }
  1847. }
  1848. llvm::Type* InitType = Init->getType();
  1849. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1850. // Strip off a bitcast if we got one back.
  1851. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1852. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1853. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  1854. // All zero index gep.
  1855. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1856. Entry = CE->getOperand(0);
  1857. }
  1858. // Entry is now either a Function or GlobalVariable.
  1859. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1860. // We have a definition after a declaration with the wrong type.
  1861. // We must make a new GlobalVariable* and update everything that used OldGV
  1862. // (a declaration or tentative definition) with the new GlobalVariable*
  1863. // (which will be a definition).
  1864. //
  1865. // This happens if there is a prototype for a global (e.g.
  1866. // "extern int x[];") and then a definition of a different type (e.g.
  1867. // "int x[10];"). This also happens when an initializer has a different type
  1868. // from the type of the global (this happens with unions).
  1869. if (!GV ||
  1870. GV->getType()->getElementType() != InitType ||
  1871. GV->getType()->getAddressSpace() !=
  1872. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1873. // Move the old entry aside so that we'll create a new one.
  1874. Entry->setName(StringRef());
  1875. // Make a new global with the correct type, this is now guaranteed to work.
  1876. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1877. // Replace all uses of the old global with the new global
  1878. llvm::Constant *NewPtrForOldDecl =
  1879. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1880. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1881. // Erase the old global, since it is no longer used.
  1882. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1883. }
  1884. MaybeHandleStaticInExternC(D, GV);
  1885. if (D->hasAttr<AnnotateAttr>())
  1886. AddGlobalAnnotations(D, GV);
  1887. GV->setInitializer(Init);
  1888. // If it is safe to mark the global 'constant', do so now.
  1889. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1890. isTypeConstant(D->getType(), true));
  1891. // If it is in a read-only section, mark it 'constant'.
  1892. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  1893. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  1894. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  1895. GV->setConstant(true);
  1896. }
  1897. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1898. // Set the llvm linkage type as appropriate.
  1899. llvm::GlobalValue::LinkageTypes Linkage =
  1900. getLLVMLinkageVarDefinition(D, GV->isConstant());
  1901. // On Darwin, the backing variable for a C++11 thread_local variable always
  1902. // has internal linkage; all accesses should just be calls to the
  1903. // Itanium-specified entry point, which has the normal linkage of the
  1904. // variable.
  1905. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  1906. Context.getTargetInfo().getTriple().isMacOSX())
  1907. Linkage = llvm::GlobalValue::InternalLinkage;
  1908. GV->setLinkage(Linkage);
  1909. if (D->hasAttr<DLLImportAttr>())
  1910. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  1911. else if (D->hasAttr<DLLExportAttr>())
  1912. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  1913. else
  1914. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  1915. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1916. // common vars aren't constant even if declared const.
  1917. GV->setConstant(false);
  1918. setNonAliasAttributes(D, GV);
  1919. if (D->getTLSKind() && !GV->isThreadLocal()) {
  1920. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1921. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1922. setTLSMode(GV, *D);
  1923. }
  1924. maybeSetTrivialComdat(*D, *GV);
  1925. // Emit the initializer function if necessary.
  1926. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1927. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1928. // HLSL Change Begin.
  1929. if (NeedsGlobalCtor)
  1930. GV->setInitializer(llvm::UndefValue::get(InitType));
  1931. // HLSL Change End.
  1932. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  1933. // Emit global variable debug information.
  1934. if (CGDebugInfo *DI = getModuleDebugInfo())
  1935. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1936. DI->EmitGlobalVariable(GV, D);
  1937. }
  1938. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  1939. CodeGenModule &CGM, const VarDecl *D,
  1940. bool NoCommon) {
  1941. // Don't give variables common linkage if -fno-common was specified unless it
  1942. // was overridden by a NoCommon attribute.
  1943. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  1944. return true;
  1945. // C11 6.9.2/2:
  1946. // A declaration of an identifier for an object that has file scope without
  1947. // an initializer, and without a storage-class specifier or with the
  1948. // storage-class specifier static, constitutes a tentative definition.
  1949. if (D->getInit() || D->hasExternalStorage())
  1950. return true;
  1951. // A variable cannot be both common and exist in a section.
  1952. if (D->hasAttr<SectionAttr>())
  1953. return true;
  1954. // Thread local vars aren't considered common linkage.
  1955. if (D->getTLSKind())
  1956. return true;
  1957. // Tentative definitions marked with WeakImportAttr are true definitions.
  1958. if (D->hasAttr<WeakImportAttr>())
  1959. return true;
  1960. // A variable cannot be both common and exist in a comdat.
  1961. if (shouldBeInCOMDAT(CGM, *D))
  1962. return true;
  1963. // Declarations with a required alignment do not have common linakge in MSVC
  1964. // mode.
  1965. if (Context.getLangOpts().MSVCCompat) {
  1966. if (D->hasAttr<AlignedAttr>())
  1967. return true;
  1968. QualType VarType = D->getType();
  1969. if (Context.isAlignmentRequired(VarType))
  1970. return true;
  1971. if (const auto *RT = VarType->getAs<RecordType>()) {
  1972. const RecordDecl *RD = RT->getDecl();
  1973. for (const FieldDecl *FD : RD->fields()) {
  1974. if (FD->isBitField())
  1975. continue;
  1976. if (FD->hasAttr<AlignedAttr>())
  1977. return true;
  1978. if (Context.isAlignmentRequired(FD->getType()))
  1979. return true;
  1980. }
  1981. }
  1982. }
  1983. return false;
  1984. }
  1985. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  1986. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  1987. if (Linkage == GVA_Internal)
  1988. return llvm::Function::InternalLinkage;
  1989. if (D->hasAttr<WeakAttr>()) {
  1990. if (IsConstantVariable)
  1991. return llvm::GlobalVariable::WeakODRLinkage;
  1992. else
  1993. return llvm::GlobalVariable::WeakAnyLinkage;
  1994. }
  1995. // We are guaranteed to have a strong definition somewhere else,
  1996. // so we can use available_externally linkage.
  1997. if (Linkage == GVA_AvailableExternally)
  1998. return llvm::Function::AvailableExternallyLinkage;
  1999. // Note that Apple's kernel linker doesn't support symbol
  2000. // coalescing, so we need to avoid linkonce and weak linkages there.
  2001. // Normally, this means we just map to internal, but for explicit
  2002. // instantiations we'll map to external.
  2003. // In C++, the compiler has to emit a definition in every translation unit
  2004. // that references the function. We should use linkonce_odr because
  2005. // a) if all references in this translation unit are optimized away, we
  2006. // don't need to codegen it. b) if the function persists, it needs to be
  2007. // merged with other definitions. c) C++ has the ODR, so we know the
  2008. // definition is dependable.
  2009. if (Linkage == GVA_DiscardableODR)
  2010. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2011. : llvm::Function::InternalLinkage;
  2012. // An explicit instantiation of a template has weak linkage, since
  2013. // explicit instantiations can occur in multiple translation units
  2014. // and must all be equivalent. However, we are not allowed to
  2015. // throw away these explicit instantiations.
  2016. if (Linkage == GVA_StrongODR)
  2017. return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
  2018. : llvm::Function::ExternalLinkage;
  2019. // C++ doesn't have tentative definitions and thus cannot have common
  2020. // linkage.
  2021. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2022. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2023. CodeGenOpts.NoCommon))
  2024. return llvm::GlobalVariable::CommonLinkage;
  2025. // selectany symbols are externally visible, so use weak instead of
  2026. // linkonce. MSVC optimizes away references to const selectany globals, so
  2027. // all definitions should be the same and ODR linkage should be used.
  2028. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2029. if (D->hasAttr<SelectAnyAttr>())
  2030. return llvm::GlobalVariable::WeakODRLinkage;
  2031. // Otherwise, we have strong external linkage.
  2032. assert(Linkage == GVA_StrongExternal);
  2033. return llvm::GlobalVariable::ExternalLinkage;
  2034. }
  2035. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2036. const VarDecl *VD, bool IsConstant) {
  2037. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2038. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2039. }
  2040. /// Replace the uses of a function that was declared with a non-proto type.
  2041. /// We want to silently drop extra arguments from call sites
  2042. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2043. llvm::Function *newFn) {
  2044. // Fast path.
  2045. if (old->use_empty()) return;
  2046. llvm::Type *newRetTy = newFn->getReturnType();
  2047. SmallVector<llvm::Value*, 4> newArgs;
  2048. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2049. ui != ue; ) {
  2050. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2051. llvm::User *user = use->getUser();
  2052. // Recognize and replace uses of bitcasts. Most calls to
  2053. // unprototyped functions will use bitcasts.
  2054. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2055. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2056. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2057. continue;
  2058. }
  2059. // Recognize calls to the function.
  2060. llvm::CallSite callSite(user);
  2061. if (!callSite) continue;
  2062. if (!callSite.isCallee(&*use)) continue;
  2063. // If the return types don't match exactly, then we can't
  2064. // transform this call unless it's dead.
  2065. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2066. continue;
  2067. // Get the call site's attribute list.
  2068. SmallVector<llvm::AttributeSet, 8> newAttrs;
  2069. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  2070. // Collect any return attributes from the call.
  2071. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  2072. newAttrs.push_back(
  2073. llvm::AttributeSet::get(newFn->getContext(),
  2074. oldAttrs.getRetAttributes()));
  2075. // If the function was passed too few arguments, don't transform.
  2076. unsigned newNumArgs = newFn->arg_size();
  2077. if (callSite.arg_size() < newNumArgs) continue;
  2078. // If extra arguments were passed, we silently drop them.
  2079. // If any of the types mismatch, we don't transform.
  2080. unsigned argNo = 0;
  2081. bool dontTransform = false;
  2082. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  2083. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  2084. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  2085. dontTransform = true;
  2086. break;
  2087. }
  2088. // Add any parameter attributes.
  2089. if (oldAttrs.hasAttributes(argNo + 1))
  2090. newAttrs.
  2091. push_back(llvm::
  2092. AttributeSet::get(newFn->getContext(),
  2093. oldAttrs.getParamAttributes(argNo + 1)));
  2094. }
  2095. if (dontTransform)
  2096. continue;
  2097. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  2098. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  2099. oldAttrs.getFnAttributes()));
  2100. // Okay, we can transform this. Create the new call instruction and copy
  2101. // over the required information.
  2102. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2103. llvm::CallSite newCall;
  2104. if (callSite.isCall()) {
  2105. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  2106. callSite.getInstruction());
  2107. } else {
  2108. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2109. newCall = llvm::InvokeInst::Create(newFn,
  2110. oldInvoke->getNormalDest(),
  2111. oldInvoke->getUnwindDest(),
  2112. newArgs, "",
  2113. callSite.getInstruction());
  2114. }
  2115. newArgs.clear(); // for the next iteration
  2116. if (!newCall->getType()->isVoidTy())
  2117. newCall->takeName(callSite.getInstruction());
  2118. newCall.setAttributes(
  2119. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  2120. newCall.setCallingConv(callSite.getCallingConv());
  2121. // Finally, remove the old call, replacing any uses with the new one.
  2122. if (!callSite->use_empty())
  2123. callSite->replaceAllUsesWith(newCall.getInstruction());
  2124. // Copy debug location attached to CI.
  2125. if (callSite->getDebugLoc())
  2126. newCall->setDebugLoc(callSite->getDebugLoc());
  2127. callSite->eraseFromParent();
  2128. }
  2129. }
  2130. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2131. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2132. /// existing call uses of the old function in the module, this adjusts them to
  2133. /// call the new function directly.
  2134. ///
  2135. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2136. /// functions to be able to inline them. If there is a bitcast in the way, it
  2137. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2138. /// run at -O0.
  2139. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2140. llvm::Function *NewFn) {
  2141. // If we're redefining a global as a function, don't transform it.
  2142. if (!isa<llvm::Function>(Old)) return;
  2143. replaceUsesOfNonProtoConstant(Old, NewFn);
  2144. }
  2145. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2146. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2147. // If we have a definition, this might be a deferred decl. If the
  2148. // instantiation is explicit, make sure we emit it at the end.
  2149. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2150. GetAddrOfGlobalVar(VD);
  2151. EmitTopLevelDecl(VD);
  2152. }
  2153. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2154. llvm::GlobalValue *GV) {
  2155. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2156. // Compute the function info and LLVM type.
  2157. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2158. // HLSL Change Begins.
  2159. // Out parameter is not ByVal.
  2160. auto I = const_cast<CGFunctionInfo&>(FI).arg_begin();
  2161. for (const ParmVarDecl *Param : D->params()) {
  2162. if (Param->isModifierOut() && I->info.isIndirect()) {
  2163. I->info.setIndirectByVal(false);
  2164. }
  2165. I++;
  2166. }
  2167. // HLSL Change Ends.
  2168. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2169. // Get or create the prototype for the function.
  2170. if (!GV) {
  2171. llvm::Constant *C =
  2172. GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
  2173. // Strip off a bitcast if we got one back.
  2174. if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
  2175. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  2176. GV = cast<llvm::GlobalValue>(CE->getOperand(0));
  2177. } else {
  2178. GV = cast<llvm::GlobalValue>(C);
  2179. }
  2180. }
  2181. if (!GV->isDeclaration()) {
  2182. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2183. GlobalDecl OldGD = Manglings.lookup(GV->getName());
  2184. if (auto *Prev = OldGD.getDecl())
  2185. getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
  2186. return;
  2187. }
  2188. if (GV->getType()->getElementType() != Ty) {
  2189. // If the types mismatch then we have to rewrite the definition.
  2190. assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
  2191. // F is the Function* for the one with the wrong type, we must make a new
  2192. // Function* and update everything that used F (a declaration) with the new
  2193. // Function* (which will be a definition).
  2194. //
  2195. // This happens if there is a prototype for a function
  2196. // (e.g. "int f()") and then a definition of a different type
  2197. // (e.g. "int f(int x)"). Move the old function aside so that it
  2198. // doesn't interfere with GetAddrOfFunction.
  2199. GV->setName(StringRef());
  2200. auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  2201. // This might be an implementation of a function without a
  2202. // prototype, in which case, try to do special replacement of
  2203. // calls which match the new prototype. The really key thing here
  2204. // is that we also potentially drop arguments from the call site
  2205. // so as to make a direct call, which makes the inliner happier
  2206. // and suppresses a number of optimizer warnings (!) about
  2207. // dropping arguments.
  2208. if (!GV->use_empty()) {
  2209. ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
  2210. GV->removeDeadConstantUsers();
  2211. }
  2212. // Replace uses of F with the Function we will endow with a body.
  2213. if (!GV->use_empty()) {
  2214. llvm::Constant *NewPtrForOldDecl =
  2215. llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
  2216. GV->replaceAllUsesWith(NewPtrForOldDecl);
  2217. }
  2218. // Ok, delete the old function now, which is dead.
  2219. GV->eraseFromParent();
  2220. GV = NewFn;
  2221. }
  2222. // We need to set linkage and visibility on the function before
  2223. // generating code for it because various parts of IR generation
  2224. // want to propagate this information down (e.g. to local static
  2225. // declarations).
  2226. auto *Fn = cast<llvm::Function>(GV);
  2227. setFunctionLinkage(GD, Fn);
  2228. setFunctionDLLStorageClass(GD, Fn);
  2229. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2230. setGlobalVisibility(Fn, D);
  2231. MaybeHandleStaticInExternC(D, Fn);
  2232. maybeSetTrivialComdat(*D, *Fn);
  2233. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2234. setFunctionDefinitionAttributes(D, Fn);
  2235. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2236. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2237. AddGlobalCtor(Fn, CA->getPriority());
  2238. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2239. AddGlobalDtor(Fn, DA->getPriority());
  2240. if (D->hasAttr<AnnotateAttr>())
  2241. AddGlobalAnnotations(D, Fn);
  2242. }
  2243. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2244. const auto *D = cast<ValueDecl>(GD.getDecl());
  2245. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2246. assert(AA && "Not an alias?");
  2247. StringRef MangledName = getMangledName(GD);
  2248. // If there is a definition in the module, then it wins over the alias.
  2249. // This is dubious, but allow it to be safe. Just ignore the alias.
  2250. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2251. if (Entry && !Entry->isDeclaration())
  2252. return;
  2253. Aliases.push_back(GD);
  2254. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2255. // Create a reference to the named value. This ensures that it is emitted
  2256. // if a deferred decl.
  2257. llvm::Constant *Aliasee;
  2258. if (isa<llvm::FunctionType>(DeclTy))
  2259. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2260. /*ForVTable=*/false);
  2261. else
  2262. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2263. llvm::PointerType::getUnqual(DeclTy),
  2264. /*D=*/nullptr);
  2265. // Create the new alias itself, but don't set a name yet.
  2266. auto *GA = llvm::GlobalAlias::create(
  2267. cast<llvm::PointerType>(Aliasee->getType()),
  2268. llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2269. if (Entry) {
  2270. if (GA->getAliasee() == Entry) {
  2271. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  2272. return;
  2273. }
  2274. assert(Entry->isDeclaration());
  2275. // If there is a declaration in the module, then we had an extern followed
  2276. // by the alias, as in:
  2277. // extern int test6();
  2278. // ...
  2279. // int test6() __attribute__((alias("test7")));
  2280. //
  2281. // Remove it and replace uses of it with the alias.
  2282. GA->takeName(Entry);
  2283. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2284. Entry->getType()));
  2285. Entry->eraseFromParent();
  2286. } else {
  2287. GA->setName(MangledName);
  2288. }
  2289. // Set attributes which are particular to an alias; this is a
  2290. // specialization of the attributes which may be set on a global
  2291. // variable/function.
  2292. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2293. D->isWeakImported()) {
  2294. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2295. }
  2296. if (const auto *VD = dyn_cast<VarDecl>(D))
  2297. if (VD->getTLSKind())
  2298. setTLSMode(GA, *VD);
  2299. setAliasAttributes(D, GA);
  2300. }
  2301. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2302. ArrayRef<llvm::Type*> Tys) {
  2303. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2304. Tys);
  2305. }
  2306. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2307. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2308. const StringLiteral *Literal, bool TargetIsLSB,
  2309. bool &IsUTF16, unsigned &StringLength) {
  2310. StringRef String = Literal->getString();
  2311. unsigned NumBytes = String.size();
  2312. // Check for simple case.
  2313. if (!Literal->containsNonAsciiOrNull()) {
  2314. StringLength = NumBytes;
  2315. return *Map.insert(std::make_pair(String, nullptr)).first;
  2316. }
  2317. // Otherwise, convert the UTF8 literals into a string of shorts.
  2318. IsUTF16 = true;
  2319. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2320. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2321. UTF16 *ToPtr = &ToBuf[0];
  2322. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2323. &ToPtr, ToPtr + NumBytes,
  2324. strictConversion);
  2325. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2326. StringLength = ToPtr - &ToBuf[0];
  2327. // Add an explicit null.
  2328. *ToPtr = 0;
  2329. return *Map.insert(std::make_pair(
  2330. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2331. (StringLength + 1) * 2),
  2332. nullptr)).first;
  2333. }
  2334. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2335. GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2336. const StringLiteral *Literal, unsigned &StringLength) {
  2337. StringRef String = Literal->getString();
  2338. StringLength = String.size();
  2339. return *Map.insert(std::make_pair(String, nullptr)).first;
  2340. }
  2341. llvm::Constant *
  2342. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2343. unsigned StringLength = 0;
  2344. bool isUTF16 = false;
  2345. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2346. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2347. getDataLayout().isLittleEndian(), isUTF16,
  2348. StringLength);
  2349. if (auto *C = Entry.second)
  2350. return C;
  2351. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2352. llvm::Constant *Zeros[] = { Zero, Zero };
  2353. llvm::Value *V;
  2354. // If we don't already have it, get __CFConstantStringClassReference.
  2355. if (!CFConstantStringClassRef) {
  2356. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2357. Ty = llvm::ArrayType::get(Ty, 0);
  2358. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  2359. "__CFConstantStringClassReference");
  2360. // Decay array -> ptr
  2361. V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2362. CFConstantStringClassRef = V;
  2363. }
  2364. else
  2365. V = CFConstantStringClassRef;
  2366. QualType CFTy = getContext().getCFConstantStringType();
  2367. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2368. llvm::Constant *Fields[4];
  2369. // Class pointer.
  2370. Fields[0] = cast<llvm::ConstantExpr>(V);
  2371. // Flags.
  2372. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2373. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  2374. llvm::ConstantInt::get(Ty, 0x07C8);
  2375. // String pointer.
  2376. llvm::Constant *C = nullptr;
  2377. if (isUTF16) {
  2378. ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
  2379. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  2380. Entry.first().size() / 2);
  2381. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2382. } else {
  2383. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2384. }
  2385. // Note: -fwritable-strings doesn't make the backing store strings of
  2386. // CFStrings writable. (See <rdar://problem/10657500>)
  2387. auto *GV =
  2388. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2389. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2390. GV->setUnnamedAddr(true);
  2391. // Don't enforce the target's minimum global alignment, since the only use
  2392. // of the string is via this class initializer.
  2393. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
  2394. // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
  2395. // that changes the section it ends in, which surprises ld64.
  2396. if (isUTF16) {
  2397. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  2398. GV->setAlignment(Align.getQuantity());
  2399. GV->setSection("__TEXT,__ustring");
  2400. } else {
  2401. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2402. GV->setAlignment(Align.getQuantity());
  2403. GV->setSection("__TEXT,__cstring,cstring_literals");
  2404. }
  2405. // String.
  2406. Fields[2] =
  2407. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2408. if (isUTF16)
  2409. // Cast the UTF16 string to the correct type.
  2410. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  2411. // String length.
  2412. Ty = getTypes().ConvertType(getContext().LongTy);
  2413. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  2414. // The struct.
  2415. C = llvm::ConstantStruct::get(STy, Fields);
  2416. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2417. llvm::GlobalVariable::PrivateLinkage, C,
  2418. "_unnamed_cfstring_");
  2419. GV->setSection("__DATA,__cfstring");
  2420. Entry.second = GV;
  2421. return GV;
  2422. }
  2423. llvm::GlobalVariable *
  2424. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  2425. unsigned StringLength = 0;
  2426. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2427. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  2428. if (auto *C = Entry.second)
  2429. return C;
  2430. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2431. llvm::Constant *Zeros[] = { Zero, Zero };
  2432. llvm::Value *V;
  2433. // If we don't already have it, get _NSConstantStringClassReference.
  2434. if (!ConstantStringClassRef) {
  2435. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2436. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2437. llvm::Constant *GV;
  2438. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2439. std::string str =
  2440. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2441. : "OBJC_CLASS_$_" + StringClass;
  2442. GV = getObjCRuntime().GetClassGlobal(str);
  2443. // Make sure the result is of the correct type.
  2444. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2445. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  2446. ConstantStringClassRef = V;
  2447. } else {
  2448. std::string str =
  2449. StringClass.empty() ? "_NSConstantStringClassReference"
  2450. : "_" + StringClass + "ClassReference";
  2451. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2452. GV = CreateRuntimeVariable(PTy, str);
  2453. // Decay array -> ptr
  2454. V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
  2455. ConstantStringClassRef = V;
  2456. }
  2457. } else
  2458. V = ConstantStringClassRef;
  2459. if (!NSConstantStringType) {
  2460. // Construct the type for a constant NSString.
  2461. RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
  2462. D->startDefinition();
  2463. QualType FieldTypes[3];
  2464. // const int *isa;
  2465. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2466. // const char *str;
  2467. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2468. // unsigned int length;
  2469. FieldTypes[2] = Context.UnsignedIntTy;
  2470. // Create fields
  2471. for (unsigned i = 0; i < 3; ++i) {
  2472. FieldDecl *Field = FieldDecl::Create(Context, D,
  2473. SourceLocation(),
  2474. SourceLocation(), nullptr,
  2475. FieldTypes[i], /*TInfo=*/nullptr,
  2476. /*BitWidth=*/nullptr,
  2477. /*Mutable=*/false,
  2478. ICIS_NoInit);
  2479. Field->setAccess(AS_public);
  2480. D->addDecl(Field);
  2481. }
  2482. D->completeDefinition();
  2483. QualType NSTy = Context.getTagDeclType(D);
  2484. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2485. }
  2486. llvm::Constant *Fields[3];
  2487. // Class pointer.
  2488. Fields[0] = cast<llvm::ConstantExpr>(V);
  2489. // String pointer.
  2490. llvm::Constant *C =
  2491. llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2492. llvm::GlobalValue::LinkageTypes Linkage;
  2493. bool isConstant;
  2494. Linkage = llvm::GlobalValue::PrivateLinkage;
  2495. isConstant = !LangOpts.WritableStrings;
  2496. auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
  2497. Linkage, C, ".str");
  2498. GV->setUnnamedAddr(true);
  2499. // Don't enforce the target's minimum global alignment, since the only use
  2500. // of the string is via this class initializer.
  2501. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2502. GV->setAlignment(Align.getQuantity());
  2503. Fields[1] =
  2504. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2505. // String length.
  2506. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2507. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2508. // The struct.
  2509. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2510. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2511. llvm::GlobalVariable::PrivateLinkage, C,
  2512. "_unnamed_nsstring_");
  2513. const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
  2514. const char *NSStringNonFragileABISection =
  2515. "__DATA,__objc_stringobj,regular,no_dead_strip";
  2516. // FIXME. Fix section.
  2517. GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
  2518. ? NSStringNonFragileABISection
  2519. : NSStringSection);
  2520. Entry.second = GV;
  2521. return GV;
  2522. }
  2523. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2524. if (ObjCFastEnumerationStateType.isNull()) {
  2525. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2526. D->startDefinition();
  2527. QualType FieldTypes[] = {
  2528. Context.UnsignedLongTy,
  2529. Context.getPointerType(Context.getObjCIdType()),
  2530. Context.getPointerType(Context.UnsignedLongTy),
  2531. Context.getConstantArrayType(Context.UnsignedLongTy,
  2532. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2533. };
  2534. for (size_t i = 0; i < 4; ++i) {
  2535. FieldDecl *Field = FieldDecl::Create(Context,
  2536. D,
  2537. SourceLocation(),
  2538. SourceLocation(), nullptr,
  2539. FieldTypes[i], /*TInfo=*/nullptr,
  2540. /*BitWidth=*/nullptr,
  2541. /*Mutable=*/false,
  2542. ICIS_NoInit);
  2543. Field->setAccess(AS_public);
  2544. D->addDecl(Field);
  2545. }
  2546. D->completeDefinition();
  2547. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2548. }
  2549. return ObjCFastEnumerationStateType;
  2550. }
  2551. llvm::Constant *
  2552. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2553. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2554. // Don't emit it as the address of the string, emit the string data itself
  2555. // as an inline array.
  2556. if (E->getCharByteWidth() == 1) {
  2557. SmallString<64> Str(E->getString());
  2558. // Resize the string to the right size, which is indicated by its type.
  2559. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2560. Str.resize(CAT->getSize().getZExtValue());
  2561. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2562. }
  2563. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2564. llvm::Type *ElemTy = AType->getElementType();
  2565. unsigned NumElements = AType->getNumElements();
  2566. // Wide strings have either 2-byte or 4-byte elements.
  2567. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2568. SmallVector<uint16_t, 32> Elements;
  2569. Elements.reserve(NumElements);
  2570. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2571. Elements.push_back(E->getCodeUnit(i));
  2572. Elements.resize(NumElements);
  2573. return llvm::ConstantDataArray::get(VMContext, Elements);
  2574. }
  2575. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2576. SmallVector<uint32_t, 32> Elements;
  2577. Elements.reserve(NumElements);
  2578. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2579. Elements.push_back(E->getCodeUnit(i));
  2580. Elements.resize(NumElements);
  2581. return llvm::ConstantDataArray::get(VMContext, Elements);
  2582. }
  2583. static llvm::GlobalVariable *
  2584. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2585. CodeGenModule &CGM, StringRef GlobalName,
  2586. unsigned Alignment) {
  2587. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2588. unsigned AddrSpace = 0;
  2589. if (CGM.getLangOpts().OpenCL)
  2590. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2591. llvm::Module &M = CGM.getModule();
  2592. // Create a global variable for this string
  2593. auto *GV = new llvm::GlobalVariable(
  2594. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  2595. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2596. GV->setAlignment(Alignment);
  2597. GV->setUnnamedAddr(true);
  2598. if (GV->isWeakForLinker()) {
  2599. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  2600. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2601. }
  2602. return GV;
  2603. }
  2604. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2605. /// constant array for the given string literal.
  2606. llvm::GlobalVariable *
  2607. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  2608. StringRef Name) {
  2609. auto Alignment =
  2610. getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
  2611. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2612. llvm::GlobalVariable **Entry = nullptr;
  2613. if (!LangOpts.WritableStrings) {
  2614. Entry = &ConstantStringMap[C];
  2615. if (auto GV = *Entry) {
  2616. if (Alignment > GV->getAlignment())
  2617. GV->setAlignment(Alignment);
  2618. return GV;
  2619. }
  2620. }
  2621. SmallString<256> MangledNameBuffer;
  2622. StringRef GlobalVariableName;
  2623. llvm::GlobalValue::LinkageTypes LT;
  2624. // Mangle the string literal if the ABI allows for it. However, we cannot
  2625. // do this if we are compiling with ASan or -fwritable-strings because they
  2626. // rely on strings having normal linkage.
  2627. if (!LangOpts.WritableStrings &&
  2628. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  2629. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  2630. llvm::raw_svector_ostream Out(MangledNameBuffer);
  2631. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  2632. Out.flush();
  2633. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  2634. GlobalVariableName = MangledNameBuffer;
  2635. } else {
  2636. LT = llvm::GlobalValue::PrivateLinkage;
  2637. GlobalVariableName = Name;
  2638. }
  2639. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  2640. if (Entry)
  2641. *Entry = GV;
  2642. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  2643. QualType());
  2644. return GV;
  2645. }
  2646. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2647. /// array for the given ObjCEncodeExpr node.
  2648. llvm::GlobalVariable *
  2649. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2650. std::string Str;
  2651. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2652. return GetAddrOfConstantCString(Str);
  2653. }
  2654. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  2655. /// the literal and a terminating '\0' character.
  2656. /// The result has pointer to array type.
  2657. llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
  2658. const std::string &Str, const char *GlobalName, unsigned Alignment) {
  2659. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2660. if (Alignment == 0) {
  2661. Alignment = getContext()
  2662. .getAlignOfGlobalVarInChars(getContext().CharTy)
  2663. .getQuantity();
  2664. }
  2665. llvm::Constant *C =
  2666. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  2667. // Don't share any string literals if strings aren't constant.
  2668. llvm::GlobalVariable **Entry = nullptr;
  2669. if (!LangOpts.WritableStrings) {
  2670. Entry = &ConstantStringMap[C];
  2671. if (auto GV = *Entry) {
  2672. if (Alignment > GV->getAlignment())
  2673. GV->setAlignment(Alignment);
  2674. return GV;
  2675. }
  2676. }
  2677. // Get the default prefix if a name wasn't specified.
  2678. if (!GlobalName)
  2679. GlobalName = ".str";
  2680. // Create a global variable for this.
  2681. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  2682. GlobalName, Alignment);
  2683. if (Entry)
  2684. *Entry = GV;
  2685. return GV;
  2686. }
  2687. llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
  2688. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2689. assert((E->getStorageDuration() == SD_Static ||
  2690. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2691. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  2692. // If we're not materializing a subobject of the temporary, keep the
  2693. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2694. QualType MaterializedType = Init->getType();
  2695. if (Init == E->GetTemporaryExpr())
  2696. MaterializedType = E->getType();
  2697. llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
  2698. if (Slot)
  2699. return Slot;
  2700. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2701. // we need to give each temporary the same name in every translation unit (and
  2702. // we also need to make the temporaries externally-visible).
  2703. SmallString<256> Name;
  2704. llvm::raw_svector_ostream Out(Name);
  2705. getCXXABI().getMangleContext().mangleReferenceTemporary(
  2706. VD, E->getManglingNumber(), Out);
  2707. Out.flush();
  2708. APValue *Value = nullptr;
  2709. if (E->getStorageDuration() == SD_Static) {
  2710. // We might have a cached constant initializer for this temporary. Note
  2711. // that this might have a different value from the value computed by
  2712. // evaluating the initializer if the surrounding constant expression
  2713. // modifies the temporary.
  2714. Value = getContext().getMaterializedTemporaryValue(E, false);
  2715. if (Value && Value->isUninit())
  2716. Value = nullptr;
  2717. }
  2718. // Try evaluating it now, it might have a constant initializer.
  2719. Expr::EvalResult EvalResult;
  2720. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2721. !EvalResult.hasSideEffects())
  2722. Value = &EvalResult.Val;
  2723. llvm::Constant *InitialValue = nullptr;
  2724. bool Constant = false;
  2725. llvm::Type *Type;
  2726. if (Value) {
  2727. // The temporary has a constant initializer, use it.
  2728. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  2729. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2730. Type = InitialValue->getType();
  2731. } else {
  2732. // No initializer, the initialization will be provided when we
  2733. // initialize the declaration which performed lifetime extension.
  2734. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2735. }
  2736. // Create a global variable for this lifetime-extended temporary.
  2737. llvm::GlobalValue::LinkageTypes Linkage =
  2738. getLLVMLinkageVarDefinition(VD, Constant);
  2739. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  2740. const VarDecl *InitVD;
  2741. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  2742. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  2743. // Temporaries defined inside a class get linkonce_odr linkage because the
  2744. // class can be defined in multipe translation units.
  2745. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  2746. } else {
  2747. // There is no need for this temporary to have external linkage if the
  2748. // VarDecl has external linkage.
  2749. Linkage = llvm::GlobalVariable::InternalLinkage;
  2750. }
  2751. }
  2752. unsigned AddrSpace = GetGlobalVarAddressSpace(
  2753. VD, getContext().getTargetAddressSpace(MaterializedType));
  2754. auto *GV = new llvm::GlobalVariable(
  2755. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  2756. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  2757. AddrSpace);
  2758. setGlobalVisibility(GV, VD);
  2759. GV->setAlignment(
  2760. getContext().getTypeAlignInChars(MaterializedType).getQuantity());
  2761. if (supportsCOMDAT() && GV->isWeakForLinker())
  2762. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2763. if (VD->getTLSKind())
  2764. setTLSMode(GV, *VD);
  2765. Slot = GV;
  2766. return GV;
  2767. }
  2768. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2769. /// properties for an implementation.
  2770. void CodeGenModule::EmitObjCPropertyImplementations(const
  2771. ObjCImplementationDecl *D) {
  2772. #if 0 // HLSL Change - no ObjC support
  2773. for (const auto *PID : D->property_impls()) {
  2774. // Dynamic is just for type-checking.
  2775. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2776. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2777. // Determine which methods need to be implemented, some may have
  2778. // been overridden. Note that ::isPropertyAccessor is not the method
  2779. // we want, that just indicates if the decl came from a
  2780. // property. What we want to know is if the method is defined in
  2781. // this implementation.
  2782. if (!D->getInstanceMethod(PD->getGetterName()))
  2783. CodeGenFunction(*this).GenerateObjCGetter(
  2784. const_cast<ObjCImplementationDecl *>(D), PID);
  2785. if (!PD->isReadOnly() &&
  2786. !D->getInstanceMethod(PD->getSetterName()))
  2787. CodeGenFunction(*this).GenerateObjCSetter(
  2788. const_cast<ObjCImplementationDecl *>(D), PID);
  2789. }
  2790. }
  2791. #endif 0 // HLSL Change - no ObjC support
  2792. }
  2793. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2794. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2795. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2796. ivar; ivar = ivar->getNextIvar())
  2797. if (ivar->getType().isDestructedType())
  2798. return true;
  2799. return false;
  2800. }
  2801. static bool AllTrivialInitializers(CodeGenModule &CGM,
  2802. ObjCImplementationDecl *D) {
  2803. CodeGenFunction CGF(CGM);
  2804. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  2805. E = D->init_end(); B != E; ++B) {
  2806. CXXCtorInitializer *CtorInitExp = *B;
  2807. Expr *Init = CtorInitExp->getInit();
  2808. if (!CGF.isTrivialInitializer(Init))
  2809. return false;
  2810. }
  2811. return true;
  2812. }
  2813. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2814. /// for an implementation.
  2815. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2816. #if 0 // HLSL Change - no ObjC support
  2817. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2818. if (needsDestructMethod(D)) {
  2819. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2820. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2821. ObjCMethodDecl *DTORMethod =
  2822. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2823. cxxSelector, getContext().VoidTy, nullptr, D,
  2824. /*isInstance=*/true, /*isVariadic=*/false,
  2825. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2826. /*isDefined=*/false, ObjCMethodDecl::Required);
  2827. D->addInstanceMethod(DTORMethod);
  2828. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2829. D->setHasDestructors(true);
  2830. }
  2831. // If the implementation doesn't have any ivar initializers, we don't need
  2832. // a .cxx_construct.
  2833. if (D->getNumIvarInitializers() == 0 ||
  2834. AllTrivialInitializers(*this, D))
  2835. return;
  2836. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2837. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2838. // The constructor returns 'self'.
  2839. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2840. D->getLocation(),
  2841. D->getLocation(),
  2842. cxxSelector,
  2843. getContext().getObjCIdType(),
  2844. nullptr, D, /*isInstance=*/true,
  2845. /*isVariadic=*/false,
  2846. /*isPropertyAccessor=*/true,
  2847. /*isImplicitlyDeclared=*/true,
  2848. /*isDefined=*/false,
  2849. ObjCMethodDecl::Required);
  2850. D->addInstanceMethod(CTORMethod);
  2851. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2852. D->setHasNonZeroConstructors(true);
  2853. #endif // HLSL Change - no ObjC support
  2854. }
  2855. /// EmitNamespace - Emit all declarations in a namespace.
  2856. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2857. for (auto *I : ND->decls()) {
  2858. if (const auto *VD = dyn_cast<VarDecl>(I))
  2859. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  2860. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  2861. continue;
  2862. EmitTopLevelDecl(I);
  2863. }
  2864. }
  2865. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2866. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2867. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2868. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2869. ErrorUnsupported(LSD, "linkage spec");
  2870. return;
  2871. }
  2872. for (auto *I : LSD->decls()) {
  2873. // Meta-data for ObjC class includes references to implemented methods.
  2874. // Generate class's method definitions first.
  2875. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  2876. for (auto *M : OID->methods())
  2877. EmitTopLevelDecl(M);
  2878. }
  2879. EmitTopLevelDecl(I);
  2880. }
  2881. }
  2882. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2883. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2884. // Ignore dependent declarations.
  2885. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2886. return;
  2887. switch (D->getKind()) {
  2888. case Decl::CXXConversion:
  2889. case Decl::CXXMethod:
  2890. case Decl::Function:
  2891. // Skip function templates
  2892. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2893. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2894. return;
  2895. EmitGlobal(cast<FunctionDecl>(D));
  2896. // Always provide some coverage mapping
  2897. // even for the functions that aren't emitted.
  2898. AddDeferredUnusedCoverageMapping(D);
  2899. break;
  2900. case Decl::Var:
  2901. // Skip variable templates
  2902. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  2903. return;
  2904. case Decl::VarTemplateSpecialization:
  2905. EmitGlobal(cast<VarDecl>(D));
  2906. getHLSLRuntime().addResource(D); // HLSL Change - add resource for global variables
  2907. break;
  2908. // Indirect fields from global anonymous structs and unions can be
  2909. // ignored; only the actual variable requires IR gen support.
  2910. case Decl::IndirectField:
  2911. break;
  2912. // C++ Decls
  2913. case Decl::Namespace:
  2914. EmitNamespace(cast<NamespaceDecl>(D));
  2915. break;
  2916. // No code generation needed.
  2917. case Decl::UsingShadow:
  2918. case Decl::ClassTemplate:
  2919. case Decl::VarTemplate:
  2920. case Decl::VarTemplatePartialSpecialization:
  2921. case Decl::FunctionTemplate:
  2922. case Decl::TypeAliasTemplate:
  2923. case Decl::Block:
  2924. case Decl::Empty:
  2925. break;
  2926. case Decl::Using: // using X; [C++]
  2927. if (CGDebugInfo *DI = getModuleDebugInfo())
  2928. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  2929. return;
  2930. case Decl::NamespaceAlias:
  2931. if (CGDebugInfo *DI = getModuleDebugInfo())
  2932. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  2933. return;
  2934. case Decl::UsingDirective: // using namespace X; [C++]
  2935. if (CGDebugInfo *DI = getModuleDebugInfo())
  2936. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  2937. return;
  2938. case Decl::CXXConstructor:
  2939. // Skip function templates
  2940. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2941. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2942. return;
  2943. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2944. break;
  2945. case Decl::CXXDestructor:
  2946. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2947. return;
  2948. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2949. break;
  2950. case Decl::StaticAssert:
  2951. // Nothing to do.
  2952. break;
  2953. // Objective-C Decls
  2954. #if 0 // HLSL Change Starts - no ObjC support
  2955. // Forward declarations, no (immediate) code generation.
  2956. case Decl::ObjCInterface:
  2957. case Decl::ObjCCategory:
  2958. break;
  2959. case Decl::ObjCProtocol: {
  2960. auto *Proto = cast<ObjCProtocolDecl>(D);
  2961. if (Proto->isThisDeclarationADefinition())
  2962. ObjCRuntime->GenerateProtocol(Proto);
  2963. break;
  2964. }
  2965. case Decl::ObjCCategoryImpl:
  2966. // Categories have properties but don't support synthesize so we
  2967. // can ignore them here.
  2968. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2969. break;
  2970. case Decl::ObjCImplementation: {
  2971. auto *OMD = cast<ObjCImplementationDecl>(D);
  2972. EmitObjCPropertyImplementations(OMD);
  2973. EmitObjCIvarInitializations(OMD);
  2974. ObjCRuntime->GenerateClass(OMD);
  2975. // Emit global variable debug information.
  2976. if (CGDebugInfo *DI = getModuleDebugInfo())
  2977. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2978. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2979. OMD->getClassInterface()), OMD->getLocation());
  2980. break;
  2981. }
  2982. case Decl::ObjCMethod: {
  2983. auto *OMD = cast<ObjCMethodDecl>(D);
  2984. // If this is not a prototype, emit the body.
  2985. if (OMD->getBody())
  2986. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2987. break;
  2988. }
  2989. case Decl::ObjCCompatibleAlias:
  2990. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2991. break;
  2992. #endif // HLSL Change Ends - no ObjC support
  2993. case Decl::LinkageSpec:
  2994. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2995. break;
  2996. #if 0 // HLSL Change Starts - no asm, import or openmp support
  2997. case Decl::FileScopeAsm: {
  2998. // File-scope asm is ignored during device-side CUDA compilation.
  2999. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3000. break;
  3001. auto *AD = cast<FileScopeAsmDecl>(D);
  3002. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3003. break;
  3004. }
  3005. case Decl::Import: {
  3006. auto *Import = cast<ImportDecl>(D);
  3007. // Ignore import declarations that come from imported modules.
  3008. if (clang::Module *Owner = Import->getImportedOwningModule()) {
  3009. if (getLangOpts().CurrentModule.empty() ||
  3010. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  3011. break;
  3012. }
  3013. if (CGDebugInfo *DI = getModuleDebugInfo())
  3014. DI->EmitImportDecl(*Import);
  3015. ImportedModules.insert(Import->getImportedModule());
  3016. break;
  3017. }
  3018. case Decl::OMPThreadPrivate:
  3019. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3020. break;
  3021. #endif // HLSL Change Ends - no asm, import or openmp support
  3022. case Decl::ClassTemplateSpecialization: {
  3023. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3024. if (DebugInfo &&
  3025. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3026. Spec->hasDefinition())
  3027. DebugInfo->completeTemplateDefinition(*Spec);
  3028. break;
  3029. }
  3030. // HLSL Change Starts
  3031. case Decl::HLSLBuffer: {
  3032. // TODO: add resource to HLSLRuntime
  3033. HLSLBufferDecl *BD = cast<HLSLBufferDecl>(D);
  3034. getHLSLRuntime().addResource(BD);
  3035. break;
  3036. }
  3037. // HLSL Change Ends
  3038. default:
  3039. // Make sure we handled everything we should, every other kind is a
  3040. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3041. // function. Need to recode Decl::Kind to do that easily.
  3042. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3043. break;
  3044. }
  3045. }
  3046. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3047. // Do we need to generate coverage mapping?
  3048. if (!CodeGenOpts.CoverageMapping)
  3049. return;
  3050. switch (D->getKind()) {
  3051. case Decl::CXXConversion:
  3052. case Decl::CXXMethod:
  3053. case Decl::Function:
  3054. case Decl::ObjCMethod:
  3055. case Decl::CXXConstructor:
  3056. case Decl::CXXDestructor: {
  3057. if (!cast<FunctionDecl>(D)->hasBody())
  3058. return;
  3059. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3060. if (I == DeferredEmptyCoverageMappingDecls.end())
  3061. DeferredEmptyCoverageMappingDecls[D] = true;
  3062. break;
  3063. }
  3064. default:
  3065. break;
  3066. };
  3067. }
  3068. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3069. // Do we need to generate coverage mapping?
  3070. if (!CodeGenOpts.CoverageMapping)
  3071. return;
  3072. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3073. if (Fn->isTemplateInstantiation())
  3074. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3075. }
  3076. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3077. if (I == DeferredEmptyCoverageMappingDecls.end())
  3078. DeferredEmptyCoverageMappingDecls[D] = false;
  3079. else
  3080. I->second = false;
  3081. }
  3082. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3083. std::vector<const Decl *> DeferredDecls;
  3084. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  3085. if (!I.second)
  3086. continue;
  3087. DeferredDecls.push_back(I.first);
  3088. }
  3089. // Sort the declarations by their location to make sure that the tests get a
  3090. // predictable order for the coverage mapping for the unused declarations.
  3091. if (CodeGenOpts.DumpCoverageMapping)
  3092. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  3093. [] (const Decl *LHS, const Decl *RHS) {
  3094. return LHS->getLocStart() < RHS->getLocStart();
  3095. });
  3096. for (const auto *D : DeferredDecls) {
  3097. switch (D->getKind()) {
  3098. case Decl::CXXConversion:
  3099. case Decl::CXXMethod:
  3100. case Decl::Function:
  3101. case Decl::ObjCMethod: {
  3102. CodeGenPGO PGO(*this);
  3103. GlobalDecl GD(cast<FunctionDecl>(D));
  3104. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3105. getFunctionLinkage(GD));
  3106. break;
  3107. }
  3108. case Decl::CXXConstructor: {
  3109. CodeGenPGO PGO(*this);
  3110. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3111. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3112. getFunctionLinkage(GD));
  3113. break;
  3114. }
  3115. case Decl::CXXDestructor: {
  3116. CodeGenPGO PGO(*this);
  3117. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3118. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3119. getFunctionLinkage(GD));
  3120. break;
  3121. }
  3122. default:
  3123. break;
  3124. };
  3125. }
  3126. }
  3127. /// Turns the given pointer into a constant.
  3128. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3129. const void *Ptr) {
  3130. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3131. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3132. return llvm::ConstantInt::get(i64, PtrInt);
  3133. }
  3134. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3135. llvm::NamedMDNode *&GlobalMetadata,
  3136. GlobalDecl D,
  3137. llvm::GlobalValue *Addr) {
  3138. if (!GlobalMetadata)
  3139. GlobalMetadata =
  3140. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3141. // TODO: should we report variant information for ctors/dtors?
  3142. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3143. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3144. CGM.getLLVMContext(), D.getDecl()))};
  3145. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3146. }
  3147. /// For each function which is declared within an extern "C" region and marked
  3148. /// as 'used', but has internal linkage, create an alias from the unmangled
  3149. /// name to the mangled name if possible. People expect to be able to refer
  3150. /// to such functions with an unmangled name from inline assembly within the
  3151. /// same translation unit.
  3152. void CodeGenModule::EmitStaticExternCAliases() {
  3153. for (auto &I : StaticExternCValues) {
  3154. IdentifierInfo *Name = I.first;
  3155. llvm::GlobalValue *Val = I.second;
  3156. if (Val && !getModule().getNamedValue(Name->getName()))
  3157. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3158. }
  3159. }
  3160. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3161. GlobalDecl &Result) const {
  3162. auto Res = Manglings.find(MangledName);
  3163. if (Res == Manglings.end())
  3164. return false;
  3165. Result = Res->getValue();
  3166. return true;
  3167. }
  3168. /// Emits metadata nodes associating all the global values in the
  3169. /// current module with the Decls they came from. This is useful for
  3170. /// projects using IR gen as a subroutine.
  3171. ///
  3172. /// Since there's currently no way to associate an MDNode directly
  3173. /// with an llvm::GlobalValue, we create a global named metadata
  3174. /// with the name 'clang.global.decl.ptrs'.
  3175. void CodeGenModule::EmitDeclMetadata() {
  3176. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3177. // StaticLocalDeclMap
  3178. for (auto &I : MangledDeclNames) {
  3179. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3180. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3181. }
  3182. }
  3183. /// Emits metadata nodes for all the local variables in the current
  3184. /// function.
  3185. void CodeGenFunction::EmitDeclMetadata() {
  3186. if (LocalDeclMap.empty()) return;
  3187. llvm::LLVMContext &Context = getLLVMContext();
  3188. // Find the unique metadata ID for this name.
  3189. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3190. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3191. for (auto &I : LocalDeclMap) {
  3192. const Decl *D = I.first;
  3193. llvm::Value *Addr = I.second;
  3194. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3195. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3196. Alloca->setMetadata(
  3197. DeclPtrKind, llvm::MDNode::get(
  3198. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3199. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3200. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3201. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3202. }
  3203. }
  3204. }
  3205. void CodeGenModule::EmitVersionIdentMetadata() {
  3206. llvm::NamedMDNode *IdentMetadata =
  3207. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3208. std::string Version = getClangFullVersion();
  3209. llvm::LLVMContext &Ctx = TheModule.getContext();
  3210. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3211. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3212. }
  3213. void CodeGenModule::EmitTargetMetadata() {
  3214. // Warning, new MangledDeclNames may be appended within this loop.
  3215. // We rely on MapVector insertions adding new elements to the end
  3216. // of the container.
  3217. // FIXME: Move this loop into the one target that needs it, and only
  3218. // loop over those declarations for which we couldn't emit the target
  3219. // metadata when we emitted the declaration.
  3220. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3221. auto Val = *(MangledDeclNames.begin() + I);
  3222. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3223. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3224. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3225. }
  3226. }
  3227. void CodeGenModule::EmitCoverageFile() {
  3228. if (!getCodeGenOpts().CoverageFile.empty()) {
  3229. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  3230. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3231. llvm::LLVMContext &Ctx = TheModule.getContext();
  3232. llvm::MDString *CoverageFile =
  3233. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  3234. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3235. llvm::MDNode *CU = CUNode->getOperand(i);
  3236. llvm::Metadata *Elts[] = {CoverageFile, CU};
  3237. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3238. }
  3239. }
  3240. }
  3241. }
  3242. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3243. // Sema has checked that all uuid strings are of the form
  3244. // "12345678-1234-1234-1234-1234567890ab".
  3245. assert(Uuid.size() == 36);
  3246. for (unsigned i = 0; i < 36; ++i) {
  3247. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3248. else assert(isHexDigit(Uuid[i]));
  3249. }
  3250. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3251. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3252. llvm::Constant *Field3[8];
  3253. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3254. Field3[Idx] = llvm::ConstantInt::get(
  3255. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3256. llvm::Constant *Fields[4] = {
  3257. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3258. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3259. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3260. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3261. };
  3262. return llvm::ConstantStruct::getAnon(Fields);
  3263. }
  3264. llvm::Constant *
  3265. CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
  3266. QualType CatchHandlerType) {
  3267. return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
  3268. }
  3269. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3270. bool ForEH) {
  3271. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3272. // FIXME: should we even be calling this method if RTTI is disabled
  3273. // and it's not for EH?
  3274. if (!ForEH && !getLangOpts().RTTI)
  3275. return llvm::Constant::getNullValue(Int8PtrTy);
  3276. if (ForEH && Ty->isObjCObjectPointerType() &&
  3277. LangOpts.ObjCRuntime.isGNUFamily())
  3278. return ObjCRuntime->GetEHType(Ty);
  3279. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3280. }
  3281. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3282. #if 0 // HLSL Change - no OpenMP support
  3283. for (auto RefExpr : D->varlists()) {
  3284. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3285. bool PerformInit =
  3286. VD->getAnyInitializer() &&
  3287. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3288. /*ForRef=*/false);
  3289. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3290. VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
  3291. CXXGlobalInits.push_back(InitFunction);
  3292. }
  3293. #endif
  3294. }
  3295. llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
  3296. llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
  3297. std::string OutName;
  3298. llvm::raw_string_ostream Out(OutName);
  3299. getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
  3300. llvm::Metadata *BitsetOps[] = {
  3301. llvm::MDString::get(getLLVMContext(), Out.str()),
  3302. llvm::ConstantAsMetadata::get(VTable),
  3303. llvm::ConstantAsMetadata::get(
  3304. llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
  3305. return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
  3306. }