CodeGenModule.cpp 159 KB

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