CodeGenModule.cpp 183 KB

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