CodeGenModule.cpp 162 KB

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