CodeGenModule.cpp 131 KB

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