CodeGenModule.cpp 141 KB

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