CodeGenModule.cpp 165 KB

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