CodeGenModule.cpp 173 KB

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