CodeGenModule.cpp 145 KB

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