CodeGenModule.cpp 201 KB

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