CodeGenModule.cpp 162 KB

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