CodeGenModule.cpp 188 KB

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