CodeGenModule.cpp 143 KB

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