CodeGenModule.cpp 122 KB

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