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