CodeGenModule.cpp 126 KB

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