CodeGenModule.cpp 136 KB

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