CodeGenModule.cpp 144 KB

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