CodeGenModule.cpp 137 KB

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