CodeGenModule.cpp 154 KB

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