CodeGenModule.cpp 122 KB

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