CodeGenModule.cpp 161 KB

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