CodeGenModule.cpp 170 KB

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