CodeGenModule.cpp 176 KB

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