CodeGenModule.cpp 253 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the per-module state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenModule.h"
  13. #include "CGBlocks.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CGOpenMPRuntime.h"
  21. #include "CGOpenMPRuntimeGPU.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenPGO.h"
  24. #include "ConstantEmitter.h"
  25. #include "CoverageMappingGen.h"
  26. #include "TargetInfo.h"
  27. #include "clang/AST/ASTContext.h"
  28. #include "clang/AST/CharUnits.h"
  29. #include "clang/AST/DeclCXX.h"
  30. #include "clang/AST/DeclObjC.h"
  31. #include "clang/AST/DeclTemplate.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/RecordLayout.h"
  34. #include "clang/AST/RecursiveASTVisitor.h"
  35. #include "clang/AST/StmtVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/CodeGenOptions.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/FileManager.h"
  41. #include "clang/Basic/Module.h"
  42. #include "clang/Basic/SourceManager.h"
  43. #include "clang/Basic/TargetInfo.h"
  44. #include "clang/Basic/Version.h"
  45. #include "clang/CodeGen/ConstantInitBuilder.h"
  46. #include "clang/Frontend/FrontendDiagnostic.h"
  47. #include "llvm/ADT/StringSwitch.h"
  48. #include "llvm/ADT/Triple.h"
  49. #include "llvm/Analysis/TargetLibraryInfo.h"
  50. #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
  51. #include "llvm/IR/CallingConv.h"
  52. #include "llvm/IR/DataLayout.h"
  53. #include "llvm/IR/Intrinsics.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/Module.h"
  56. #include "llvm/IR/ProfileSummary.h"
  57. #include "llvm/ProfileData/InstrProfReader.h"
  58. #include "llvm/Support/CodeGen.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/ConvertUTF.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/MD5.h"
  63. #include "llvm/Support/TimeProfiler.h"
  64. #include "llvm/Support/X86TargetParser.h"
  65. using namespace clang;
  66. using namespace CodeGen;
  67. static llvm::cl::opt<bool> LimitedCoverage(
  68. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  69. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  70. llvm::cl::init(false));
  71. static const char AnnotationSection[] = "llvm.metadata";
  72. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  73. switch (CGM.getContext().getCXXABIKind()) {
  74. case TargetCXXABI::AppleARM64:
  75. case TargetCXXABI::Fuchsia:
  76. case TargetCXXABI::GenericAArch64:
  77. case TargetCXXABI::GenericARM:
  78. case TargetCXXABI::iOS:
  79. case TargetCXXABI::WatchOS:
  80. case TargetCXXABI::GenericMIPS:
  81. case TargetCXXABI::GenericItanium:
  82. case TargetCXXABI::WebAssembly:
  83. case TargetCXXABI::XL:
  84. return CreateItaniumCXXABI(CGM);
  85. case TargetCXXABI::Microsoft:
  86. return CreateMicrosoftCXXABI(CGM);
  87. }
  88. llvm_unreachable("invalid C++ ABI kind");
  89. }
  90. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  91. const PreprocessorOptions &PPO,
  92. const CodeGenOptions &CGO, llvm::Module &M,
  93. DiagnosticsEngine &diags,
  94. CoverageSourceInfo *CoverageInfo)
  95. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  96. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  97. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  98. VMContext(M.getContext()), Types(*this), VTables(*this),
  99. SanitizerMD(new SanitizerMetadata(*this)) {
  100. // Initialize the type cache.
  101. llvm::LLVMContext &LLVMContext = M.getContext();
  102. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  103. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  104. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  105. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  106. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  107. HalfTy = llvm::Type::getHalfTy(LLVMContext);
  108. BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
  109. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  110. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  111. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  112. PointerAlignInBytes =
  113. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  114. SizeSizeInBytes =
  115. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  116. IntAlignInBytes =
  117. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  118. CharTy =
  119. llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
  120. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  121. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  122. C.getTargetInfo().getMaxPointerWidth());
  123. Int8PtrTy = Int8Ty->getPointerTo(0);
  124. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  125. const llvm::DataLayout &DL = M.getDataLayout();
  126. AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
  127. GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
  128. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  129. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  130. if (LangOpts.ObjC)
  131. createObjCRuntime();
  132. if (LangOpts.OpenCL)
  133. createOpenCLRuntime();
  134. if (LangOpts.OpenMP)
  135. createOpenMPRuntime();
  136. if (LangOpts.CUDA)
  137. createCUDARuntime();
  138. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  139. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  140. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  141. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  142. getCXXABI().getMangleContext()));
  143. // If debug info or coverage generation is enabled, create the CGDebugInfo
  144. // object.
  145. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  146. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  147. DebugInfo.reset(new CGDebugInfo(*this));
  148. Block.GlobalUniqueCount = 0;
  149. if (C.getLangOpts().ObjC)
  150. ObjCData.reset(new ObjCEntrypoints());
  151. if (CodeGenOpts.hasProfileClangUse()) {
  152. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  153. CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
  154. if (auto E = ReaderOrErr.takeError()) {
  155. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  156. "Could not read profile %0: %1");
  157. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  158. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  159. << EI.message();
  160. });
  161. } else
  162. PGOReader = std::move(ReaderOrErr.get());
  163. }
  164. // If coverage mapping generation is enabled, create the
  165. // CoverageMappingModuleGen object.
  166. if (CodeGenOpts.CoverageMapping)
  167. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  168. // Generate the module name hash here if needed.
  169. if (CodeGenOpts.UniqueInternalLinkageNames &&
  170. !getModule().getSourceFileName().empty()) {
  171. std::string Path = getModule().getSourceFileName();
  172. // Check if a path substitution is needed from the MacroPrefixMap.
  173. for (const auto &Entry : LangOpts.MacroPrefixMap)
  174. if (Path.rfind(Entry.first, 0) != std::string::npos) {
  175. Path = Entry.second + Path.substr(Entry.first.size());
  176. break;
  177. }
  178. llvm::MD5 Md5;
  179. Md5.update(Path);
  180. llvm::MD5::MD5Result R;
  181. Md5.final(R);
  182. SmallString<32> Str;
  183. llvm::MD5::stringifyResult(R, Str);
  184. // Convert MD5hash to Decimal. Demangler suffixes can either contain
  185. // numbers or characters but not both.
  186. llvm::APInt IntHash(128, Str.str(), 16);
  187. // Prepend "__uniq" before the hash for tools like profilers to understand
  188. // that this symbol is of internal linkage type. The "__uniq" is the
  189. // pre-determined prefix that is used to tell tools that this symbol was
  190. // created with -funique-internal-linakge-symbols and the tools can strip or
  191. // keep the prefix as needed.
  192. ModuleNameHash = (Twine(".__uniq.") +
  193. Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str();
  194. }
  195. }
  196. CodeGenModule::~CodeGenModule() {}
  197. void CodeGenModule::createObjCRuntime() {
  198. // This is just isGNUFamily(), but we want to force implementors of
  199. // new ABIs to decide how best to do this.
  200. switch (LangOpts.ObjCRuntime.getKind()) {
  201. case ObjCRuntime::GNUstep:
  202. case ObjCRuntime::GCC:
  203. case ObjCRuntime::ObjFW:
  204. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  205. return;
  206. case ObjCRuntime::FragileMacOSX:
  207. case ObjCRuntime::MacOSX:
  208. case ObjCRuntime::iOS:
  209. case ObjCRuntime::WatchOS:
  210. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  211. return;
  212. }
  213. llvm_unreachable("bad runtime kind");
  214. }
  215. void CodeGenModule::createOpenCLRuntime() {
  216. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  217. }
  218. void CodeGenModule::createOpenMPRuntime() {
  219. // Select a specialized code generation class based on the target, if any.
  220. // If it does not exist use the default implementation.
  221. switch (getTriple().getArch()) {
  222. case llvm::Triple::nvptx:
  223. case llvm::Triple::nvptx64:
  224. case llvm::Triple::amdgcn:
  225. assert(getLangOpts().OpenMPIsDevice &&
  226. "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
  227. OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
  228. break;
  229. default:
  230. if (LangOpts.OpenMPSimd)
  231. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  232. else
  233. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  234. break;
  235. }
  236. }
  237. void CodeGenModule::createCUDARuntime() {
  238. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  239. }
  240. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  241. Replacements[Name] = C;
  242. }
  243. void CodeGenModule::applyReplacements() {
  244. for (auto &I : Replacements) {
  245. StringRef MangledName = I.first();
  246. llvm::Constant *Replacement = I.second;
  247. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  248. if (!Entry)
  249. continue;
  250. auto *OldF = cast<llvm::Function>(Entry);
  251. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  252. if (!NewF) {
  253. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  254. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  255. } else {
  256. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  257. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  258. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  259. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  260. }
  261. }
  262. // Replace old with new, but keep the old order.
  263. OldF->replaceAllUsesWith(Replacement);
  264. if (NewF) {
  265. NewF->removeFromParent();
  266. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  267. NewF);
  268. }
  269. OldF->eraseFromParent();
  270. }
  271. }
  272. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  273. GlobalValReplacements.push_back(std::make_pair(GV, C));
  274. }
  275. void CodeGenModule::applyGlobalValReplacements() {
  276. for (auto &I : GlobalValReplacements) {
  277. llvm::GlobalValue *GV = I.first;
  278. llvm::Constant *C = I.second;
  279. GV->replaceAllUsesWith(C);
  280. GV->eraseFromParent();
  281. }
  282. }
  283. // This is only used in aliases that we created and we know they have a
  284. // linear structure.
  285. static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
  286. const llvm::Constant *C;
  287. if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
  288. C = GA->getAliasee();
  289. else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
  290. C = GI->getResolver();
  291. else
  292. return GV;
  293. const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
  294. if (!AliaseeGV)
  295. return nullptr;
  296. const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
  297. if (FinalGV == GV)
  298. return nullptr;
  299. return FinalGV;
  300. }
  301. static bool checkAliasedGlobal(DiagnosticsEngine &Diags,
  302. SourceLocation Location, bool IsIFunc,
  303. const llvm::GlobalValue *Alias,
  304. const llvm::GlobalValue *&GV) {
  305. GV = getAliasedGlobal(Alias);
  306. if (!GV) {
  307. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  308. return false;
  309. }
  310. if (GV->isDeclaration()) {
  311. Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
  312. return false;
  313. }
  314. if (IsIFunc) {
  315. // Check resolver function type.
  316. const auto *F = dyn_cast<llvm::Function>(GV);
  317. if (!F) {
  318. Diags.Report(Location, diag::err_alias_to_undefined)
  319. << IsIFunc << IsIFunc;
  320. return false;
  321. }
  322. llvm::FunctionType *FTy = F->getFunctionType();
  323. if (!FTy->getReturnType()->isPointerTy()) {
  324. Diags.Report(Location, diag::err_ifunc_resolver_return);
  325. return false;
  326. }
  327. }
  328. return true;
  329. }
  330. void CodeGenModule::checkAliases() {
  331. // Check if the constructed aliases are well formed. It is really unfortunate
  332. // that we have to do this in CodeGen, but we only construct mangled names
  333. // and aliases during codegen.
  334. bool Error = false;
  335. DiagnosticsEngine &Diags = getDiags();
  336. for (const GlobalDecl &GD : Aliases) {
  337. const auto *D = cast<ValueDecl>(GD.getDecl());
  338. SourceLocation Location;
  339. bool IsIFunc = D->hasAttr<IFuncAttr>();
  340. if (const Attr *A = D->getDefiningAttr())
  341. Location = A->getLocation();
  342. else
  343. llvm_unreachable("Not an alias or ifunc?");
  344. StringRef MangledName = getMangledName(GD);
  345. llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
  346. const llvm::GlobalValue *GV = nullptr;
  347. if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) {
  348. Error = true;
  349. continue;
  350. }
  351. llvm::Constant *Aliasee =
  352. IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
  353. : cast<llvm::GlobalAlias>(Alias)->getAliasee();
  354. llvm::GlobalValue *AliaseeGV;
  355. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  356. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  357. else
  358. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  359. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  360. StringRef AliasSection = SA->getName();
  361. if (AliasSection != AliaseeGV->getSection())
  362. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  363. << AliasSection << IsIFunc << IsIFunc;
  364. }
  365. // We have to handle alias to weak aliases in here. LLVM itself disallows
  366. // this since the object semantics would not match the IL one. For
  367. // compatibility with gcc we implement it by just pointing the alias
  368. // to its aliasee's aliasee. We also warn, since the user is probably
  369. // expecting the link to be weak.
  370. if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
  371. if (GA->isInterposable()) {
  372. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  373. << GV->getName() << GA->getName() << IsIFunc;
  374. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  375. GA->getAliasee(), Alias->getType());
  376. if (IsIFunc)
  377. cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
  378. else
  379. cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
  380. }
  381. }
  382. }
  383. if (!Error)
  384. return;
  385. for (const GlobalDecl &GD : Aliases) {
  386. StringRef MangledName = getMangledName(GD);
  387. llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
  388. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  389. Alias->eraseFromParent();
  390. }
  391. }
  392. void CodeGenModule::clear() {
  393. DeferredDeclsToEmit.clear();
  394. if (OpenMPRuntime)
  395. OpenMPRuntime->clear();
  396. }
  397. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  398. StringRef MainFile) {
  399. if (!hasDiagnostics())
  400. return;
  401. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  402. if (MainFile.empty())
  403. MainFile = "<stdin>";
  404. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  405. } else {
  406. if (Mismatched > 0)
  407. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  408. if (Missing > 0)
  409. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  410. }
  411. }
  412. static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
  413. llvm::Module &M) {
  414. if (!LO.VisibilityFromDLLStorageClass)
  415. return;
  416. llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
  417. CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
  418. llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
  419. CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
  420. llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
  421. CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
  422. llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
  423. CodeGenModule::GetLLVMVisibility(
  424. LO.getExternDeclNoDLLStorageClassVisibility());
  425. for (llvm::GlobalValue &GV : M.global_values()) {
  426. if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
  427. continue;
  428. // Reset DSO locality before setting the visibility. This removes
  429. // any effects that visibility options and annotations may have
  430. // had on the DSO locality. Setting the visibility will implicitly set
  431. // appropriate globals to DSO Local; however, this will be pessimistic
  432. // w.r.t. to the normal compiler IRGen.
  433. GV.setDSOLocal(false);
  434. if (GV.isDeclarationForLinker()) {
  435. GV.setVisibility(GV.getDLLStorageClass() ==
  436. llvm::GlobalValue::DLLImportStorageClass
  437. ? ExternDeclDLLImportVisibility
  438. : ExternDeclNoDLLStorageClassVisibility);
  439. } else {
  440. GV.setVisibility(GV.getDLLStorageClass() ==
  441. llvm::GlobalValue::DLLExportStorageClass
  442. ? DLLExportVisibility
  443. : NoDLLStorageClassVisibility);
  444. }
  445. GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  446. }
  447. }
  448. void CodeGenModule::Release() {
  449. EmitDeferred();
  450. EmitVTablesOpportunistically();
  451. applyGlobalValReplacements();
  452. applyReplacements();
  453. checkAliases();
  454. emitMultiVersionFunctions();
  455. EmitCXXGlobalInitFunc();
  456. EmitCXXGlobalCleanUpFunc();
  457. registerGlobalDtorsWithAtExit();
  458. EmitCXXThreadLocalInitFunc();
  459. if (ObjCRuntime)
  460. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  461. AddGlobalCtor(ObjCInitFunction);
  462. if (Context.getLangOpts().CUDA && CUDARuntime) {
  463. if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
  464. AddGlobalCtor(CudaCtorFunction);
  465. }
  466. if (OpenMPRuntime) {
  467. if (llvm::Function *OpenMPRequiresDirectiveRegFun =
  468. OpenMPRuntime->emitRequiresDirectiveRegFun()) {
  469. AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
  470. }
  471. OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
  472. OpenMPRuntime->clear();
  473. }
  474. if (PGOReader) {
  475. getModule().setProfileSummary(
  476. PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
  477. llvm::ProfileSummary::PSK_Instr);
  478. if (PGOStats.hasDiagnostics())
  479. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  480. }
  481. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  482. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  483. EmitGlobalAnnotations();
  484. EmitStaticExternCAliases();
  485. EmitDeferredUnusedCoverageMappings();
  486. CodeGenPGO(*this).setValueProfilingFlag(getModule());
  487. if (CoverageMapping)
  488. CoverageMapping->emit();
  489. if (CodeGenOpts.SanitizeCfiCrossDso) {
  490. CodeGenFunction(*this).EmitCfiCheckFail();
  491. CodeGenFunction(*this).EmitCfiCheckStub();
  492. }
  493. emitAtAvailableLinkGuard();
  494. if (Context.getTargetInfo().getTriple().isWasm() &&
  495. !Context.getTargetInfo().getTriple().isOSEmscripten()) {
  496. EmitMainVoidAlias();
  497. }
  498. // Emit reference of __amdgpu_device_library_preserve_asan_functions to
  499. // preserve ASAN functions in bitcode libraries.
  500. if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) {
  501. auto *FT = llvm::FunctionType::get(VoidTy, {});
  502. auto *F = llvm::Function::Create(
  503. FT, llvm::GlobalValue::ExternalLinkage,
  504. "__amdgpu_device_library_preserve_asan_functions", &getModule());
  505. auto *Var = new llvm::GlobalVariable(
  506. getModule(), FT->getPointerTo(),
  507. /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
  508. "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
  509. llvm::GlobalVariable::NotThreadLocal);
  510. addCompilerUsedGlobal(Var);
  511. if (!getModule().getModuleFlag("amdgpu_hostcall")) {
  512. getModule().addModuleFlag(llvm::Module::Override, "amdgpu_hostcall", 1);
  513. }
  514. }
  515. emitLLVMUsed();
  516. if (SanStats)
  517. SanStats->finish();
  518. if (CodeGenOpts.Autolink &&
  519. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  520. EmitModuleLinkOptions();
  521. }
  522. // On ELF we pass the dependent library specifiers directly to the linker
  523. // without manipulating them. This is in contrast to other platforms where
  524. // they are mapped to a specific linker option by the compiler. This
  525. // difference is a result of the greater variety of ELF linkers and the fact
  526. // that ELF linkers tend to handle libraries in a more complicated fashion
  527. // than on other platforms. This forces us to defer handling the dependent
  528. // libs to the linker.
  529. //
  530. // CUDA/HIP device and host libraries are different. Currently there is no
  531. // way to differentiate dependent libraries for host or device. Existing
  532. // usage of #pragma comment(lib, *) is intended for host libraries on
  533. // Windows. Therefore emit llvm.dependent-libraries only for host.
  534. if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
  535. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
  536. for (auto *MD : ELFDependentLibraries)
  537. NMD->addOperand(MD);
  538. }
  539. // Record mregparm value now so it is visible through rest of codegen.
  540. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  541. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  542. CodeGenOpts.NumRegisterParameters);
  543. if (CodeGenOpts.DwarfVersion) {
  544. getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
  545. CodeGenOpts.DwarfVersion);
  546. }
  547. if (CodeGenOpts.Dwarf64)
  548. getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
  549. if (Context.getLangOpts().SemanticInterposition)
  550. // Require various optimization to respect semantic interposition.
  551. getModule().setSemanticInterposition(true);
  552. if (CodeGenOpts.EmitCodeView) {
  553. // Indicate that we want CodeView in the metadata.
  554. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  555. }
  556. if (CodeGenOpts.CodeViewGHash) {
  557. getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
  558. }
  559. if (CodeGenOpts.ControlFlowGuard) {
  560. // Function ID tables and checks for Control Flow Guard (cfguard=2).
  561. getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
  562. } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
  563. // Function ID tables for Control Flow Guard (cfguard=1).
  564. getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
  565. }
  566. if (CodeGenOpts.EHContGuard) {
  567. // Function ID tables for EH Continuation Guard.
  568. getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
  569. }
  570. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  571. // We don't support LTO with 2 with different StrictVTablePointers
  572. // FIXME: we could support it by stripping all the information introduced
  573. // by StrictVTablePointers.
  574. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  575. llvm::Metadata *Ops[2] = {
  576. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  577. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  578. llvm::Type::getInt32Ty(VMContext), 1))};
  579. getModule().addModuleFlag(llvm::Module::Require,
  580. "StrictVTablePointersRequirement",
  581. llvm::MDNode::get(VMContext, Ops));
  582. }
  583. if (getModuleDebugInfo())
  584. // We support a single version in the linked module. The LLVM
  585. // parser will drop debug info with a different version number
  586. // (and warn about it, too).
  587. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  588. llvm::DEBUG_METADATA_VERSION);
  589. // We need to record the widths of enums and wchar_t, so that we can generate
  590. // the correct build attributes in the ARM backend. wchar_size is also used by
  591. // TargetLibraryInfo.
  592. uint64_t WCharWidth =
  593. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  594. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  595. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  596. if ( Arch == llvm::Triple::arm
  597. || Arch == llvm::Triple::armeb
  598. || Arch == llvm::Triple::thumb
  599. || Arch == llvm::Triple::thumbeb) {
  600. // The minimum width of an enum in bytes
  601. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  602. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  603. }
  604. if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
  605. StringRef ABIStr = Target.getABI();
  606. llvm::LLVMContext &Ctx = TheModule.getContext();
  607. getModule().addModuleFlag(llvm::Module::Error, "target-abi",
  608. llvm::MDString::get(Ctx, ABIStr));
  609. }
  610. if (CodeGenOpts.SanitizeCfiCrossDso) {
  611. // Indicate that we want cross-DSO control flow integrity checks.
  612. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  613. }
  614. if (CodeGenOpts.WholeProgramVTables) {
  615. // Indicate whether VFE was enabled for this module, so that the
  616. // vcall_visibility metadata added under whole program vtables is handled
  617. // appropriately in the optimizer.
  618. getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
  619. CodeGenOpts.VirtualFunctionElimination);
  620. }
  621. if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
  622. getModule().addModuleFlag(llvm::Module::Override,
  623. "CFI Canonical Jump Tables",
  624. CodeGenOpts.SanitizeCfiCanonicalJumpTables);
  625. }
  626. if (CodeGenOpts.CFProtectionReturn &&
  627. Target.checkCFProtectionReturnSupported(getDiags())) {
  628. // Indicate that we want to instrument return control flow protection.
  629. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  630. 1);
  631. }
  632. if (CodeGenOpts.CFProtectionBranch &&
  633. Target.checkCFProtectionBranchSupported(getDiags())) {
  634. // Indicate that we want to instrument branch control flow protection.
  635. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  636. 1);
  637. }
  638. if (CodeGenOpts.IBTSeal)
  639. getModule().addModuleFlag(llvm::Module::Override, "ibt-seal", 1);
  640. // Add module metadata for return address signing (ignoring
  641. // non-leaf/all) and stack tagging. These are actually turned on by function
  642. // attributes, but we use module metadata to emit build attributes. This is
  643. // needed for LTO, where the function attributes are inside bitcode
  644. // serialised into a global variable by the time build attributes are
  645. // emitted, so we can't access them.
  646. if (Context.getTargetInfo().hasFeature("ptrauth") &&
  647. LangOpts.getSignReturnAddressScope() !=
  648. LangOptions::SignReturnAddressScopeKind::None)
  649. getModule().addModuleFlag(llvm::Module::Override,
  650. "sign-return-address-buildattr", 1);
  651. if (LangOpts.Sanitize.has(SanitizerKind::MemTag))
  652. getModule().addModuleFlag(llvm::Module::Override,
  653. "tag-stack-memory-buildattr", 1);
  654. if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
  655. Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  656. Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
  657. Arch == llvm::Triple::aarch64_be) {
  658. getModule().addModuleFlag(llvm::Module::Error, "branch-target-enforcement",
  659. LangOpts.BranchTargetEnforcement);
  660. getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
  661. LangOpts.hasSignReturnAddress());
  662. getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
  663. LangOpts.isSignReturnAddressScopeAll());
  664. getModule().addModuleFlag(llvm::Module::Error,
  665. "sign-return-address-with-bkey",
  666. !LangOpts.isSignReturnAddressWithAKey());
  667. }
  668. if (!CodeGenOpts.MemoryProfileOutput.empty()) {
  669. llvm::LLVMContext &Ctx = TheModule.getContext();
  670. getModule().addModuleFlag(
  671. llvm::Module::Error, "MemProfProfileFilename",
  672. llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
  673. }
  674. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  675. // Indicate whether __nvvm_reflect should be configured to flush denormal
  676. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  677. // property.)
  678. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  679. CodeGenOpts.FP32DenormalMode.Output !=
  680. llvm::DenormalMode::IEEE);
  681. }
  682. if (LangOpts.EHAsynch)
  683. getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
  684. // Indicate whether this Module was compiled with -fopenmp
  685. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
  686. getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
  687. if (getLangOpts().OpenMPIsDevice)
  688. getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
  689. LangOpts.OpenMP);
  690. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  691. if (LangOpts.OpenCL) {
  692. EmitOpenCLMetadata();
  693. // Emit SPIR version.
  694. if (getTriple().isSPIR()) {
  695. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  696. // opencl.spir.version named metadata.
  697. // C++ for OpenCL has a distinct mapping for version compatibility with
  698. // OpenCL.
  699. auto Version = LangOpts.getOpenCLCompatibleVersion();
  700. llvm::Metadata *SPIRVerElts[] = {
  701. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  702. Int32Ty, Version / 100)),
  703. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  704. Int32Ty, (Version / 100 > 1) ? 0 : 2))};
  705. llvm::NamedMDNode *SPIRVerMD =
  706. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  707. llvm::LLVMContext &Ctx = TheModule.getContext();
  708. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  709. }
  710. }
  711. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  712. assert(PLevel < 3 && "Invalid PIC Level");
  713. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  714. if (Context.getLangOpts().PIE)
  715. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  716. }
  717. if (getCodeGenOpts().CodeModel.size() > 0) {
  718. unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
  719. .Case("tiny", llvm::CodeModel::Tiny)
  720. .Case("small", llvm::CodeModel::Small)
  721. .Case("kernel", llvm::CodeModel::Kernel)
  722. .Case("medium", llvm::CodeModel::Medium)
  723. .Case("large", llvm::CodeModel::Large)
  724. .Default(~0u);
  725. if (CM != ~0u) {
  726. llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
  727. getModule().setCodeModel(codeModel);
  728. }
  729. }
  730. if (CodeGenOpts.NoPLT)
  731. getModule().setRtLibUseGOT();
  732. if (CodeGenOpts.UnwindTables)
  733. getModule().setUwtable();
  734. switch (CodeGenOpts.getFramePointer()) {
  735. case CodeGenOptions::FramePointerKind::None:
  736. // 0 ("none") is the default.
  737. break;
  738. case CodeGenOptions::FramePointerKind::NonLeaf:
  739. getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
  740. break;
  741. case CodeGenOptions::FramePointerKind::All:
  742. getModule().setFramePointer(llvm::FramePointerKind::All);
  743. break;
  744. }
  745. SimplifyPersonality();
  746. if (getCodeGenOpts().EmitDeclMetadata)
  747. EmitDeclMetadata();
  748. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  749. EmitCoverageFile();
  750. if (CGDebugInfo *DI = getModuleDebugInfo())
  751. DI->finalize();
  752. if (getCodeGenOpts().EmitVersionIdentMetadata)
  753. EmitVersionIdentMetadata();
  754. if (!getCodeGenOpts().RecordCommandLine.empty())
  755. EmitCommandLineMetadata();
  756. if (!getCodeGenOpts().StackProtectorGuard.empty())
  757. getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
  758. if (!getCodeGenOpts().StackProtectorGuardReg.empty())
  759. getModule().setStackProtectorGuardReg(
  760. getCodeGenOpts().StackProtectorGuardReg);
  761. if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
  762. getModule().setStackProtectorGuardOffset(
  763. getCodeGenOpts().StackProtectorGuardOffset);
  764. if (getCodeGenOpts().StackAlignment)
  765. getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
  766. if (getCodeGenOpts().SkipRaxSetup)
  767. getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
  768. getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
  769. EmitBackendOptionsMetadata(getCodeGenOpts());
  770. // Set visibility from DLL storage class
  771. // We do this at the end of LLVM IR generation; after any operation
  772. // that might affect the DLL storage class or the visibility, and
  773. // before anything that might act on these.
  774. setVisibilityFromDLLStorageClass(LangOpts, getModule());
  775. }
  776. void CodeGenModule::EmitOpenCLMetadata() {
  777. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  778. // opencl.ocl.version named metadata node.
  779. // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
  780. auto Version = LangOpts.getOpenCLCompatibleVersion();
  781. llvm::Metadata *OCLVerElts[] = {
  782. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  783. Int32Ty, Version / 100)),
  784. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  785. Int32Ty, (Version % 100) / 10))};
  786. llvm::NamedMDNode *OCLVerMD =
  787. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  788. llvm::LLVMContext &Ctx = TheModule.getContext();
  789. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  790. }
  791. void CodeGenModule::EmitBackendOptionsMetadata(
  792. const CodeGenOptions CodeGenOpts) {
  793. switch (getTriple().getArch()) {
  794. default:
  795. break;
  796. case llvm::Triple::riscv32:
  797. case llvm::Triple::riscv64:
  798. getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
  799. CodeGenOpts.SmallDataLimit);
  800. break;
  801. }
  802. }
  803. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  804. // Make sure that this type is translated.
  805. Types.UpdateCompletedType(TD);
  806. }
  807. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  808. // Make sure that this type is translated.
  809. Types.RefreshTypeCacheForClass(RD);
  810. }
  811. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  812. if (!TBAA)
  813. return nullptr;
  814. return TBAA->getTypeInfo(QTy);
  815. }
  816. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  817. if (!TBAA)
  818. return TBAAAccessInfo();
  819. if (getLangOpts().CUDAIsDevice) {
  820. // As CUDA builtin surface/texture types are replaced, skip generating TBAA
  821. // access info.
  822. if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
  823. if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
  824. nullptr)
  825. return TBAAAccessInfo();
  826. } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
  827. if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
  828. nullptr)
  829. return TBAAAccessInfo();
  830. }
  831. }
  832. return TBAA->getAccessInfo(AccessType);
  833. }
  834. TBAAAccessInfo
  835. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  836. if (!TBAA)
  837. return TBAAAccessInfo();
  838. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  839. }
  840. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  841. if (!TBAA)
  842. return nullptr;
  843. return TBAA->getTBAAStructInfo(QTy);
  844. }
  845. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  846. if (!TBAA)
  847. return nullptr;
  848. return TBAA->getBaseTypeInfo(QTy);
  849. }
  850. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  851. if (!TBAA)
  852. return nullptr;
  853. return TBAA->getAccessTagInfo(Info);
  854. }
  855. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  856. TBAAAccessInfo TargetInfo) {
  857. if (!TBAA)
  858. return TBAAAccessInfo();
  859. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  860. }
  861. TBAAAccessInfo
  862. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  863. TBAAAccessInfo InfoB) {
  864. if (!TBAA)
  865. return TBAAAccessInfo();
  866. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  867. }
  868. TBAAAccessInfo
  869. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  870. TBAAAccessInfo SrcInfo) {
  871. if (!TBAA)
  872. return TBAAAccessInfo();
  873. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  874. }
  875. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  876. TBAAAccessInfo TBAAInfo) {
  877. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  878. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  879. }
  880. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  881. llvm::Instruction *I, const CXXRecordDecl *RD) {
  882. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  883. llvm::MDNode::get(getLLVMContext(), {}));
  884. }
  885. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  886. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  887. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  888. }
  889. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  890. /// specified stmt yet.
  891. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  892. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  893. "cannot compile this %0 yet");
  894. std::string Msg = Type;
  895. getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
  896. << Msg << S->getSourceRange();
  897. }
  898. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  899. /// specified decl yet.
  900. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  901. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  902. "cannot compile this %0 yet");
  903. std::string Msg = Type;
  904. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  905. }
  906. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  907. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  908. }
  909. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  910. const NamedDecl *D) const {
  911. if (GV->hasDLLImportStorageClass())
  912. return;
  913. // Internal definitions always have default visibility.
  914. if (GV->hasLocalLinkage()) {
  915. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  916. return;
  917. }
  918. if (!D)
  919. return;
  920. // Set visibility for definitions, and for declarations if requested globally
  921. // or set explicitly.
  922. LinkageInfo LV = D->getLinkageAndVisibility();
  923. if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
  924. !GV->isDeclarationForLinker())
  925. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  926. }
  927. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  928. llvm::GlobalValue *GV) {
  929. if (GV->hasLocalLinkage())
  930. return true;
  931. if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
  932. return true;
  933. // DLLImport explicitly marks the GV as external.
  934. if (GV->hasDLLImportStorageClass())
  935. return false;
  936. const llvm::Triple &TT = CGM.getTriple();
  937. if (TT.isWindowsGNUEnvironment()) {
  938. // In MinGW, variables without DLLImport can still be automatically
  939. // imported from a DLL by the linker; don't mark variables that
  940. // potentially could come from another DLL as DSO local.
  941. // With EmulatedTLS, TLS variables can be autoimported from other DLLs
  942. // (and this actually happens in the public interface of libstdc++), so
  943. // such variables can't be marked as DSO local. (Native TLS variables
  944. // can't be dllimported at all, though.)
  945. if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
  946. (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
  947. return false;
  948. }
  949. // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
  950. // remain unresolved in the link, they can be resolved to zero, which is
  951. // outside the current DSO.
  952. if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
  953. return false;
  954. // Every other GV is local on COFF.
  955. // Make an exception for windows OS in the triple: Some firmware builds use
  956. // *-win32-macho triples. This (accidentally?) produced windows relocations
  957. // without GOT tables in older clang versions; Keep this behaviour.
  958. // FIXME: even thread local variables?
  959. if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
  960. return true;
  961. // Only handle COFF and ELF for now.
  962. if (!TT.isOSBinFormatELF())
  963. return false;
  964. // If this is not an executable, don't assume anything is local.
  965. const auto &CGOpts = CGM.getCodeGenOpts();
  966. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  967. const auto &LOpts = CGM.getLangOpts();
  968. if (RM != llvm::Reloc::Static && !LOpts.PIE) {
  969. // On ELF, if -fno-semantic-interposition is specified and the target
  970. // supports local aliases, there will be neither CC1
  971. // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
  972. // dso_local on the function if using a local alias is preferable (can avoid
  973. // PLT indirection).
  974. if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
  975. return false;
  976. return !(CGM.getLangOpts().SemanticInterposition ||
  977. CGM.getLangOpts().HalfNoSemanticInterposition);
  978. }
  979. // A definition cannot be preempted from an executable.
  980. if (!GV->isDeclarationForLinker())
  981. return true;
  982. // Most PIC code sequences that assume that a symbol is local cannot produce a
  983. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  984. // depended, it seems worth it to handle it here.
  985. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  986. return false;
  987. // PowerPC64 prefers TOC indirection to avoid copy relocations.
  988. if (TT.isPPC64())
  989. return false;
  990. if (CGOpts.DirectAccessExternalData) {
  991. // If -fdirect-access-external-data (default for -fno-pic), set dso_local
  992. // for non-thread-local variables. If the symbol is not defined in the
  993. // executable, a copy relocation will be needed at link time. dso_local is
  994. // excluded for thread-local variables because they generally don't support
  995. // copy relocations.
  996. if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
  997. if (!Var->isThreadLocal())
  998. return true;
  999. // -fno-pic sets dso_local on a function declaration to allow direct
  1000. // accesses when taking its address (similar to a data symbol). If the
  1001. // function is not defined in the executable, a canonical PLT entry will be
  1002. // needed at link time. -fno-direct-access-external-data can avoid the
  1003. // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
  1004. // it could just cause trouble without providing perceptible benefits.
  1005. if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  1006. return true;
  1007. }
  1008. // If we can use copy relocations we can assume it is local.
  1009. // Otherwise don't assume it is local.
  1010. return false;
  1011. }
  1012. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
  1013. GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
  1014. }
  1015. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  1016. GlobalDecl GD) const {
  1017. const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
  1018. // C++ destructors have a few C++ ABI specific special cases.
  1019. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
  1020. getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
  1021. return;
  1022. }
  1023. setDLLImportDLLExport(GV, D);
  1024. }
  1025. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  1026. const NamedDecl *D) const {
  1027. if (D && D->isExternallyVisible()) {
  1028. if (D->hasAttr<DLLImportAttr>())
  1029. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  1030. else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
  1031. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  1032. }
  1033. }
  1034. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  1035. GlobalDecl GD) const {
  1036. setDLLImportDLLExport(GV, GD);
  1037. setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
  1038. }
  1039. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  1040. const NamedDecl *D) const {
  1041. setDLLImportDLLExport(GV, D);
  1042. setGVPropertiesAux(GV, D);
  1043. }
  1044. void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
  1045. const NamedDecl *D) const {
  1046. setGlobalVisibility(GV, D);
  1047. setDSOLocal(GV);
  1048. GV->setPartition(CodeGenOpts.SymbolPartition);
  1049. }
  1050. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  1051. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  1052. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  1053. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  1054. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  1055. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  1056. }
  1057. llvm::GlobalVariable::ThreadLocalMode
  1058. CodeGenModule::GetDefaultLLVMTLSModel() const {
  1059. switch (CodeGenOpts.getDefaultTLSModel()) {
  1060. case CodeGenOptions::GeneralDynamicTLSModel:
  1061. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  1062. case CodeGenOptions::LocalDynamicTLSModel:
  1063. return llvm::GlobalVariable::LocalDynamicTLSModel;
  1064. case CodeGenOptions::InitialExecTLSModel:
  1065. return llvm::GlobalVariable::InitialExecTLSModel;
  1066. case CodeGenOptions::LocalExecTLSModel:
  1067. return llvm::GlobalVariable::LocalExecTLSModel;
  1068. }
  1069. llvm_unreachable("Invalid TLS model!");
  1070. }
  1071. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  1072. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  1073. llvm::GlobalValue::ThreadLocalMode TLM;
  1074. TLM = GetDefaultLLVMTLSModel();
  1075. // Override the TLS model if it is explicitly specified.
  1076. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  1077. TLM = GetLLVMTLSModel(Attr->getModel());
  1078. }
  1079. GV->setThreadLocalMode(TLM);
  1080. }
  1081. static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
  1082. StringRef Name) {
  1083. const TargetInfo &Target = CGM.getTarget();
  1084. return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
  1085. }
  1086. static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
  1087. const CPUSpecificAttr *Attr,
  1088. unsigned CPUIndex,
  1089. raw_ostream &Out) {
  1090. // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
  1091. // supported.
  1092. if (Attr)
  1093. Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
  1094. else if (CGM.getTarget().supportsIFunc())
  1095. Out << ".resolver";
  1096. }
  1097. static void AppendTargetMangling(const CodeGenModule &CGM,
  1098. const TargetAttr *Attr, raw_ostream &Out) {
  1099. if (Attr->isDefaultVersion())
  1100. return;
  1101. Out << '.';
  1102. const TargetInfo &Target = CGM.getTarget();
  1103. ParsedTargetAttr Info =
  1104. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  1105. // Multiversioning doesn't allow "no-${feature}", so we can
  1106. // only have "+" prefixes here.
  1107. assert(LHS.startswith("+") && RHS.startswith("+") &&
  1108. "Features should always have a prefix.");
  1109. return Target.multiVersionSortPriority(LHS.substr(1)) >
  1110. Target.multiVersionSortPriority(RHS.substr(1));
  1111. });
  1112. bool IsFirst = true;
  1113. if (!Info.Architecture.empty()) {
  1114. IsFirst = false;
  1115. Out << "arch_" << Info.Architecture;
  1116. }
  1117. for (StringRef Feat : Info.Features) {
  1118. if (!IsFirst)
  1119. Out << '_';
  1120. IsFirst = false;
  1121. Out << Feat.substr(1);
  1122. }
  1123. }
  1124. // Returns true if GD is a function decl with internal linkage and
  1125. // needs a unique suffix after the mangled name.
  1126. static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
  1127. CodeGenModule &CGM) {
  1128. const Decl *D = GD.getDecl();
  1129. return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
  1130. (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
  1131. }
  1132. static void AppendTargetClonesMangling(const CodeGenModule &CGM,
  1133. const TargetClonesAttr *Attr,
  1134. unsigned VersionIndex,
  1135. raw_ostream &Out) {
  1136. Out << '.';
  1137. StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
  1138. if (FeatureStr.startswith("arch="))
  1139. Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
  1140. else
  1141. Out << FeatureStr;
  1142. Out << '.' << Attr->getMangledIndex(VersionIndex);
  1143. }
  1144. static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
  1145. const NamedDecl *ND,
  1146. bool OmitMultiVersionMangling = false) {
  1147. SmallString<256> Buffer;
  1148. llvm::raw_svector_ostream Out(Buffer);
  1149. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  1150. if (!CGM.getModuleNameHash().empty())
  1151. MC.needsUniqueInternalLinkageNames();
  1152. bool ShouldMangle = MC.shouldMangleDeclName(ND);
  1153. if (ShouldMangle)
  1154. MC.mangleName(GD.getWithDecl(ND), Out);
  1155. else {
  1156. IdentifierInfo *II = ND->getIdentifier();
  1157. assert(II && "Attempt to mangle unnamed decl.");
  1158. const auto *FD = dyn_cast<FunctionDecl>(ND);
  1159. if (FD &&
  1160. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  1161. Out << "__regcall3__" << II->getName();
  1162. } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
  1163. GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
  1164. Out << "__device_stub__" << II->getName();
  1165. } else {
  1166. Out << II->getName();
  1167. }
  1168. }
  1169. // Check if the module name hash should be appended for internal linkage
  1170. // symbols. This should come before multi-version target suffixes are
  1171. // appended. This is to keep the name and module hash suffix of the
  1172. // internal linkage function together. The unique suffix should only be
  1173. // added when name mangling is done to make sure that the final name can
  1174. // be properly demangled. For example, for C functions without prototypes,
  1175. // name mangling is not done and the unique suffix should not be appeneded
  1176. // then.
  1177. if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
  1178. assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
  1179. "Hash computed when not explicitly requested");
  1180. Out << CGM.getModuleNameHash();
  1181. }
  1182. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  1183. if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
  1184. switch (FD->getMultiVersionKind()) {
  1185. case MultiVersionKind::CPUDispatch:
  1186. case MultiVersionKind::CPUSpecific:
  1187. AppendCPUSpecificCPUDispatchMangling(CGM,
  1188. FD->getAttr<CPUSpecificAttr>(),
  1189. GD.getMultiVersionIndex(), Out);
  1190. break;
  1191. case MultiVersionKind::Target:
  1192. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  1193. break;
  1194. case MultiVersionKind::TargetClones:
  1195. AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
  1196. GD.getMultiVersionIndex(), Out);
  1197. break;
  1198. case MultiVersionKind::None:
  1199. llvm_unreachable("None multiversion type isn't valid here");
  1200. }
  1201. }
  1202. // Make unique name for device side static file-scope variable for HIP.
  1203. if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
  1204. CGM.getLangOpts().GPURelocatableDeviceCode &&
  1205. CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
  1206. CGM.printPostfixForExternalizedDecl(Out, ND);
  1207. return std::string(Out.str());
  1208. }
  1209. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  1210. const FunctionDecl *FD,
  1211. StringRef &CurName) {
  1212. if (!FD->isMultiVersion())
  1213. return;
  1214. // Get the name of what this would be without the 'target' attribute. This
  1215. // allows us to lookup the version that was emitted when this wasn't a
  1216. // multiversion function.
  1217. std::string NonTargetName =
  1218. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  1219. GlobalDecl OtherGD;
  1220. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  1221. assert(OtherGD.getCanonicalDecl()
  1222. .getDecl()
  1223. ->getAsFunction()
  1224. ->isMultiVersion() &&
  1225. "Other GD should now be a multiversioned function");
  1226. // OtherFD is the version of this function that was mangled BEFORE
  1227. // becoming a MultiVersion function. It potentially needs to be updated.
  1228. const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
  1229. .getDecl()
  1230. ->getAsFunction()
  1231. ->getMostRecentDecl();
  1232. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  1233. // This is so that if the initial version was already the 'default'
  1234. // version, we don't try to update it.
  1235. if (OtherName != NonTargetName) {
  1236. // Remove instead of erase, since others may have stored the StringRef
  1237. // to this.
  1238. const auto ExistingRecord = Manglings.find(NonTargetName);
  1239. if (ExistingRecord != std::end(Manglings))
  1240. Manglings.remove(&(*ExistingRecord));
  1241. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  1242. StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
  1243. Result.first->first();
  1244. // If this is the current decl is being created, make sure we update the name.
  1245. if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
  1246. CurName = OtherNameRef;
  1247. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  1248. Entry->setName(OtherName);
  1249. }
  1250. }
  1251. }
  1252. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  1253. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  1254. // Some ABIs don't have constructor variants. Make sure that base and
  1255. // complete constructors get mangled the same.
  1256. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  1257. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  1258. CXXCtorType OrigCtorType = GD.getCtorType();
  1259. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  1260. if (OrigCtorType == Ctor_Base)
  1261. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  1262. }
  1263. }
  1264. // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
  1265. // static device variable depends on whether the variable is referenced by
  1266. // a host or device host function. Therefore the mangled name cannot be
  1267. // cached.
  1268. if (!LangOpts.CUDAIsDevice ||
  1269. !getContext().mayExternalizeStaticVar(GD.getDecl())) {
  1270. auto FoundName = MangledDeclNames.find(CanonicalGD);
  1271. if (FoundName != MangledDeclNames.end())
  1272. return FoundName->second;
  1273. }
  1274. // Keep the first result in the case of a mangling collision.
  1275. const auto *ND = cast<NamedDecl>(GD.getDecl());
  1276. std::string MangledName = getMangledNameImpl(*this, GD, ND);
  1277. // Ensure either we have different ABIs between host and device compilations,
  1278. // says host compilation following MSVC ABI but device compilation follows
  1279. // Itanium C++ ABI or, if they follow the same ABI, kernel names after
  1280. // mangling should be the same after name stubbing. The later checking is
  1281. // very important as the device kernel name being mangled in host-compilation
  1282. // is used to resolve the device binaries to be executed. Inconsistent naming
  1283. // result in undefined behavior. Even though we cannot check that naming
  1284. // directly between host- and device-compilations, the host- and
  1285. // device-mangling in host compilation could help catching certain ones.
  1286. assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
  1287. getContext().shouldExternalizeStaticVar(ND) || getLangOpts().CUDAIsDevice ||
  1288. (getContext().getAuxTargetInfo() &&
  1289. (getContext().getAuxTargetInfo()->getCXXABI() !=
  1290. getContext().getTargetInfo().getCXXABI())) ||
  1291. getCUDARuntime().getDeviceSideName(ND) ==
  1292. getMangledNameImpl(
  1293. *this,
  1294. GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
  1295. ND));
  1296. auto Result = Manglings.insert(std::make_pair(MangledName, GD));
  1297. return MangledDeclNames[CanonicalGD] = Result.first->first();
  1298. }
  1299. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  1300. const BlockDecl *BD) {
  1301. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  1302. const Decl *D = GD.getDecl();
  1303. SmallString<256> Buffer;
  1304. llvm::raw_svector_ostream Out(Buffer);
  1305. if (!D)
  1306. MangleCtx.mangleGlobalBlock(BD,
  1307. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  1308. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  1309. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  1310. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  1311. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  1312. else
  1313. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  1314. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  1315. return Result.first->first();
  1316. }
  1317. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  1318. return getModule().getNamedValue(Name);
  1319. }
  1320. /// AddGlobalCtor - Add a function to the list that will be called before
  1321. /// main() runs.
  1322. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  1323. llvm::Constant *AssociatedData) {
  1324. // FIXME: Type coercion of void()* types.
  1325. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  1326. }
  1327. /// AddGlobalDtor - Add a function to the list that will be called
  1328. /// when the module is unloaded.
  1329. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
  1330. bool IsDtorAttrFunc) {
  1331. if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
  1332. (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
  1333. DtorsUsingAtExit[Priority].push_back(Dtor);
  1334. return;
  1335. }
  1336. // FIXME: Type coercion of void()* types.
  1337. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  1338. }
  1339. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  1340. if (Fns.empty()) return;
  1341. // Ctor function type is void()*.
  1342. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  1343. llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
  1344. TheModule.getDataLayout().getProgramAddressSpace());
  1345. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  1346. llvm::StructType *CtorStructTy = llvm::StructType::get(
  1347. Int32Ty, CtorPFTy, VoidPtrTy);
  1348. // Construct the constructor and destructor arrays.
  1349. ConstantInitBuilder builder(*this);
  1350. auto ctors = builder.beginArray(CtorStructTy);
  1351. for (const auto &I : Fns) {
  1352. auto ctor = ctors.beginStruct(CtorStructTy);
  1353. ctor.addInt(Int32Ty, I.Priority);
  1354. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  1355. if (I.AssociatedData)
  1356. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  1357. else
  1358. ctor.addNullPointer(VoidPtrTy);
  1359. ctor.finishAndAddTo(ctors);
  1360. }
  1361. auto list =
  1362. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  1363. /*constant*/ false,
  1364. llvm::GlobalValue::AppendingLinkage);
  1365. // The LTO linker doesn't seem to like it when we set an alignment
  1366. // on appending variables. Take it off as a workaround.
  1367. list->setAlignment(llvm::None);
  1368. Fns.clear();
  1369. }
  1370. llvm::GlobalValue::LinkageTypes
  1371. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  1372. const auto *D = cast<FunctionDecl>(GD.getDecl());
  1373. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  1374. if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
  1375. return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
  1376. if (isa<CXXConstructorDecl>(D) &&
  1377. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  1378. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1379. // Our approach to inheriting constructors is fundamentally different from
  1380. // that used by the MS ABI, so keep our inheriting constructor thunks
  1381. // internal rather than trying to pick an unambiguous mangling for them.
  1382. return llvm::GlobalValue::InternalLinkage;
  1383. }
  1384. return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
  1385. }
  1386. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  1387. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  1388. if (!MDS) return nullptr;
  1389. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  1390. }
  1391. void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
  1392. const CGFunctionInfo &Info,
  1393. llvm::Function *F, bool IsThunk) {
  1394. unsigned CallingConv;
  1395. llvm::AttributeList PAL;
  1396. ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
  1397. /*AttrOnCallSite=*/false, IsThunk);
  1398. F->setAttributes(PAL);
  1399. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  1400. }
  1401. static void removeImageAccessQualifier(std::string& TyName) {
  1402. std::string ReadOnlyQual("__read_only");
  1403. std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
  1404. if (ReadOnlyPos != std::string::npos)
  1405. // "+ 1" for the space after access qualifier.
  1406. TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
  1407. else {
  1408. std::string WriteOnlyQual("__write_only");
  1409. std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
  1410. if (WriteOnlyPos != std::string::npos)
  1411. TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
  1412. else {
  1413. std::string ReadWriteQual("__read_write");
  1414. std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
  1415. if (ReadWritePos != std::string::npos)
  1416. TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
  1417. }
  1418. }
  1419. }
  1420. // Returns the address space id that should be produced to the
  1421. // kernel_arg_addr_space metadata. This is always fixed to the ids
  1422. // as specified in the SPIR 2.0 specification in order to differentiate
  1423. // for example in clGetKernelArgInfo() implementation between the address
  1424. // spaces with targets without unique mapping to the OpenCL address spaces
  1425. // (basically all single AS CPUs).
  1426. static unsigned ArgInfoAddressSpace(LangAS AS) {
  1427. switch (AS) {
  1428. case LangAS::opencl_global:
  1429. return 1;
  1430. case LangAS::opencl_constant:
  1431. return 2;
  1432. case LangAS::opencl_local:
  1433. return 3;
  1434. case LangAS::opencl_generic:
  1435. return 4; // Not in SPIR 2.0 specs.
  1436. case LangAS::opencl_global_device:
  1437. return 5;
  1438. case LangAS::opencl_global_host:
  1439. return 6;
  1440. default:
  1441. return 0; // Assume private.
  1442. }
  1443. }
  1444. void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
  1445. const FunctionDecl *FD,
  1446. CodeGenFunction *CGF) {
  1447. assert(((FD && CGF) || (!FD && !CGF)) &&
  1448. "Incorrect use - FD and CGF should either be both null or not!");
  1449. // Create MDNodes that represent the kernel arg metadata.
  1450. // Each MDNode is a list in the form of "key", N number of values which is
  1451. // the same number of values as their are kernel arguments.
  1452. const PrintingPolicy &Policy = Context.getPrintingPolicy();
  1453. // MDNode for the kernel argument address space qualifiers.
  1454. SmallVector<llvm::Metadata *, 8> addressQuals;
  1455. // MDNode for the kernel argument access qualifiers (images only).
  1456. SmallVector<llvm::Metadata *, 8> accessQuals;
  1457. // MDNode for the kernel argument type names.
  1458. SmallVector<llvm::Metadata *, 8> argTypeNames;
  1459. // MDNode for the kernel argument base type names.
  1460. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  1461. // MDNode for the kernel argument type qualifiers.
  1462. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  1463. // MDNode for the kernel argument names.
  1464. SmallVector<llvm::Metadata *, 8> argNames;
  1465. if (FD && CGF)
  1466. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  1467. const ParmVarDecl *parm = FD->getParamDecl(i);
  1468. QualType ty = parm->getType();
  1469. std::string typeQuals;
  1470. // Get image and pipe access qualifier:
  1471. if (ty->isImageType() || ty->isPipeType()) {
  1472. const Decl *PDecl = parm;
  1473. if (auto *TD = dyn_cast<TypedefType>(ty))
  1474. PDecl = TD->getDecl();
  1475. const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
  1476. if (A && A->isWriteOnly())
  1477. accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
  1478. else if (A && A->isReadWrite())
  1479. accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
  1480. else
  1481. accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
  1482. } else
  1483. accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
  1484. // Get argument name.
  1485. argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
  1486. auto getTypeSpelling = [&](QualType Ty) {
  1487. auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
  1488. if (Ty.isCanonical()) {
  1489. StringRef typeNameRef = typeName;
  1490. // Turn "unsigned type" to "utype"
  1491. if (typeNameRef.consume_front("unsigned "))
  1492. return std::string("u") + typeNameRef.str();
  1493. if (typeNameRef.consume_front("signed "))
  1494. return typeNameRef.str();
  1495. }
  1496. return typeName;
  1497. };
  1498. if (ty->isPointerType()) {
  1499. QualType pointeeTy = ty->getPointeeType();
  1500. // Get address qualifier.
  1501. addressQuals.push_back(
  1502. llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
  1503. ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
  1504. // Get argument type name.
  1505. std::string typeName = getTypeSpelling(pointeeTy) + "*";
  1506. std::string baseTypeName =
  1507. getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
  1508. argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
  1509. argBaseTypeNames.push_back(
  1510. llvm::MDString::get(VMContext, baseTypeName));
  1511. // Get argument type qualifiers:
  1512. if (ty.isRestrictQualified())
  1513. typeQuals = "restrict";
  1514. if (pointeeTy.isConstQualified() ||
  1515. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  1516. typeQuals += typeQuals.empty() ? "const" : " const";
  1517. if (pointeeTy.isVolatileQualified())
  1518. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  1519. } else {
  1520. uint32_t AddrSpc = 0;
  1521. bool isPipe = ty->isPipeType();
  1522. if (ty->isImageType() || isPipe)
  1523. AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
  1524. addressQuals.push_back(
  1525. llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
  1526. // Get argument type name.
  1527. ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
  1528. std::string typeName = getTypeSpelling(ty);
  1529. std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
  1530. // Remove access qualifiers on images
  1531. // (as they are inseparable from type in clang implementation,
  1532. // but OpenCL spec provides a special query to get access qualifier
  1533. // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
  1534. if (ty->isImageType()) {
  1535. removeImageAccessQualifier(typeName);
  1536. removeImageAccessQualifier(baseTypeName);
  1537. }
  1538. argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
  1539. argBaseTypeNames.push_back(
  1540. llvm::MDString::get(VMContext, baseTypeName));
  1541. if (isPipe)
  1542. typeQuals = "pipe";
  1543. }
  1544. argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
  1545. }
  1546. Fn->setMetadata("kernel_arg_addr_space",
  1547. llvm::MDNode::get(VMContext, addressQuals));
  1548. Fn->setMetadata("kernel_arg_access_qual",
  1549. llvm::MDNode::get(VMContext, accessQuals));
  1550. Fn->setMetadata("kernel_arg_type",
  1551. llvm::MDNode::get(VMContext, argTypeNames));
  1552. Fn->setMetadata("kernel_arg_base_type",
  1553. llvm::MDNode::get(VMContext, argBaseTypeNames));
  1554. Fn->setMetadata("kernel_arg_type_qual",
  1555. llvm::MDNode::get(VMContext, argTypeQuals));
  1556. if (getCodeGenOpts().EmitOpenCLArgMetadata)
  1557. Fn->setMetadata("kernel_arg_name",
  1558. llvm::MDNode::get(VMContext, argNames));
  1559. }
  1560. /// Determines whether the language options require us to model
  1561. /// unwind exceptions. We treat -fexceptions as mandating this
  1562. /// except under the fragile ObjC ABI with only ObjC exceptions
  1563. /// enabled. This means, for example, that C with -fexceptions
  1564. /// enables this.
  1565. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  1566. // If exceptions are completely disabled, obviously this is false.
  1567. if (!LangOpts.Exceptions) return false;
  1568. // If C++ exceptions are enabled, this is true.
  1569. if (LangOpts.CXXExceptions) return true;
  1570. // If ObjC exceptions are enabled, this depends on the ABI.
  1571. if (LangOpts.ObjCExceptions) {
  1572. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  1573. }
  1574. return true;
  1575. }
  1576. static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
  1577. const CXXMethodDecl *MD) {
  1578. // Check that the type metadata can ever actually be used by a call.
  1579. if (!CGM.getCodeGenOpts().LTOUnit ||
  1580. !CGM.HasHiddenLTOVisibility(MD->getParent()))
  1581. return false;
  1582. // Only functions whose address can be taken with a member function pointer
  1583. // need this sort of type metadata.
  1584. return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
  1585. !isa<CXXDestructorDecl>(MD);
  1586. }
  1587. std::vector<const CXXRecordDecl *>
  1588. CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
  1589. llvm::SetVector<const CXXRecordDecl *> MostBases;
  1590. std::function<void (const CXXRecordDecl *)> CollectMostBases;
  1591. CollectMostBases = [&](const CXXRecordDecl *RD) {
  1592. if (RD->getNumBases() == 0)
  1593. MostBases.insert(RD);
  1594. for (const CXXBaseSpecifier &B : RD->bases())
  1595. CollectMostBases(B.getType()->getAsCXXRecordDecl());
  1596. };
  1597. CollectMostBases(RD);
  1598. return MostBases.takeVector();
  1599. }
  1600. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  1601. llvm::Function *F) {
  1602. llvm::AttrBuilder B(F->getContext());
  1603. if (CodeGenOpts.UnwindTables)
  1604. B.addAttribute(llvm::Attribute::UWTable);
  1605. if (CodeGenOpts.StackClashProtector)
  1606. B.addAttribute("probe-stack", "inline-asm");
  1607. if (!hasUnwindExceptions(LangOpts))
  1608. B.addAttribute(llvm::Attribute::NoUnwind);
  1609. if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
  1610. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  1611. B.addAttribute(llvm::Attribute::StackProtect);
  1612. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  1613. B.addAttribute(llvm::Attribute::StackProtectStrong);
  1614. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  1615. B.addAttribute(llvm::Attribute::StackProtectReq);
  1616. }
  1617. if (!D) {
  1618. // If we don't have a declaration to control inlining, the function isn't
  1619. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  1620. // disabled, mark the function as noinline.
  1621. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1622. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  1623. B.addAttribute(llvm::Attribute::NoInline);
  1624. F->addFnAttrs(B);
  1625. return;
  1626. }
  1627. // Track whether we need to add the optnone LLVM attribute,
  1628. // starting with the default for this optimization level.
  1629. bool ShouldAddOptNone =
  1630. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  1631. // We can't add optnone in the following cases, it won't pass the verifier.
  1632. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  1633. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  1634. // Add optnone, but do so only if the function isn't always_inline.
  1635. if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
  1636. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1637. B.addAttribute(llvm::Attribute::OptimizeNone);
  1638. // OptimizeNone implies noinline; we should not be inlining such functions.
  1639. B.addAttribute(llvm::Attribute::NoInline);
  1640. // We still need to handle naked functions even though optnone subsumes
  1641. // much of their semantics.
  1642. if (D->hasAttr<NakedAttr>())
  1643. B.addAttribute(llvm::Attribute::Naked);
  1644. // OptimizeNone wins over OptimizeForSize and MinSize.
  1645. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1646. F->removeFnAttr(llvm::Attribute::MinSize);
  1647. } else if (D->hasAttr<NakedAttr>()) {
  1648. // Naked implies noinline: we should not be inlining such functions.
  1649. B.addAttribute(llvm::Attribute::Naked);
  1650. B.addAttribute(llvm::Attribute::NoInline);
  1651. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1652. B.addAttribute(llvm::Attribute::NoDuplicate);
  1653. } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1654. // Add noinline if the function isn't always_inline.
  1655. B.addAttribute(llvm::Attribute::NoInline);
  1656. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1657. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1658. // (noinline wins over always_inline, and we can't specify both in IR)
  1659. B.addAttribute(llvm::Attribute::AlwaysInline);
  1660. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1661. // If we're not inlining, then force everything that isn't always_inline to
  1662. // carry an explicit noinline attribute.
  1663. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1664. B.addAttribute(llvm::Attribute::NoInline);
  1665. } else {
  1666. // Otherwise, propagate the inline hint attribute and potentially use its
  1667. // absence to mark things as noinline.
  1668. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1669. // Search function and template pattern redeclarations for inline.
  1670. auto CheckForInline = [](const FunctionDecl *FD) {
  1671. auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
  1672. return Redecl->isInlineSpecified();
  1673. };
  1674. if (any_of(FD->redecls(), CheckRedeclForInline))
  1675. return true;
  1676. const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
  1677. if (!Pattern)
  1678. return false;
  1679. return any_of(Pattern->redecls(), CheckRedeclForInline);
  1680. };
  1681. if (CheckForInline(FD)) {
  1682. B.addAttribute(llvm::Attribute::InlineHint);
  1683. } else if (CodeGenOpts.getInlining() ==
  1684. CodeGenOptions::OnlyHintInlining &&
  1685. !FD->isInlined() &&
  1686. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1687. B.addAttribute(llvm::Attribute::NoInline);
  1688. }
  1689. }
  1690. }
  1691. // Add other optimization related attributes if we are optimizing this
  1692. // function.
  1693. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1694. if (D->hasAttr<ColdAttr>()) {
  1695. if (!ShouldAddOptNone)
  1696. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1697. B.addAttribute(llvm::Attribute::Cold);
  1698. }
  1699. if (D->hasAttr<HotAttr>())
  1700. B.addAttribute(llvm::Attribute::Hot);
  1701. if (D->hasAttr<MinSizeAttr>())
  1702. B.addAttribute(llvm::Attribute::MinSize);
  1703. }
  1704. F->addFnAttrs(B);
  1705. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1706. if (alignment)
  1707. F->setAlignment(llvm::Align(alignment));
  1708. if (!D->hasAttr<AlignedAttr>())
  1709. if (LangOpts.FunctionAlignment)
  1710. F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
  1711. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1712. // reserve a bit for differentiating between virtual and non-virtual member
  1713. // functions. If the current target's C++ ABI requires this and this is a
  1714. // member function, set its alignment accordingly.
  1715. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1716. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1717. F->setAlignment(llvm::Align(2));
  1718. }
  1719. // In the cross-dso CFI mode with canonical jump tables, we want !type
  1720. // attributes on definitions only.
  1721. if (CodeGenOpts.SanitizeCfiCrossDso &&
  1722. CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
  1723. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1724. // Skip available_externally functions. They won't be codegen'ed in the
  1725. // current module anyway.
  1726. if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
  1727. CreateFunctionTypeMetadataForIcall(FD, F);
  1728. }
  1729. }
  1730. // Emit type metadata on member functions for member function pointer checks.
  1731. // These are only ever necessary on definitions; we're guaranteed that the
  1732. // definition will be present in the LTO unit as a result of LTO visibility.
  1733. auto *MD = dyn_cast<CXXMethodDecl>(D);
  1734. if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
  1735. for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
  1736. llvm::Metadata *Id =
  1737. CreateMetadataIdentifierForType(Context.getMemberPointerType(
  1738. MD->getType(), Context.getRecordType(Base).getTypePtr()));
  1739. F->addTypeMetadata(0, Id);
  1740. }
  1741. }
  1742. }
  1743. void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
  1744. llvm::Function *F) {
  1745. if (D->hasAttr<StrictFPAttr>()) {
  1746. llvm::AttrBuilder FuncAttrs(F->getContext());
  1747. FuncAttrs.addAttribute("strictfp");
  1748. F->addFnAttrs(FuncAttrs);
  1749. }
  1750. }
  1751. void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
  1752. const Decl *D = GD.getDecl();
  1753. if (isa_and_nonnull<NamedDecl>(D))
  1754. setGVProperties(GV, GD);
  1755. else
  1756. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1757. if (D && D->hasAttr<UsedAttr>())
  1758. addUsedOrCompilerUsedGlobal(GV);
  1759. if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
  1760. const auto *VD = cast<VarDecl>(D);
  1761. if (VD->getType().isConstQualified() &&
  1762. VD->getStorageDuration() == SD_Static)
  1763. addUsedOrCompilerUsedGlobal(GV);
  1764. }
  1765. }
  1766. bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
  1767. llvm::AttrBuilder &Attrs) {
  1768. // Add target-cpu and target-features attributes to functions. If
  1769. // we have a decl for the function and it has a target attribute then
  1770. // parse that and add it to the feature set.
  1771. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1772. StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
  1773. std::vector<std::string> Features;
  1774. const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
  1775. FD = FD ? FD->getMostRecentDecl() : FD;
  1776. const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
  1777. const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
  1778. const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
  1779. bool AddedAttr = false;
  1780. if (TD || SD || TC) {
  1781. llvm::StringMap<bool> FeatureMap;
  1782. getContext().getFunctionFeatureMap(FeatureMap, GD);
  1783. // Produce the canonical string for this set of features.
  1784. for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
  1785. Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
  1786. // Now add the target-cpu and target-features to the function.
  1787. // While we populated the feature map above, we still need to
  1788. // get and parse the target attribute so we can get the cpu for
  1789. // the function.
  1790. if (TD) {
  1791. ParsedTargetAttr ParsedAttr = TD->parse();
  1792. if (!ParsedAttr.Architecture.empty() &&
  1793. getTarget().isValidCPUName(ParsedAttr.Architecture)) {
  1794. TargetCPU = ParsedAttr.Architecture;
  1795. TuneCPU = ""; // Clear the tune CPU.
  1796. }
  1797. if (!ParsedAttr.Tune.empty() &&
  1798. getTarget().isValidCPUName(ParsedAttr.Tune))
  1799. TuneCPU = ParsedAttr.Tune;
  1800. }
  1801. } else {
  1802. // Otherwise just add the existing target cpu and target features to the
  1803. // function.
  1804. Features = getTarget().getTargetOpts().Features;
  1805. }
  1806. if (!TargetCPU.empty()) {
  1807. Attrs.addAttribute("target-cpu", TargetCPU);
  1808. AddedAttr = true;
  1809. }
  1810. if (!TuneCPU.empty()) {
  1811. Attrs.addAttribute("tune-cpu", TuneCPU);
  1812. AddedAttr = true;
  1813. }
  1814. if (!Features.empty()) {
  1815. llvm::sort(Features);
  1816. Attrs.addAttribute("target-features", llvm::join(Features, ","));
  1817. AddedAttr = true;
  1818. }
  1819. return AddedAttr;
  1820. }
  1821. void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
  1822. llvm::GlobalObject *GO) {
  1823. const Decl *D = GD.getDecl();
  1824. SetCommonAttributes(GD, GO);
  1825. if (D) {
  1826. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1827. if (D->hasAttr<RetainAttr>())
  1828. addUsedGlobal(GV);
  1829. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1830. GV->addAttribute("bss-section", SA->getName());
  1831. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1832. GV->addAttribute("data-section", SA->getName());
  1833. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1834. GV->addAttribute("rodata-section", SA->getName());
  1835. if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
  1836. GV->addAttribute("relro-section", SA->getName());
  1837. }
  1838. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1839. if (D->hasAttr<RetainAttr>())
  1840. addUsedGlobal(F);
  1841. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1842. if (!D->getAttr<SectionAttr>())
  1843. F->addFnAttr("implicit-section-name", SA->getName());
  1844. llvm::AttrBuilder Attrs(F->getContext());
  1845. if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
  1846. // We know that GetCPUAndFeaturesAttributes will always have the
  1847. // newest set, since it has the newest possible FunctionDecl, so the
  1848. // new ones should replace the old.
  1849. llvm::AttributeMask RemoveAttrs;
  1850. RemoveAttrs.addAttribute("target-cpu");
  1851. RemoveAttrs.addAttribute("target-features");
  1852. RemoveAttrs.addAttribute("tune-cpu");
  1853. F->removeFnAttrs(RemoveAttrs);
  1854. F->addFnAttrs(Attrs);
  1855. }
  1856. }
  1857. if (const auto *CSA = D->getAttr<CodeSegAttr>())
  1858. GO->setSection(CSA->getName());
  1859. else if (const auto *SA = D->getAttr<SectionAttr>())
  1860. GO->setSection(SA->getName());
  1861. }
  1862. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1863. }
  1864. void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
  1865. llvm::Function *F,
  1866. const CGFunctionInfo &FI) {
  1867. const Decl *D = GD.getDecl();
  1868. SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
  1869. SetLLVMFunctionAttributesForDefinition(D, F);
  1870. F->setLinkage(llvm::Function::InternalLinkage);
  1871. setNonAliasAttributes(GD, F);
  1872. }
  1873. static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
  1874. // Set linkage and visibility in case we never see a definition.
  1875. LinkageInfo LV = ND->getLinkageAndVisibility();
  1876. // Don't set internal linkage on declarations.
  1877. // "extern_weak" is overloaded in LLVM; we probably should have
  1878. // separate linkage types for this.
  1879. if (isExternallyVisible(LV.getLinkage()) &&
  1880. (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
  1881. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1882. }
  1883. void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
  1884. llvm::Function *F) {
  1885. // Only if we are checking indirect calls.
  1886. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1887. return;
  1888. // Non-static class methods are handled via vtable or member function pointer
  1889. // checks elsewhere.
  1890. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1891. return;
  1892. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1893. F->addTypeMetadata(0, MD);
  1894. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1895. // Emit a hash-based bit set entry for cross-DSO calls.
  1896. if (CodeGenOpts.SanitizeCfiCrossDso)
  1897. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1898. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1899. }
  1900. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1901. bool IsIncompleteFunction,
  1902. bool IsThunk) {
  1903. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1904. // If this is an intrinsic function, set the function's attributes
  1905. // to the intrinsic's attributes.
  1906. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1907. return;
  1908. }
  1909. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1910. if (!IsIncompleteFunction)
  1911. SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
  1912. IsThunk);
  1913. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1914. // where substantial code, including the libstdc++ dylib, was compiled with
  1915. // GCC and does not actually return "this".
  1916. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1917. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1918. assert(!F->arg_empty() &&
  1919. F->arg_begin()->getType()
  1920. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1921. "unexpected this return");
  1922. F->addParamAttr(0, llvm::Attribute::Returned);
  1923. }
  1924. // Only a few attributes are set on declarations; these may later be
  1925. // overridden by a definition.
  1926. setLinkageForGV(F, FD);
  1927. setGVProperties(F, FD);
  1928. // Setup target-specific attributes.
  1929. if (!IsIncompleteFunction && F->isDeclaration())
  1930. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1931. if (const auto *CSA = FD->getAttr<CodeSegAttr>())
  1932. F->setSection(CSA->getName());
  1933. else if (const auto *SA = FD->getAttr<SectionAttr>())
  1934. F->setSection(SA->getName());
  1935. if (const auto *EA = FD->getAttr<ErrorAttr>()) {
  1936. if (EA->isError())
  1937. F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
  1938. else if (EA->isWarning())
  1939. F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
  1940. }
  1941. // If we plan on emitting this inline builtin, we can't treat it as a builtin.
  1942. if (FD->isInlineBuiltinDeclaration()) {
  1943. const FunctionDecl *FDBody;
  1944. bool HasBody = FD->hasBody(FDBody);
  1945. (void)HasBody;
  1946. assert(HasBody && "Inline builtin declarations should always have an "
  1947. "available body!");
  1948. if (shouldEmitFunction(FDBody))
  1949. F->addFnAttr(llvm::Attribute::NoBuiltin);
  1950. }
  1951. if (FD->isReplaceableGlobalAllocationFunction()) {
  1952. // A replaceable global allocation function does not act like a builtin by
  1953. // default, only if it is invoked by a new-expression or delete-expression.
  1954. F->addFnAttr(llvm::Attribute::NoBuiltin);
  1955. }
  1956. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1957. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1958. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1959. if (MD->isVirtual())
  1960. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1961. // Don't emit entries for function declarations in the cross-DSO mode. This
  1962. // is handled with better precision by the receiving DSO. But if jump tables
  1963. // are non-canonical then we need type metadata in order to produce the local
  1964. // jump table.
  1965. if (!CodeGenOpts.SanitizeCfiCrossDso ||
  1966. !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
  1967. CreateFunctionTypeMetadataForIcall(FD, F);
  1968. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1969. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1970. if (const auto *CB = FD->getAttr<CallbackAttr>()) {
  1971. // Annotate the callback behavior as metadata:
  1972. // - The callback callee (as argument number).
  1973. // - The callback payloads (as argument numbers).
  1974. llvm::LLVMContext &Ctx = F->getContext();
  1975. llvm::MDBuilder MDB(Ctx);
  1976. // The payload indices are all but the first one in the encoding. The first
  1977. // identifies the callback callee.
  1978. int CalleeIdx = *CB->encoding_begin();
  1979. ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
  1980. F->addMetadata(llvm::LLVMContext::MD_callback,
  1981. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  1982. CalleeIdx, PayloadIndices,
  1983. /* VarArgsArePassed */ false)}));
  1984. }
  1985. }
  1986. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1987. assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
  1988. "Only globals with definition can force usage.");
  1989. LLVMUsed.emplace_back(GV);
  1990. }
  1991. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1992. assert(!GV->isDeclaration() &&
  1993. "Only globals with definition can force usage.");
  1994. LLVMCompilerUsed.emplace_back(GV);
  1995. }
  1996. void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1997. assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
  1998. "Only globals with definition can force usage.");
  1999. if (getTriple().isOSBinFormatELF())
  2000. LLVMCompilerUsed.emplace_back(GV);
  2001. else
  2002. LLVMUsed.emplace_back(GV);
  2003. }
  2004. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  2005. std::vector<llvm::WeakTrackingVH> &List) {
  2006. // Don't create llvm.used if there is no need.
  2007. if (List.empty())
  2008. return;
  2009. // Convert List to what ConstantArray needs.
  2010. SmallVector<llvm::Constant*, 8> UsedArray;
  2011. UsedArray.resize(List.size());
  2012. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  2013. UsedArray[i] =
  2014. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  2015. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  2016. }
  2017. if (UsedArray.empty())
  2018. return;
  2019. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  2020. auto *GV = new llvm::GlobalVariable(
  2021. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  2022. llvm::ConstantArray::get(ATy, UsedArray), Name);
  2023. GV->setSection("llvm.metadata");
  2024. }
  2025. void CodeGenModule::emitLLVMUsed() {
  2026. emitUsed(*this, "llvm.used", LLVMUsed);
  2027. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  2028. }
  2029. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  2030. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  2031. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  2032. }
  2033. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  2034. llvm::SmallString<32> Opt;
  2035. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  2036. if (Opt.empty())
  2037. return;
  2038. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  2039. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  2040. }
  2041. void CodeGenModule::AddDependentLib(StringRef Lib) {
  2042. auto &C = getLLVMContext();
  2043. if (getTarget().getTriple().isOSBinFormatELF()) {
  2044. ELFDependentLibraries.push_back(
  2045. llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
  2046. return;
  2047. }
  2048. llvm::SmallString<24> Opt;
  2049. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  2050. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  2051. LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
  2052. }
  2053. /// Add link options implied by the given module, including modules
  2054. /// it depends on, using a postorder walk.
  2055. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  2056. SmallVectorImpl<llvm::MDNode *> &Metadata,
  2057. llvm::SmallPtrSet<Module *, 16> &Visited) {
  2058. // Import this module's parent.
  2059. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  2060. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  2061. }
  2062. // Import this module's dependencies.
  2063. for (Module *Import : llvm::reverse(Mod->Imports)) {
  2064. if (Visited.insert(Import).second)
  2065. addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
  2066. }
  2067. // Add linker options to link against the libraries/frameworks
  2068. // described by this module.
  2069. llvm::LLVMContext &Context = CGM.getLLVMContext();
  2070. bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
  2071. // For modules that use export_as for linking, use that module
  2072. // name instead.
  2073. if (Mod->UseExportAsModuleLinkName)
  2074. return;
  2075. for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
  2076. // Link against a framework. Frameworks are currently Darwin only, so we
  2077. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  2078. if (LL.IsFramework) {
  2079. llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
  2080. llvm::MDString::get(Context, LL.Library)};
  2081. Metadata.push_back(llvm::MDNode::get(Context, Args));
  2082. continue;
  2083. }
  2084. // Link against a library.
  2085. if (IsELF) {
  2086. llvm::Metadata *Args[2] = {
  2087. llvm::MDString::get(Context, "lib"),
  2088. llvm::MDString::get(Context, LL.Library),
  2089. };
  2090. Metadata.push_back(llvm::MDNode::get(Context, Args));
  2091. } else {
  2092. llvm::SmallString<24> Opt;
  2093. CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
  2094. auto *OptString = llvm::MDString::get(Context, Opt);
  2095. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  2096. }
  2097. }
  2098. }
  2099. void CodeGenModule::EmitModuleLinkOptions() {
  2100. // Collect the set of all of the modules we want to visit to emit link
  2101. // options, which is essentially the imported modules and all of their
  2102. // non-explicit child modules.
  2103. llvm::SetVector<clang::Module *> LinkModules;
  2104. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  2105. SmallVector<clang::Module *, 16> Stack;
  2106. // Seed the stack with imported modules.
  2107. for (Module *M : ImportedModules) {
  2108. // Do not add any link flags when an implementation TU of a module imports
  2109. // a header of that same module.
  2110. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  2111. !getLangOpts().isCompilingModule())
  2112. continue;
  2113. if (Visited.insert(M).second)
  2114. Stack.push_back(M);
  2115. }
  2116. // Find all of the modules to import, making a little effort to prune
  2117. // non-leaf modules.
  2118. while (!Stack.empty()) {
  2119. clang::Module *Mod = Stack.pop_back_val();
  2120. bool AnyChildren = false;
  2121. // Visit the submodules of this module.
  2122. for (const auto &SM : Mod->submodules()) {
  2123. // Skip explicit children; they need to be explicitly imported to be
  2124. // linked against.
  2125. if (SM->IsExplicit)
  2126. continue;
  2127. if (Visited.insert(SM).second) {
  2128. Stack.push_back(SM);
  2129. AnyChildren = true;
  2130. }
  2131. }
  2132. // We didn't find any children, so add this module to the list of
  2133. // modules to link against.
  2134. if (!AnyChildren) {
  2135. LinkModules.insert(Mod);
  2136. }
  2137. }
  2138. // Add link options for all of the imported modules in reverse topological
  2139. // order. We don't do anything to try to order import link flags with respect
  2140. // to linker options inserted by things like #pragma comment().
  2141. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  2142. Visited.clear();
  2143. for (Module *M : LinkModules)
  2144. if (Visited.insert(M).second)
  2145. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  2146. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  2147. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  2148. // Add the linker options metadata flag.
  2149. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  2150. for (auto *MD : LinkerOptionsMetadata)
  2151. NMD->addOperand(MD);
  2152. }
  2153. void CodeGenModule::EmitDeferred() {
  2154. // Emit deferred declare target declarations.
  2155. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
  2156. getOpenMPRuntime().emitDeferredTargetDecls();
  2157. // Emit code for any potentially referenced deferred decls. Since a
  2158. // previously unused static decl may become used during the generation of code
  2159. // for a static function, iterate until no changes are made.
  2160. if (!DeferredVTables.empty()) {
  2161. EmitDeferredVTables();
  2162. // Emitting a vtable doesn't directly cause more vtables to
  2163. // become deferred, although it can cause functions to be
  2164. // emitted that then need those vtables.
  2165. assert(DeferredVTables.empty());
  2166. }
  2167. // Emit CUDA/HIP static device variables referenced by host code only.
  2168. // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
  2169. // needed for further handling.
  2170. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
  2171. for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
  2172. DeferredDeclsToEmit.push_back(V);
  2173. // Stop if we're out of both deferred vtables and deferred declarations.
  2174. if (DeferredDeclsToEmit.empty())
  2175. return;
  2176. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  2177. // work, it will not interfere with this.
  2178. std::vector<GlobalDecl> CurDeclsToEmit;
  2179. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  2180. for (GlobalDecl &D : CurDeclsToEmit) {
  2181. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  2182. // to get GlobalValue with exactly the type we need, not something that
  2183. // might had been created for another decl with the same mangled name but
  2184. // different type.
  2185. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  2186. GetAddrOfGlobal(D, ForDefinition));
  2187. // In case of different address spaces, we may still get a cast, even with
  2188. // IsForDefinition equal to true. Query mangled names table to get
  2189. // GlobalValue.
  2190. if (!GV)
  2191. GV = GetGlobalValue(getMangledName(D));
  2192. // Make sure GetGlobalValue returned non-null.
  2193. assert(GV);
  2194. // Check to see if we've already emitted this. This is necessary
  2195. // for a couple of reasons: first, decls can end up in the
  2196. // deferred-decls queue multiple times, and second, decls can end
  2197. // up with definitions in unusual ways (e.g. by an extern inline
  2198. // function acquiring a strong function redefinition). Just
  2199. // ignore these cases.
  2200. if (!GV->isDeclaration())
  2201. continue;
  2202. // If this is OpenMP, check if it is legal to emit this global normally.
  2203. if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
  2204. continue;
  2205. // Otherwise, emit the definition and move on to the next one.
  2206. EmitGlobalDefinition(D, GV);
  2207. // If we found out that we need to emit more decls, do that recursively.
  2208. // This has the advantage that the decls are emitted in a DFS and related
  2209. // ones are close together, which is convenient for testing.
  2210. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  2211. EmitDeferred();
  2212. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  2213. }
  2214. }
  2215. }
  2216. void CodeGenModule::EmitVTablesOpportunistically() {
  2217. // Try to emit external vtables as available_externally if they have emitted
  2218. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  2219. // is not allowed to create new references to things that need to be emitted
  2220. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  2221. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  2222. && "Only emit opportunistic vtables with optimizations");
  2223. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  2224. assert(getVTables().isVTableExternal(RD) &&
  2225. "This queue should only contain external vtables");
  2226. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  2227. VTables.GenerateClassData(RD);
  2228. }
  2229. OpportunisticVTables.clear();
  2230. }
  2231. void CodeGenModule::EmitGlobalAnnotations() {
  2232. if (Annotations.empty())
  2233. return;
  2234. // Create a new global variable for the ConstantStruct in the Module.
  2235. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  2236. Annotations[0]->getType(), Annotations.size()), Annotations);
  2237. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  2238. llvm::GlobalValue::AppendingLinkage,
  2239. Array, "llvm.global.annotations");
  2240. gv->setSection(AnnotationSection);
  2241. }
  2242. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  2243. llvm::Constant *&AStr = AnnotationStrings[Str];
  2244. if (AStr)
  2245. return AStr;
  2246. // Not found yet, create a new global.
  2247. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  2248. auto *gv =
  2249. new llvm::GlobalVariable(getModule(), s->getType(), true,
  2250. llvm::GlobalValue::PrivateLinkage, s, ".str");
  2251. gv->setSection(AnnotationSection);
  2252. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2253. AStr = gv;
  2254. return gv;
  2255. }
  2256. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  2257. SourceManager &SM = getContext().getSourceManager();
  2258. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  2259. if (PLoc.isValid())
  2260. return EmitAnnotationString(PLoc.getFilename());
  2261. return EmitAnnotationString(SM.getBufferName(Loc));
  2262. }
  2263. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  2264. SourceManager &SM = getContext().getSourceManager();
  2265. PresumedLoc PLoc = SM.getPresumedLoc(L);
  2266. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  2267. SM.getExpansionLineNumber(L);
  2268. return llvm::ConstantInt::get(Int32Ty, LineNo);
  2269. }
  2270. llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
  2271. ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
  2272. if (Exprs.empty())
  2273. return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy);
  2274. llvm::FoldingSetNodeID ID;
  2275. for (Expr *E : Exprs) {
  2276. ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
  2277. }
  2278. llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
  2279. if (Lookup)
  2280. return Lookup;
  2281. llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
  2282. LLVMArgs.reserve(Exprs.size());
  2283. ConstantEmitter ConstEmiter(*this);
  2284. llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
  2285. const auto *CE = cast<clang::ConstantExpr>(E);
  2286. return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
  2287. CE->getType());
  2288. });
  2289. auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
  2290. auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
  2291. llvm::GlobalValue::PrivateLinkage, Struct,
  2292. ".args");
  2293. GV->setSection(AnnotationSection);
  2294. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2295. auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
  2296. Lookup = Bitcasted;
  2297. return Bitcasted;
  2298. }
  2299. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  2300. const AnnotateAttr *AA,
  2301. SourceLocation L) {
  2302. // Get the globals for file name, annotation, and the line number.
  2303. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  2304. *UnitGV = EmitAnnotationUnit(L),
  2305. *LineNoCst = EmitAnnotationLineNo(L),
  2306. *Args = EmitAnnotationArgs(AA);
  2307. llvm::Constant *GVInGlobalsAS = GV;
  2308. if (GV->getAddressSpace() !=
  2309. getDataLayout().getDefaultGlobalsAddressSpace()) {
  2310. GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
  2311. GV, GV->getValueType()->getPointerTo(
  2312. getDataLayout().getDefaultGlobalsAddressSpace()));
  2313. }
  2314. // Create the ConstantStruct for the global annotation.
  2315. llvm::Constant *Fields[] = {
  2316. llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
  2317. llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy),
  2318. llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy),
  2319. LineNoCst,
  2320. Args,
  2321. };
  2322. return llvm::ConstantStruct::getAnon(Fields);
  2323. }
  2324. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  2325. llvm::GlobalValue *GV) {
  2326. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  2327. // Get the struct elements for these annotations.
  2328. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  2329. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  2330. }
  2331. bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
  2332. SourceLocation Loc) const {
  2333. const auto &NoSanitizeL = getContext().getNoSanitizeList();
  2334. // NoSanitize by function name.
  2335. if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
  2336. return true;
  2337. // NoSanitize by location.
  2338. if (Loc.isValid())
  2339. return NoSanitizeL.containsLocation(Kind, Loc);
  2340. // If location is unknown, this may be a compiler-generated function. Assume
  2341. // it's located in the main file.
  2342. auto &SM = Context.getSourceManager();
  2343. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  2344. return NoSanitizeL.containsFile(Kind, MainFile->getName());
  2345. }
  2346. return false;
  2347. }
  2348. bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
  2349. SourceLocation Loc, QualType Ty,
  2350. StringRef Category) const {
  2351. // For now globals can be ignored only in ASan and KASan.
  2352. const SanitizerMask EnabledAsanMask =
  2353. LangOpts.Sanitize.Mask &
  2354. (SanitizerKind::Address | SanitizerKind::KernelAddress |
  2355. SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
  2356. SanitizerKind::MemTag);
  2357. if (!EnabledAsanMask)
  2358. return false;
  2359. const auto &NoSanitizeL = getContext().getNoSanitizeList();
  2360. if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
  2361. return true;
  2362. if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
  2363. return true;
  2364. // Check global type.
  2365. if (!Ty.isNull()) {
  2366. // Drill down the array types: if global variable of a fixed type is
  2367. // not sanitized, we also don't instrument arrays of them.
  2368. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  2369. Ty = AT->getElementType();
  2370. Ty = Ty.getCanonicalType().getUnqualifiedType();
  2371. // Only record types (classes, structs etc.) are ignored.
  2372. if (Ty->isRecordType()) {
  2373. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  2374. if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
  2375. return true;
  2376. }
  2377. }
  2378. return false;
  2379. }
  2380. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  2381. StringRef Category) const {
  2382. const auto &XRayFilter = getContext().getXRayFilter();
  2383. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  2384. auto Attr = ImbueAttr::NONE;
  2385. if (Loc.isValid())
  2386. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  2387. if (Attr == ImbueAttr::NONE)
  2388. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  2389. switch (Attr) {
  2390. case ImbueAttr::NONE:
  2391. return false;
  2392. case ImbueAttr::ALWAYS:
  2393. Fn->addFnAttr("function-instrument", "xray-always");
  2394. break;
  2395. case ImbueAttr::ALWAYS_ARG1:
  2396. Fn->addFnAttr("function-instrument", "xray-always");
  2397. Fn->addFnAttr("xray-log-args", "1");
  2398. break;
  2399. case ImbueAttr::NEVER:
  2400. Fn->addFnAttr("function-instrument", "xray-never");
  2401. break;
  2402. }
  2403. return true;
  2404. }
  2405. bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
  2406. SourceLocation Loc) const {
  2407. const auto &ProfileList = getContext().getProfileList();
  2408. // If the profile list is empty, then instrument everything.
  2409. if (ProfileList.isEmpty())
  2410. return false;
  2411. CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
  2412. // First, check the function name.
  2413. Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
  2414. if (V.hasValue())
  2415. return *V;
  2416. // Next, check the source location.
  2417. if (Loc.isValid()) {
  2418. Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
  2419. if (V.hasValue())
  2420. return *V;
  2421. }
  2422. // If location is unknown, this may be a compiler-generated function. Assume
  2423. // it's located in the main file.
  2424. auto &SM = Context.getSourceManager();
  2425. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  2426. Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
  2427. if (V.hasValue())
  2428. return *V;
  2429. }
  2430. return ProfileList.getDefault();
  2431. }
  2432. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  2433. // Never defer when EmitAllDecls is specified.
  2434. if (LangOpts.EmitAllDecls)
  2435. return true;
  2436. if (CodeGenOpts.KeepStaticConsts) {
  2437. const auto *VD = dyn_cast<VarDecl>(Global);
  2438. if (VD && VD->getType().isConstQualified() &&
  2439. VD->getStorageDuration() == SD_Static)
  2440. return true;
  2441. }
  2442. return getContext().DeclMustBeEmitted(Global);
  2443. }
  2444. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  2445. // In OpenMP 5.0 variables and function may be marked as
  2446. // device_type(host/nohost) and we should not emit them eagerly unless we sure
  2447. // that they must be emitted on the host/device. To be sure we need to have
  2448. // seen a declare target with an explicit mentioning of the function, we know
  2449. // we have if the level of the declare target attribute is -1. Note that we
  2450. // check somewhere else if we should emit this at all.
  2451. if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
  2452. llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
  2453. OMPDeclareTargetDeclAttr::getActiveAttr(Global);
  2454. if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
  2455. return false;
  2456. }
  2457. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  2458. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  2459. // Implicit template instantiations may change linkage if they are later
  2460. // explicitly instantiated, so they should not be emitted eagerly.
  2461. return false;
  2462. }
  2463. if (const auto *VD = dyn_cast<VarDecl>(Global))
  2464. if (Context.getInlineVariableDefinitionKind(VD) ==
  2465. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  2466. // A definition of an inline constexpr static data member may change
  2467. // linkage later if it's redeclared outside the class.
  2468. return false;
  2469. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  2470. // codegen for global variables, because they may be marked as threadprivate.
  2471. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  2472. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
  2473. !isTypeConstant(Global->getType(), false) &&
  2474. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
  2475. return false;
  2476. return true;
  2477. }
  2478. ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
  2479. StringRef Name = getMangledName(GD);
  2480. // The UUID descriptor should be pointer aligned.
  2481. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  2482. // Look for an existing global.
  2483. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  2484. return ConstantAddress(GV, GV->getValueType(), Alignment);
  2485. ConstantEmitter Emitter(*this);
  2486. llvm::Constant *Init;
  2487. APValue &V = GD->getAsAPValue();
  2488. if (!V.isAbsent()) {
  2489. // If possible, emit the APValue version of the initializer. In particular,
  2490. // this gets the type of the constant right.
  2491. Init = Emitter.emitForInitializer(
  2492. GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
  2493. } else {
  2494. // As a fallback, directly construct the constant.
  2495. // FIXME: This may get padding wrong under esoteric struct layout rules.
  2496. // MSVC appears to create a complete type 'struct __s_GUID' that it
  2497. // presumably uses to represent these constants.
  2498. MSGuidDecl::Parts Parts = GD->getParts();
  2499. llvm::Constant *Fields[4] = {
  2500. llvm::ConstantInt::get(Int32Ty, Parts.Part1),
  2501. llvm::ConstantInt::get(Int16Ty, Parts.Part2),
  2502. llvm::ConstantInt::get(Int16Ty, Parts.Part3),
  2503. llvm::ConstantDataArray::getRaw(
  2504. StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
  2505. Int8Ty)};
  2506. Init = llvm::ConstantStruct::getAnon(Fields);
  2507. }
  2508. auto *GV = new llvm::GlobalVariable(
  2509. getModule(), Init->getType(),
  2510. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  2511. if (supportsCOMDAT())
  2512. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2513. setDSOLocal(GV);
  2514. if (!V.isAbsent()) {
  2515. Emitter.finalize(GV);
  2516. return ConstantAddress(GV, GV->getValueType(), Alignment);
  2517. }
  2518. llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
  2519. llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
  2520. GV, Ty->getPointerTo(GV->getAddressSpace()));
  2521. return ConstantAddress(Addr, Ty, Alignment);
  2522. }
  2523. ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
  2524. const TemplateParamObjectDecl *TPO) {
  2525. StringRef Name = getMangledName(TPO);
  2526. CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
  2527. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  2528. return ConstantAddress(GV, GV->getValueType(), Alignment);
  2529. ConstantEmitter Emitter(*this);
  2530. llvm::Constant *Init = Emitter.emitForInitializer(
  2531. TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
  2532. if (!Init) {
  2533. ErrorUnsupported(TPO, "template parameter object");
  2534. return ConstantAddress::invalid();
  2535. }
  2536. auto *GV = new llvm::GlobalVariable(
  2537. getModule(), Init->getType(),
  2538. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  2539. if (supportsCOMDAT())
  2540. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2541. Emitter.finalize(GV);
  2542. return ConstantAddress(GV, GV->getValueType(), Alignment);
  2543. }
  2544. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  2545. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  2546. assert(AA && "No alias?");
  2547. CharUnits Alignment = getContext().getDeclAlign(VD);
  2548. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  2549. // See if there is already something with the target's name in the module.
  2550. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  2551. if (Entry) {
  2552. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  2553. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  2554. return ConstantAddress(Ptr, DeclTy, Alignment);
  2555. }
  2556. llvm::Constant *Aliasee;
  2557. if (isa<llvm::FunctionType>(DeclTy))
  2558. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  2559. GlobalDecl(cast<FunctionDecl>(VD)),
  2560. /*ForVTable=*/false);
  2561. else
  2562. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
  2563. nullptr);
  2564. auto *F = cast<llvm::GlobalValue>(Aliasee);
  2565. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  2566. WeakRefReferences.insert(F);
  2567. return ConstantAddress(Aliasee, DeclTy, Alignment);
  2568. }
  2569. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  2570. const auto *Global = cast<ValueDecl>(GD.getDecl());
  2571. // Weak references don't produce any output by themselves.
  2572. if (Global->hasAttr<WeakRefAttr>())
  2573. return;
  2574. // If this is an alias definition (which otherwise looks like a declaration)
  2575. // emit it now.
  2576. if (Global->hasAttr<AliasAttr>())
  2577. return EmitAliasDefinition(GD);
  2578. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  2579. if (Global->hasAttr<IFuncAttr>())
  2580. return emitIFuncDefinition(GD);
  2581. // If this is a cpu_dispatch multiversion function, emit the resolver.
  2582. if (Global->hasAttr<CPUDispatchAttr>())
  2583. return emitCPUDispatchDefinition(GD);
  2584. // If this is CUDA, be selective about which declarations we emit.
  2585. if (LangOpts.CUDA) {
  2586. if (LangOpts.CUDAIsDevice) {
  2587. if (!Global->hasAttr<CUDADeviceAttr>() &&
  2588. !Global->hasAttr<CUDAGlobalAttr>() &&
  2589. !Global->hasAttr<CUDAConstantAttr>() &&
  2590. !Global->hasAttr<CUDASharedAttr>() &&
  2591. !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
  2592. !Global->getType()->isCUDADeviceBuiltinTextureType())
  2593. return;
  2594. } else {
  2595. // We need to emit host-side 'shadows' for all global
  2596. // device-side variables because the CUDA runtime needs their
  2597. // size and host-side address in order to provide access to
  2598. // their device-side incarnations.
  2599. // So device-only functions are the only things we skip.
  2600. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  2601. Global->hasAttr<CUDADeviceAttr>())
  2602. return;
  2603. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  2604. "Expected Variable or Function");
  2605. }
  2606. }
  2607. if (LangOpts.OpenMP) {
  2608. // If this is OpenMP, check if it is legal to emit this global normally.
  2609. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  2610. return;
  2611. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  2612. if (MustBeEmitted(Global))
  2613. EmitOMPDeclareReduction(DRD);
  2614. return;
  2615. } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
  2616. if (MustBeEmitted(Global))
  2617. EmitOMPDeclareMapper(DMD);
  2618. return;
  2619. }
  2620. }
  2621. // Ignore declarations, they will be emitted on their first use.
  2622. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  2623. // Forward declarations are emitted lazily on first use.
  2624. if (!FD->doesThisDeclarationHaveABody()) {
  2625. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  2626. return;
  2627. StringRef MangledName = getMangledName(GD);
  2628. // Compute the function info and LLVM type.
  2629. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2630. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  2631. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  2632. /*DontDefer=*/false);
  2633. return;
  2634. }
  2635. } else {
  2636. const auto *VD = cast<VarDecl>(Global);
  2637. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  2638. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  2639. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  2640. if (LangOpts.OpenMP) {
  2641. // Emit declaration of the must-be-emitted declare target variable.
  2642. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2643. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  2644. bool UnifiedMemoryEnabled =
  2645. getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
  2646. if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2647. !UnifiedMemoryEnabled) {
  2648. (void)GetAddrOfGlobalVar(VD);
  2649. } else {
  2650. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  2651. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2652. UnifiedMemoryEnabled)) &&
  2653. "Link clause or to clause with unified memory expected.");
  2654. (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  2655. }
  2656. return;
  2657. }
  2658. }
  2659. // If this declaration may have caused an inline variable definition to
  2660. // change linkage, make sure that it's emitted.
  2661. if (Context.getInlineVariableDefinitionKind(VD) ==
  2662. ASTContext::InlineVariableDefinitionKind::Strong)
  2663. GetAddrOfGlobalVar(VD);
  2664. return;
  2665. }
  2666. }
  2667. // Defer code generation to first use when possible, e.g. if this is an inline
  2668. // function. If the global must always be emitted, do it eagerly if possible
  2669. // to benefit from cache locality.
  2670. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  2671. // Emit the definition if it can't be deferred.
  2672. EmitGlobalDefinition(GD);
  2673. return;
  2674. }
  2675. // If we're deferring emission of a C++ variable with an
  2676. // initializer, remember the order in which it appeared in the file.
  2677. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  2678. cast<VarDecl>(Global)->hasInit()) {
  2679. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  2680. CXXGlobalInits.push_back(nullptr);
  2681. }
  2682. StringRef MangledName = getMangledName(GD);
  2683. if (GetGlobalValue(MangledName) != nullptr) {
  2684. // The value has already been used and should therefore be emitted.
  2685. addDeferredDeclToEmit(GD);
  2686. } else if (MustBeEmitted(Global)) {
  2687. // The value must be emitted, but cannot be emitted eagerly.
  2688. assert(!MayBeEmittedEagerly(Global));
  2689. addDeferredDeclToEmit(GD);
  2690. } else {
  2691. // Otherwise, remember that we saw a deferred decl with this name. The
  2692. // first use of the mangled name will cause it to move into
  2693. // DeferredDeclsToEmit.
  2694. DeferredDecls[MangledName] = GD;
  2695. }
  2696. }
  2697. // Check if T is a class type with a destructor that's not dllimport.
  2698. static bool HasNonDllImportDtor(QualType T) {
  2699. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  2700. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2701. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  2702. return true;
  2703. return false;
  2704. }
  2705. namespace {
  2706. struct FunctionIsDirectlyRecursive
  2707. : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
  2708. const StringRef Name;
  2709. const Builtin::Context &BI;
  2710. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
  2711. : Name(N), BI(C) {}
  2712. bool VisitCallExpr(const CallExpr *E) {
  2713. const FunctionDecl *FD = E->getDirectCallee();
  2714. if (!FD)
  2715. return false;
  2716. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2717. if (Attr && Name == Attr->getLabel())
  2718. return true;
  2719. unsigned BuiltinID = FD->getBuiltinID();
  2720. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  2721. return false;
  2722. StringRef BuiltinName = BI.getName(BuiltinID);
  2723. if (BuiltinName.startswith("__builtin_") &&
  2724. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  2725. return true;
  2726. }
  2727. return false;
  2728. }
  2729. bool VisitStmt(const Stmt *S) {
  2730. for (const Stmt *Child : S->children())
  2731. if (Child && this->Visit(Child))
  2732. return true;
  2733. return false;
  2734. }
  2735. };
  2736. // Make sure we're not referencing non-imported vars or functions.
  2737. struct DLLImportFunctionVisitor
  2738. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  2739. bool SafeToInline = true;
  2740. bool shouldVisitImplicitCode() const { return true; }
  2741. bool VisitVarDecl(VarDecl *VD) {
  2742. if (VD->getTLSKind()) {
  2743. // A thread-local variable cannot be imported.
  2744. SafeToInline = false;
  2745. return SafeToInline;
  2746. }
  2747. // A variable definition might imply a destructor call.
  2748. if (VD->isThisDeclarationADefinition())
  2749. SafeToInline = !HasNonDllImportDtor(VD->getType());
  2750. return SafeToInline;
  2751. }
  2752. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  2753. if (const auto *D = E->getTemporary()->getDestructor())
  2754. SafeToInline = D->hasAttr<DLLImportAttr>();
  2755. return SafeToInline;
  2756. }
  2757. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2758. ValueDecl *VD = E->getDecl();
  2759. if (isa<FunctionDecl>(VD))
  2760. SafeToInline = VD->hasAttr<DLLImportAttr>();
  2761. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  2762. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  2763. return SafeToInline;
  2764. }
  2765. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  2766. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  2767. return SafeToInline;
  2768. }
  2769. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2770. CXXMethodDecl *M = E->getMethodDecl();
  2771. if (!M) {
  2772. // Call through a pointer to member function. This is safe to inline.
  2773. SafeToInline = true;
  2774. } else {
  2775. SafeToInline = M->hasAttr<DLLImportAttr>();
  2776. }
  2777. return SafeToInline;
  2778. }
  2779. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  2780. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  2781. return SafeToInline;
  2782. }
  2783. bool VisitCXXNewExpr(CXXNewExpr *E) {
  2784. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  2785. return SafeToInline;
  2786. }
  2787. };
  2788. }
  2789. // isTriviallyRecursive - Check if this function calls another
  2790. // decl that, because of the asm attribute or the other decl being a builtin,
  2791. // ends up pointing to itself.
  2792. bool
  2793. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  2794. StringRef Name;
  2795. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  2796. // asm labels are a special kind of mangling we have to support.
  2797. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2798. if (!Attr)
  2799. return false;
  2800. Name = Attr->getLabel();
  2801. } else {
  2802. Name = FD->getName();
  2803. }
  2804. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  2805. const Stmt *Body = FD->getBody();
  2806. return Body ? Walker.Visit(Body) : false;
  2807. }
  2808. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  2809. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  2810. return true;
  2811. const auto *F = cast<FunctionDecl>(GD.getDecl());
  2812. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  2813. return false;
  2814. if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
  2815. // Check whether it would be safe to inline this dllimport function.
  2816. DLLImportFunctionVisitor Visitor;
  2817. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  2818. if (!Visitor.SafeToInline)
  2819. return false;
  2820. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  2821. // Implicit destructor invocations aren't captured in the AST, so the
  2822. // check above can't see them. Check for them manually here.
  2823. for (const Decl *Member : Dtor->getParent()->decls())
  2824. if (isa<FieldDecl>(Member))
  2825. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  2826. return false;
  2827. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  2828. if (HasNonDllImportDtor(B.getType()))
  2829. return false;
  2830. }
  2831. }
  2832. // Inline builtins declaration must be emitted. They often are fortified
  2833. // functions.
  2834. if (F->isInlineBuiltinDeclaration())
  2835. return true;
  2836. // PR9614. Avoid cases where the source code is lying to us. An available
  2837. // externally function should have an equivalent function somewhere else,
  2838. // but a function that calls itself through asm label/`__builtin_` trickery is
  2839. // clearly not equivalent to the real implementation.
  2840. // This happens in glibc's btowc and in some configure checks.
  2841. return !isTriviallyRecursive(F);
  2842. }
  2843. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  2844. return CodeGenOpts.OptimizationLevel > 0;
  2845. }
  2846. void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
  2847. llvm::GlobalValue *GV) {
  2848. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2849. if (FD->isCPUSpecificMultiVersion()) {
  2850. auto *Spec = FD->getAttr<CPUSpecificAttr>();
  2851. for (unsigned I = 0; I < Spec->cpus_size(); ++I)
  2852. EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
  2853. // Requires multiple emits.
  2854. } else if (FD->isTargetClonesMultiVersion()) {
  2855. auto *Clone = FD->getAttr<TargetClonesAttr>();
  2856. for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
  2857. if (Clone->isFirstOfVersion(I))
  2858. EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
  2859. EmitTargetClonesResolver(GD);
  2860. } else
  2861. EmitGlobalFunctionDefinition(GD, GV);
  2862. }
  2863. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  2864. const auto *D = cast<ValueDecl>(GD.getDecl());
  2865. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  2866. Context.getSourceManager(),
  2867. "Generating code for declaration");
  2868. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2869. // At -O0, don't generate IR for functions with available_externally
  2870. // linkage.
  2871. if (!shouldEmitFunction(GD))
  2872. return;
  2873. llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
  2874. std::string Name;
  2875. llvm::raw_string_ostream OS(Name);
  2876. FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
  2877. /*Qualified=*/true);
  2878. return Name;
  2879. });
  2880. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  2881. // Make sure to emit the definition(s) before we emit the thunks.
  2882. // This is necessary for the generation of certain thunks.
  2883. if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
  2884. ABI->emitCXXStructor(GD);
  2885. else if (FD->isMultiVersion())
  2886. EmitMultiVersionFunctionDefinition(GD, GV);
  2887. else
  2888. EmitGlobalFunctionDefinition(GD, GV);
  2889. if (Method->isVirtual())
  2890. getVTables().EmitThunks(GD);
  2891. return;
  2892. }
  2893. if (FD->isMultiVersion())
  2894. return EmitMultiVersionFunctionDefinition(GD, GV);
  2895. return EmitGlobalFunctionDefinition(GD, GV);
  2896. }
  2897. if (const auto *VD = dyn_cast<VarDecl>(D))
  2898. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  2899. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  2900. }
  2901. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2902. llvm::Function *NewFn);
  2903. static unsigned
  2904. TargetMVPriority(const TargetInfo &TI,
  2905. const CodeGenFunction::MultiVersionResolverOption &RO) {
  2906. unsigned Priority = 0;
  2907. for (StringRef Feat : RO.Conditions.Features)
  2908. Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
  2909. if (!RO.Conditions.Architecture.empty())
  2910. Priority = std::max(
  2911. Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
  2912. return Priority;
  2913. }
  2914. // Multiversion functions should be at most 'WeakODRLinkage' so that a different
  2915. // TU can forward declare the function without causing problems. Particularly
  2916. // in the cases of CPUDispatch, this causes issues. This also makes sure we
  2917. // work with internal linkage functions, so that the same function name can be
  2918. // used with internal linkage in multiple TUs.
  2919. llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
  2920. GlobalDecl GD) {
  2921. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2922. if (FD->getFormalLinkage() == InternalLinkage)
  2923. return llvm::GlobalValue::InternalLinkage;
  2924. return llvm::GlobalValue::WeakODRLinkage;
  2925. }
  2926. void CodeGenModule::EmitTargetClonesResolver(GlobalDecl GD) {
  2927. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2928. assert(FD && "Not a FunctionDecl?");
  2929. const auto *TC = FD->getAttr<TargetClonesAttr>();
  2930. assert(TC && "Not a target_clones Function?");
  2931. QualType CanonTy = Context.getCanonicalType(FD->getType());
  2932. llvm::Type *DeclTy = getTypes().ConvertType(CanonTy);
  2933. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  2934. const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
  2935. DeclTy = getTypes().GetFunctionType(FInfo);
  2936. }
  2937. llvm::Function *ResolverFunc;
  2938. if (getTarget().supportsIFunc()) {
  2939. auto *IFunc = cast<llvm::GlobalIFunc>(
  2940. GetOrCreateMultiVersionResolver(GD, DeclTy, FD));
  2941. ResolverFunc = cast<llvm::Function>(IFunc->getResolver());
  2942. } else
  2943. ResolverFunc =
  2944. cast<llvm::Function>(GetOrCreateMultiVersionResolver(GD, DeclTy, FD));
  2945. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2946. for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
  2947. ++VersionIndex) {
  2948. if (!TC->isFirstOfVersion(VersionIndex))
  2949. continue;
  2950. StringRef Version = TC->getFeatureStr(VersionIndex);
  2951. StringRef MangledName =
  2952. getMangledName(GD.getWithMultiVersionIndex(VersionIndex));
  2953. llvm::Constant *Func = GetGlobalValue(MangledName);
  2954. assert(Func &&
  2955. "Should have already been created before calling resolver emit");
  2956. StringRef Architecture;
  2957. llvm::SmallVector<StringRef, 1> Feature;
  2958. if (Version.startswith("arch="))
  2959. Architecture = Version.drop_front(sizeof("arch=") - 1);
  2960. else if (Version != "default")
  2961. Feature.push_back(Version);
  2962. Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
  2963. }
  2964. const TargetInfo &TI = getTarget();
  2965. std::stable_sort(
  2966. Options.begin(), Options.end(),
  2967. [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2968. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2969. return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
  2970. });
  2971. CodeGenFunction CGF(*this);
  2972. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2973. }
  2974. void CodeGenModule::emitMultiVersionFunctions() {
  2975. std::vector<GlobalDecl> MVFuncsToEmit;
  2976. MultiVersionFuncs.swap(MVFuncsToEmit);
  2977. for (GlobalDecl GD : MVFuncsToEmit) {
  2978. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2979. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2980. getContext().forEachMultiversionedFunctionVersion(
  2981. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  2982. GlobalDecl CurGD{
  2983. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  2984. StringRef MangledName = getMangledName(CurGD);
  2985. llvm::Constant *Func = GetGlobalValue(MangledName);
  2986. if (!Func) {
  2987. if (CurFD->isDefined()) {
  2988. EmitGlobalFunctionDefinition(CurGD, nullptr);
  2989. Func = GetGlobalValue(MangledName);
  2990. } else {
  2991. const CGFunctionInfo &FI =
  2992. getTypes().arrangeGlobalDeclaration(GD);
  2993. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2994. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  2995. /*DontDefer=*/false, ForDefinition);
  2996. }
  2997. assert(Func && "This should have just been created");
  2998. }
  2999. const auto *TA = CurFD->getAttr<TargetAttr>();
  3000. llvm::SmallVector<StringRef, 8> Feats;
  3001. TA->getAddedFeatures(Feats);
  3002. Options.emplace_back(cast<llvm::Function>(Func),
  3003. TA->getArchitecture(), Feats);
  3004. });
  3005. llvm::Function *ResolverFunc;
  3006. const TargetInfo &TI = getTarget();
  3007. if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
  3008. ResolverFunc = cast<llvm::Function>(
  3009. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  3010. ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
  3011. } else {
  3012. ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
  3013. }
  3014. if (supportsCOMDAT())
  3015. ResolverFunc->setComdat(
  3016. getModule().getOrInsertComdat(ResolverFunc->getName()));
  3017. llvm::stable_sort(
  3018. Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
  3019. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  3020. return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
  3021. });
  3022. CodeGenFunction CGF(*this);
  3023. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  3024. }
  3025. // Ensure that any additions to the deferred decls list caused by emitting a
  3026. // variant are emitted. This can happen when the variant itself is inline and
  3027. // calls a function without linkage.
  3028. if (!MVFuncsToEmit.empty())
  3029. EmitDeferred();
  3030. // Ensure that any additions to the multiversion funcs list from either the
  3031. // deferred decls or the multiversion functions themselves are emitted.
  3032. if (!MultiVersionFuncs.empty())
  3033. emitMultiVersionFunctions();
  3034. }
  3035. void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
  3036. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  3037. assert(FD && "Not a FunctionDecl?");
  3038. assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
  3039. const auto *DD = FD->getAttr<CPUDispatchAttr>();
  3040. assert(DD && "Not a cpu_dispatch Function?");
  3041. llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
  3042. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  3043. const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
  3044. DeclTy = getTypes().GetFunctionType(FInfo);
  3045. }
  3046. StringRef ResolverName = getMangledName(GD);
  3047. UpdateMultiVersionNames(GD, FD, ResolverName);
  3048. llvm::Type *ResolverType;
  3049. GlobalDecl ResolverGD;
  3050. if (getTarget().supportsIFunc()) {
  3051. ResolverType = llvm::FunctionType::get(
  3052. llvm::PointerType::get(DeclTy,
  3053. Context.getTargetAddressSpace(FD->getType())),
  3054. false);
  3055. }
  3056. else {
  3057. ResolverType = DeclTy;
  3058. ResolverGD = GD;
  3059. }
  3060. auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
  3061. ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
  3062. ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
  3063. if (supportsCOMDAT())
  3064. ResolverFunc->setComdat(
  3065. getModule().getOrInsertComdat(ResolverFunc->getName()));
  3066. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  3067. const TargetInfo &Target = getTarget();
  3068. unsigned Index = 0;
  3069. for (const IdentifierInfo *II : DD->cpus()) {
  3070. // Get the name of the target function so we can look it up/create it.
  3071. std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
  3072. getCPUSpecificMangling(*this, II->getName());
  3073. llvm::Constant *Func = GetGlobalValue(MangledName);
  3074. if (!Func) {
  3075. GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
  3076. if (ExistingDecl.getDecl() &&
  3077. ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
  3078. EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
  3079. Func = GetGlobalValue(MangledName);
  3080. } else {
  3081. if (!ExistingDecl.getDecl())
  3082. ExistingDecl = GD.getWithMultiVersionIndex(Index);
  3083. Func = GetOrCreateLLVMFunction(
  3084. MangledName, DeclTy, ExistingDecl,
  3085. /*ForVTable=*/false, /*DontDefer=*/true,
  3086. /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
  3087. }
  3088. }
  3089. llvm::SmallVector<StringRef, 32> Features;
  3090. Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
  3091. llvm::transform(Features, Features.begin(),
  3092. [](StringRef Str) { return Str.substr(1); });
  3093. llvm::erase_if(Features, [&Target](StringRef Feat) {
  3094. return !Target.validateCpuSupports(Feat);
  3095. });
  3096. Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
  3097. ++Index;
  3098. }
  3099. llvm::stable_sort(
  3100. Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
  3101. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  3102. return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
  3103. llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
  3104. });
  3105. // If the list contains multiple 'default' versions, such as when it contains
  3106. // 'pentium' and 'generic', don't emit the call to the generic one (since we
  3107. // always run on at least a 'pentium'). We do this by deleting the 'least
  3108. // advanced' (read, lowest mangling letter).
  3109. while (Options.size() > 1 &&
  3110. llvm::X86::getCpuSupportsMask(
  3111. (Options.end() - 2)->Conditions.Features) == 0) {
  3112. StringRef LHSName = (Options.end() - 2)->Function->getName();
  3113. StringRef RHSName = (Options.end() - 1)->Function->getName();
  3114. if (LHSName.compare(RHSName) < 0)
  3115. Options.erase(Options.end() - 2);
  3116. else
  3117. Options.erase(Options.end() - 1);
  3118. }
  3119. CodeGenFunction CGF(*this);
  3120. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  3121. if (getTarget().supportsIFunc()) {
  3122. std::string AliasName = getMangledNameImpl(
  3123. *this, GD, FD, /*OmitMultiVersionMangling=*/true);
  3124. llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
  3125. if (!AliasFunc) {
  3126. auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
  3127. AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
  3128. /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
  3129. auto *GA = llvm::GlobalAlias::create(DeclTy, 0,
  3130. getMultiversionLinkage(*this, GD),
  3131. AliasName, IFunc, &getModule());
  3132. SetCommonAttributes(GD, GA);
  3133. }
  3134. }
  3135. }
  3136. /// If a dispatcher for the specified mangled name is not in the module, create
  3137. /// and return an llvm Function with the specified type.
  3138. llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
  3139. GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
  3140. std::string MangledName =
  3141. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  3142. // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
  3143. // a separate resolver).
  3144. std::string ResolverName = MangledName;
  3145. if (getTarget().supportsIFunc())
  3146. ResolverName += ".ifunc";
  3147. else if (FD->isTargetMultiVersion())
  3148. ResolverName += ".resolver";
  3149. // If this already exists, just return that one.
  3150. if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
  3151. return ResolverGV;
  3152. // Since this is the first time we've created this IFunc, make sure
  3153. // that we put this multiversioned function into the list to be
  3154. // replaced later if necessary (target multiversioning only).
  3155. if (FD->isTargetMultiVersion())
  3156. MultiVersionFuncs.push_back(GD);
  3157. else if (FD->isTargetClonesMultiVersion()) {
  3158. // In target_clones multiversioning, make sure we emit this if used.
  3159. auto DDI =
  3160. DeferredDecls.find(getMangledName(GD.getWithMultiVersionIndex(0)));
  3161. if (DDI != DeferredDecls.end()) {
  3162. addDeferredDeclToEmit(GD);
  3163. DeferredDecls.erase(DDI);
  3164. } else {
  3165. // Emit the symbol of the 1st variant, so that the deferred decls know we
  3166. // need it, otherwise the only global value will be the resolver/ifunc,
  3167. // which end up getting broken if we search for them with GetGlobalValue'.
  3168. GetOrCreateLLVMFunction(
  3169. getMangledName(GD.getWithMultiVersionIndex(0)), DeclTy, FD,
  3170. /*ForVTable=*/false, /*DontDefer=*/true,
  3171. /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
  3172. }
  3173. }
  3174. if (getTarget().supportsIFunc()) {
  3175. llvm::Type *ResolverType = llvm::FunctionType::get(
  3176. llvm::PointerType::get(
  3177. DeclTy, getContext().getTargetAddressSpace(FD->getType())),
  3178. false);
  3179. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  3180. MangledName + ".resolver", ResolverType, GlobalDecl{},
  3181. /*ForVTable=*/false);
  3182. llvm::GlobalIFunc *GIF =
  3183. llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
  3184. "", Resolver, &getModule());
  3185. GIF->setName(ResolverName);
  3186. SetCommonAttributes(FD, GIF);
  3187. return GIF;
  3188. }
  3189. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  3190. ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
  3191. assert(isa<llvm::GlobalValue>(Resolver) &&
  3192. "Resolver should be created for the first time");
  3193. SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
  3194. return Resolver;
  3195. }
  3196. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  3197. /// module, create and return an llvm Function with the specified type. If there
  3198. /// is something in the module with the specified name, return it potentially
  3199. /// bitcasted to the right type.
  3200. ///
  3201. /// If D is non-null, it specifies a decl that correspond to this. This is used
  3202. /// to set the attributes on the function when it is first created.
  3203. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  3204. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  3205. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  3206. ForDefinition_t IsForDefinition) {
  3207. const Decl *D = GD.getDecl();
  3208. // Any attempts to use a MultiVersion function should result in retrieving
  3209. // the iFunc instead. Name Mangling will handle the rest of the changes.
  3210. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  3211. // For the device mark the function as one that should be emitted.
  3212. if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
  3213. !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
  3214. !DontDefer && !IsForDefinition) {
  3215. if (const FunctionDecl *FDDef = FD->getDefinition()) {
  3216. GlobalDecl GDDef;
  3217. if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
  3218. GDDef = GlobalDecl(CD, GD.getCtorType());
  3219. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
  3220. GDDef = GlobalDecl(DD, GD.getDtorType());
  3221. else
  3222. GDDef = GlobalDecl(FDDef);
  3223. EmitGlobal(GDDef);
  3224. }
  3225. }
  3226. if (FD->isMultiVersion()) {
  3227. UpdateMultiVersionNames(GD, FD, MangledName);
  3228. if (!IsForDefinition)
  3229. return GetOrCreateMultiVersionResolver(GD, Ty, FD);
  3230. }
  3231. }
  3232. // Lookup the entry, lazily creating it if necessary.
  3233. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3234. if (Entry) {
  3235. if (WeakRefReferences.erase(Entry)) {
  3236. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  3237. if (FD && !FD->hasAttr<WeakAttr>())
  3238. Entry->setLinkage(llvm::Function::ExternalLinkage);
  3239. }
  3240. // Handle dropped DLL attributes.
  3241. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
  3242. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  3243. setDSOLocal(Entry);
  3244. }
  3245. // If there are two attempts to define the same mangled name, issue an
  3246. // error.
  3247. if (IsForDefinition && !Entry->isDeclaration()) {
  3248. GlobalDecl OtherGD;
  3249. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  3250. // to make sure that we issue an error only once.
  3251. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3252. (GD.getCanonicalDecl().getDecl() !=
  3253. OtherGD.getCanonicalDecl().getDecl()) &&
  3254. DiagnosedConflictingDefinitions.insert(GD).second) {
  3255. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  3256. << MangledName;
  3257. getDiags().Report(OtherGD.getDecl()->getLocation(),
  3258. diag::note_previous_definition);
  3259. }
  3260. }
  3261. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  3262. (Entry->getValueType() == Ty)) {
  3263. return Entry;
  3264. }
  3265. // Make sure the result is of the correct type.
  3266. // (If function is requested for a definition, we always need to create a new
  3267. // function, not just return a bitcast.)
  3268. if (!IsForDefinition)
  3269. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  3270. }
  3271. // This function doesn't have a complete type (for example, the return
  3272. // type is an incomplete struct). Use a fake type instead, and make
  3273. // sure not to try to set attributes.
  3274. bool IsIncompleteFunction = false;
  3275. llvm::FunctionType *FTy;
  3276. if (isa<llvm::FunctionType>(Ty)) {
  3277. FTy = cast<llvm::FunctionType>(Ty);
  3278. } else {
  3279. FTy = llvm::FunctionType::get(VoidTy, false);
  3280. IsIncompleteFunction = true;
  3281. }
  3282. llvm::Function *F =
  3283. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  3284. Entry ? StringRef() : MangledName, &getModule());
  3285. // If we already created a function with the same mangled name (but different
  3286. // type) before, take its name and add it to the list of functions to be
  3287. // replaced with F at the end of CodeGen.
  3288. //
  3289. // This happens if there is a prototype for a function (e.g. "int f()") and
  3290. // then a definition of a different type (e.g. "int f(int x)").
  3291. if (Entry) {
  3292. F->takeName(Entry);
  3293. // This might be an implementation of a function without a prototype, in
  3294. // which case, try to do special replacement of calls which match the new
  3295. // prototype. The really key thing here is that we also potentially drop
  3296. // arguments from the call site so as to make a direct call, which makes the
  3297. // inliner happier and suppresses a number of optimizer warnings (!) about
  3298. // dropping arguments.
  3299. if (!Entry->use_empty()) {
  3300. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  3301. Entry->removeDeadConstantUsers();
  3302. }
  3303. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  3304. F, Entry->getValueType()->getPointerTo());
  3305. addGlobalValReplacement(Entry, BC);
  3306. }
  3307. assert(F->getName() == MangledName && "name was uniqued!");
  3308. if (D)
  3309. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  3310. if (ExtraAttrs.hasFnAttrs()) {
  3311. llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
  3312. F->addFnAttrs(B);
  3313. }
  3314. if (!DontDefer) {
  3315. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  3316. // each other bottoming out with the base dtor. Therefore we emit non-base
  3317. // dtors on usage, even if there is no dtor definition in the TU.
  3318. if (D && isa<CXXDestructorDecl>(D) &&
  3319. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  3320. GD.getDtorType()))
  3321. addDeferredDeclToEmit(GD);
  3322. // This is the first use or definition of a mangled name. If there is a
  3323. // deferred decl with this name, remember that we need to emit it at the end
  3324. // of the file.
  3325. auto DDI = DeferredDecls.find(MangledName);
  3326. if (DDI != DeferredDecls.end()) {
  3327. // Move the potentially referenced deferred decl to the
  3328. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  3329. // don't need it anymore).
  3330. addDeferredDeclToEmit(DDI->second);
  3331. DeferredDecls.erase(DDI);
  3332. // Otherwise, there are cases we have to worry about where we're
  3333. // using a declaration for which we must emit a definition but where
  3334. // we might not find a top-level definition:
  3335. // - member functions defined inline in their classes
  3336. // - friend functions defined inline in some class
  3337. // - special member functions with implicit definitions
  3338. // If we ever change our AST traversal to walk into class methods,
  3339. // this will be unnecessary.
  3340. //
  3341. // We also don't emit a definition for a function if it's going to be an
  3342. // entry in a vtable, unless it's already marked as used.
  3343. } else if (getLangOpts().CPlusPlus && D) {
  3344. // Look for a declaration that's lexically in a record.
  3345. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  3346. FD = FD->getPreviousDecl()) {
  3347. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  3348. if (FD->doesThisDeclarationHaveABody()) {
  3349. addDeferredDeclToEmit(GD.getWithDecl(FD));
  3350. break;
  3351. }
  3352. }
  3353. }
  3354. }
  3355. }
  3356. // Make sure the result is of the requested type.
  3357. if (!IsIncompleteFunction) {
  3358. assert(F->getFunctionType() == Ty);
  3359. return F;
  3360. }
  3361. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  3362. return llvm::ConstantExpr::getBitCast(F, PTy);
  3363. }
  3364. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  3365. /// non-null, then this function will use the specified type if it has to
  3366. /// create it (this occurs when we see a definition of the function).
  3367. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  3368. llvm::Type *Ty,
  3369. bool ForVTable,
  3370. bool DontDefer,
  3371. ForDefinition_t IsForDefinition) {
  3372. assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
  3373. "consteval function should never be emitted");
  3374. // If there was no specific requested type, just convert it now.
  3375. if (!Ty) {
  3376. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  3377. Ty = getTypes().ConvertType(FD->getType());
  3378. }
  3379. // Devirtualized destructor calls may come through here instead of via
  3380. // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
  3381. // of the complete destructor when necessary.
  3382. if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
  3383. if (getTarget().getCXXABI().isMicrosoft() &&
  3384. GD.getDtorType() == Dtor_Complete &&
  3385. DD->getParent()->getNumVBases() == 0)
  3386. GD = GlobalDecl(DD, Dtor_Base);
  3387. }
  3388. StringRef MangledName = getMangledName(GD);
  3389. auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  3390. /*IsThunk=*/false, llvm::AttributeList(),
  3391. IsForDefinition);
  3392. // Returns kernel handle for HIP kernel stub function.
  3393. if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  3394. cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
  3395. auto *Handle = getCUDARuntime().getKernelHandle(
  3396. cast<llvm::Function>(F->stripPointerCasts()), GD);
  3397. if (IsForDefinition)
  3398. return F;
  3399. return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
  3400. }
  3401. return F;
  3402. }
  3403. llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
  3404. llvm::GlobalValue *F =
  3405. cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
  3406. return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F),
  3407. llvm::Type::getInt8PtrTy(VMContext));
  3408. }
  3409. static const FunctionDecl *
  3410. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  3411. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  3412. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3413. IdentifierInfo &CII = C.Idents.get(Name);
  3414. for (const auto *Result : DC->lookup(&CII))
  3415. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  3416. return FD;
  3417. if (!C.getLangOpts().CPlusPlus)
  3418. return nullptr;
  3419. // Demangle the premangled name from getTerminateFn()
  3420. IdentifierInfo &CXXII =
  3421. (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
  3422. ? C.Idents.get("terminate")
  3423. : C.Idents.get(Name);
  3424. for (const auto &N : {"__cxxabiv1", "std"}) {
  3425. IdentifierInfo &NS = C.Idents.get(N);
  3426. for (const auto *Result : DC->lookup(&NS)) {
  3427. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  3428. if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
  3429. for (const auto *Result : LSD->lookup(&NS))
  3430. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  3431. break;
  3432. if (ND)
  3433. for (const auto *Result : ND->lookup(&CXXII))
  3434. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  3435. return FD;
  3436. }
  3437. }
  3438. return nullptr;
  3439. }
  3440. /// CreateRuntimeFunction - Create a new runtime function with the specified
  3441. /// type and name.
  3442. llvm::FunctionCallee
  3443. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  3444. llvm::AttributeList ExtraAttrs, bool Local,
  3445. bool AssumeConvergent) {
  3446. if (AssumeConvergent) {
  3447. ExtraAttrs =
  3448. ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
  3449. }
  3450. llvm::Constant *C =
  3451. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  3452. /*DontDefer=*/false, /*IsThunk=*/false,
  3453. ExtraAttrs);
  3454. if (auto *F = dyn_cast<llvm::Function>(C)) {
  3455. if (F->empty()) {
  3456. F->setCallingConv(getRuntimeCC());
  3457. // In Windows Itanium environments, try to mark runtime functions
  3458. // dllimport. For Mingw and MSVC, don't. We don't really know if the user
  3459. // will link their standard library statically or dynamically. Marking
  3460. // functions imported when they are not imported can cause linker errors
  3461. // and warnings.
  3462. if (!Local && getTriple().isWindowsItaniumEnvironment() &&
  3463. !getCodeGenOpts().LTOVisibilityPublicStd) {
  3464. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  3465. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  3466. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3467. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3468. }
  3469. }
  3470. setDSOLocal(F);
  3471. }
  3472. }
  3473. return {FTy, C};
  3474. }
  3475. /// isTypeConstant - Determine whether an object of this type can be emitted
  3476. /// as a constant.
  3477. ///
  3478. /// If ExcludeCtor is true, the duration when the object's constructor runs
  3479. /// will not be considered. The caller will need to verify that the object is
  3480. /// not written to during its construction.
  3481. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  3482. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  3483. return false;
  3484. if (Context.getLangOpts().CPlusPlus) {
  3485. if (const CXXRecordDecl *Record
  3486. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  3487. return ExcludeCtor && !Record->hasMutableFields() &&
  3488. Record->hasTrivialDestructor();
  3489. }
  3490. return true;
  3491. }
  3492. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  3493. /// create and return an llvm GlobalVariable with the specified type and address
  3494. /// space. If there is something in the module with the specified name, return
  3495. /// it potentially bitcasted to the right type.
  3496. ///
  3497. /// If D is non-null, it specifies a decl that correspond to this. This is used
  3498. /// to set the attributes on the global when it is first created.
  3499. ///
  3500. /// If IsForDefinition is true, it is guaranteed that an actual global with
  3501. /// type Ty will be returned, not conversion of a variable with the same
  3502. /// mangled name but some other type.
  3503. llvm::Constant *
  3504. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
  3505. LangAS AddrSpace, const VarDecl *D,
  3506. ForDefinition_t IsForDefinition) {
  3507. // Lookup the entry, lazily creating it if necessary.
  3508. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3509. unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  3510. if (Entry) {
  3511. if (WeakRefReferences.erase(Entry)) {
  3512. if (D && !D->hasAttr<WeakAttr>())
  3513. Entry->setLinkage(llvm::Function::ExternalLinkage);
  3514. }
  3515. // Handle dropped DLL attributes.
  3516. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  3517. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  3518. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
  3519. getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
  3520. if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
  3521. return Entry;
  3522. // If there are two attempts to define the same mangled name, issue an
  3523. // error.
  3524. if (IsForDefinition && !Entry->isDeclaration()) {
  3525. GlobalDecl OtherGD;
  3526. const VarDecl *OtherD;
  3527. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  3528. // to make sure that we issue an error only once.
  3529. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  3530. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  3531. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  3532. OtherD->hasInit() &&
  3533. DiagnosedConflictingDefinitions.insert(D).second) {
  3534. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  3535. << MangledName;
  3536. getDiags().Report(OtherGD.getDecl()->getLocation(),
  3537. diag::note_previous_definition);
  3538. }
  3539. }
  3540. // Make sure the result is of the correct type.
  3541. if (Entry->getType()->getAddressSpace() != TargetAS) {
  3542. return llvm::ConstantExpr::getAddrSpaceCast(Entry,
  3543. Ty->getPointerTo(TargetAS));
  3544. }
  3545. // (If global is requested for a definition, we always need to create a new
  3546. // global, not just return a bitcast.)
  3547. if (!IsForDefinition)
  3548. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
  3549. }
  3550. auto DAddrSpace = GetGlobalVarAddressSpace(D);
  3551. auto *GV = new llvm::GlobalVariable(
  3552. getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
  3553. MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
  3554. getContext().getTargetAddressSpace(DAddrSpace));
  3555. // If we already created a global with the same mangled name (but different
  3556. // type) before, take its name and remove it from its parent.
  3557. if (Entry) {
  3558. GV->takeName(Entry);
  3559. if (!Entry->use_empty()) {
  3560. llvm::Constant *NewPtrForOldDecl =
  3561. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  3562. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  3563. }
  3564. Entry->eraseFromParent();
  3565. }
  3566. // This is the first use or definition of a mangled name. If there is a
  3567. // deferred decl with this name, remember that we need to emit it at the end
  3568. // of the file.
  3569. auto DDI = DeferredDecls.find(MangledName);
  3570. if (DDI != DeferredDecls.end()) {
  3571. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  3572. // list, and remove it from DeferredDecls (since we don't need it anymore).
  3573. addDeferredDeclToEmit(DDI->second);
  3574. DeferredDecls.erase(DDI);
  3575. }
  3576. // Handle things which are present even on external declarations.
  3577. if (D) {
  3578. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
  3579. getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
  3580. // FIXME: This code is overly simple and should be merged with other global
  3581. // handling.
  3582. GV->setConstant(isTypeConstant(D->getType(), false));
  3583. GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
  3584. setLinkageForGV(GV, D);
  3585. if (D->getTLSKind()) {
  3586. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  3587. CXXThreadLocals.push_back(D);
  3588. setTLSMode(GV, *D);
  3589. }
  3590. setGVProperties(GV, D);
  3591. // If required by the ABI, treat declarations of static data members with
  3592. // inline initializers as definitions.
  3593. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  3594. EmitGlobalVarDefinition(D);
  3595. }
  3596. // Emit section information for extern variables.
  3597. if (D->hasExternalStorage()) {
  3598. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  3599. GV->setSection(SA->getName());
  3600. }
  3601. // Handle XCore specific ABI requirements.
  3602. if (getTriple().getArch() == llvm::Triple::xcore &&
  3603. D->getLanguageLinkage() == CLanguageLinkage &&
  3604. D->getType().isConstant(Context) &&
  3605. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  3606. GV->setSection(".cp.rodata");
  3607. // Check if we a have a const declaration with an initializer, we may be
  3608. // able to emit it as available_externally to expose it's value to the
  3609. // optimizer.
  3610. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  3611. D->getType().isConstQualified() && !GV->hasInitializer() &&
  3612. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  3613. const auto *Record =
  3614. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  3615. bool HasMutableFields = Record && Record->hasMutableFields();
  3616. if (!HasMutableFields) {
  3617. const VarDecl *InitDecl;
  3618. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  3619. if (InitExpr) {
  3620. ConstantEmitter emitter(*this);
  3621. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  3622. if (Init) {
  3623. auto *InitType = Init->getType();
  3624. if (GV->getValueType() != InitType) {
  3625. // The type of the initializer does not match the definition.
  3626. // This happens when an initializer has a different type from
  3627. // the type of the global (because of padding at the end of a
  3628. // structure for instance).
  3629. GV->setName(StringRef());
  3630. // Make a new global with the correct type, this is now guaranteed
  3631. // to work.
  3632. auto *NewGV = cast<llvm::GlobalVariable>(
  3633. GetAddrOfGlobalVar(D, InitType, IsForDefinition)
  3634. ->stripPointerCasts());
  3635. // Erase the old global, since it is no longer used.
  3636. GV->eraseFromParent();
  3637. GV = NewGV;
  3638. } else {
  3639. GV->setInitializer(Init);
  3640. GV->setConstant(true);
  3641. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  3642. }
  3643. emitter.finalize(GV);
  3644. }
  3645. }
  3646. }
  3647. }
  3648. }
  3649. if (GV->isDeclaration()) {
  3650. getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
  3651. // External HIP managed variables needed to be recorded for transformation
  3652. // in both device and host compilations.
  3653. if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
  3654. D->hasExternalStorage())
  3655. getCUDARuntime().handleVarRegistration(D, *GV);
  3656. }
  3657. LangAS ExpectedAS =
  3658. D ? D->getType().getAddressSpace()
  3659. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  3660. assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
  3661. if (DAddrSpace != ExpectedAS) {
  3662. return getTargetCodeGenInfo().performAddrSpaceCast(
  3663. *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
  3664. }
  3665. return GV;
  3666. }
  3667. llvm::Constant *
  3668. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
  3669. const Decl *D = GD.getDecl();
  3670. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  3671. return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  3672. /*DontDefer=*/false, IsForDefinition);
  3673. if (isa<CXXMethodDecl>(D)) {
  3674. auto FInfo =
  3675. &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
  3676. auto Ty = getTypes().GetFunctionType(*FInfo);
  3677. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  3678. IsForDefinition);
  3679. }
  3680. if (isa<FunctionDecl>(D)) {
  3681. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3682. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3683. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  3684. IsForDefinition);
  3685. }
  3686. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
  3687. }
  3688. llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
  3689. StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
  3690. unsigned Alignment) {
  3691. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  3692. llvm::GlobalVariable *OldGV = nullptr;
  3693. if (GV) {
  3694. // Check if the variable has the right type.
  3695. if (GV->getValueType() == Ty)
  3696. return GV;
  3697. // Because C++ name mangling, the only way we can end up with an already
  3698. // existing global with the same name is if it has been declared extern "C".
  3699. assert(GV->isDeclaration() && "Declaration has wrong type!");
  3700. OldGV = GV;
  3701. }
  3702. // Create a new variable.
  3703. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  3704. Linkage, nullptr, Name);
  3705. if (OldGV) {
  3706. // Replace occurrences of the old variable if needed.
  3707. GV->takeName(OldGV);
  3708. if (!OldGV->use_empty()) {
  3709. llvm::Constant *NewPtrForOldDecl =
  3710. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  3711. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  3712. }
  3713. OldGV->eraseFromParent();
  3714. }
  3715. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  3716. !GV->hasAvailableExternallyLinkage())
  3717. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3718. GV->setAlignment(llvm::MaybeAlign(Alignment));
  3719. return GV;
  3720. }
  3721. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  3722. /// given global variable. If Ty is non-null and if the global doesn't exist,
  3723. /// then it will be created with the specified type instead of whatever the
  3724. /// normal requested type would be. If IsForDefinition is true, it is guaranteed
  3725. /// that an actual global with type Ty will be returned, not conversion of a
  3726. /// variable with the same mangled name but some other type.
  3727. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  3728. llvm::Type *Ty,
  3729. ForDefinition_t IsForDefinition) {
  3730. assert(D->hasGlobalStorage() && "Not a global variable");
  3731. QualType ASTTy = D->getType();
  3732. if (!Ty)
  3733. Ty = getTypes().ConvertTypeForMem(ASTTy);
  3734. StringRef MangledName = getMangledName(D);
  3735. return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
  3736. IsForDefinition);
  3737. }
  3738. /// CreateRuntimeVariable - Create a new runtime global variable with the
  3739. /// specified type and name.
  3740. llvm::Constant *
  3741. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  3742. StringRef Name) {
  3743. LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
  3744. : LangAS::Default;
  3745. auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
  3746. setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
  3747. return Ret;
  3748. }
  3749. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  3750. assert(!D->getInit() && "Cannot emit definite definitions here!");
  3751. StringRef MangledName = getMangledName(D);
  3752. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  3753. // We already have a definition, not declaration, with the same mangled name.
  3754. // Emitting of declaration is not required (and actually overwrites emitted
  3755. // definition).
  3756. if (GV && !GV->isDeclaration())
  3757. return;
  3758. // If we have not seen a reference to this variable yet, place it into the
  3759. // deferred declarations table to be emitted if needed later.
  3760. if (!MustBeEmitted(D) && !GV) {
  3761. DeferredDecls[MangledName] = D;
  3762. return;
  3763. }
  3764. // The tentative definition is the only definition.
  3765. EmitGlobalVarDefinition(D);
  3766. }
  3767. void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
  3768. EmitExternalVarDeclaration(D);
  3769. }
  3770. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  3771. return Context.toCharUnitsFromBits(
  3772. getDataLayout().getTypeStoreSizeInBits(Ty));
  3773. }
  3774. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  3775. if (LangOpts.OpenCL) {
  3776. LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  3777. assert(AS == LangAS::opencl_global ||
  3778. AS == LangAS::opencl_global_device ||
  3779. AS == LangAS::opencl_global_host ||
  3780. AS == LangAS::opencl_constant ||
  3781. AS == LangAS::opencl_local ||
  3782. AS >= LangAS::FirstTargetAddressSpace);
  3783. return AS;
  3784. }
  3785. if (LangOpts.SYCLIsDevice &&
  3786. (!D || D->getType().getAddressSpace() == LangAS::Default))
  3787. return LangAS::sycl_global;
  3788. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  3789. if (D && D->hasAttr<CUDAConstantAttr>())
  3790. return LangAS::cuda_constant;
  3791. else if (D && D->hasAttr<CUDASharedAttr>())
  3792. return LangAS::cuda_shared;
  3793. else if (D && D->hasAttr<CUDADeviceAttr>())
  3794. return LangAS::cuda_device;
  3795. else if (D && D->getType().isConstQualified())
  3796. return LangAS::cuda_constant;
  3797. else
  3798. return LangAS::cuda_device;
  3799. }
  3800. if (LangOpts.OpenMP) {
  3801. LangAS AS;
  3802. if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
  3803. return AS;
  3804. }
  3805. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  3806. }
  3807. LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
  3808. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  3809. if (LangOpts.OpenCL)
  3810. return LangAS::opencl_constant;
  3811. if (LangOpts.SYCLIsDevice)
  3812. return LangAS::sycl_global;
  3813. if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
  3814. // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
  3815. // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
  3816. // with OpVariable instructions with Generic storage class which is not
  3817. // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
  3818. // UniformConstant storage class is not viable as pointers to it may not be
  3819. // casted to Generic pointers which are used to model HIP's "flat" pointers.
  3820. return LangAS::cuda_device;
  3821. if (auto AS = getTarget().getConstantAddressSpace())
  3822. return AS.getValue();
  3823. return LangAS::Default;
  3824. }
  3825. // In address space agnostic languages, string literals are in default address
  3826. // space in AST. However, certain targets (e.g. amdgcn) request them to be
  3827. // emitted in constant address space in LLVM IR. To be consistent with other
  3828. // parts of AST, string literal global variables in constant address space
  3829. // need to be casted to default address space before being put into address
  3830. // map and referenced by other part of CodeGen.
  3831. // In OpenCL, string literals are in constant address space in AST, therefore
  3832. // they should not be casted to default address space.
  3833. static llvm::Constant *
  3834. castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
  3835. llvm::GlobalVariable *GV) {
  3836. llvm::Constant *Cast = GV;
  3837. if (!CGM.getLangOpts().OpenCL) {
  3838. auto AS = CGM.GetGlobalConstantAddressSpace();
  3839. if (AS != LangAS::Default)
  3840. Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  3841. CGM, GV, AS, LangAS::Default,
  3842. GV->getValueType()->getPointerTo(
  3843. CGM.getContext().getTargetAddressSpace(LangAS::Default)));
  3844. }
  3845. return Cast;
  3846. }
  3847. template<typename SomeDecl>
  3848. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  3849. llvm::GlobalValue *GV) {
  3850. if (!getLangOpts().CPlusPlus)
  3851. return;
  3852. // Must have 'used' attribute, or else inline assembly can't rely on
  3853. // the name existing.
  3854. if (!D->template hasAttr<UsedAttr>())
  3855. return;
  3856. // Must have internal linkage and an ordinary name.
  3857. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  3858. return;
  3859. // Must be in an extern "C" context. Entities declared directly within
  3860. // a record are not extern "C" even if the record is in such a context.
  3861. const SomeDecl *First = D->getFirstDecl();
  3862. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  3863. return;
  3864. // OK, this is an internal linkage entity inside an extern "C" linkage
  3865. // specification. Make a note of that so we can give it the "expected"
  3866. // mangled name if nothing else is using that name.
  3867. std::pair<StaticExternCMap::iterator, bool> R =
  3868. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  3869. // If we have multiple internal linkage entities with the same name
  3870. // in extern "C" regions, none of them gets that name.
  3871. if (!R.second)
  3872. R.first->second = nullptr;
  3873. }
  3874. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  3875. if (!CGM.supportsCOMDAT())
  3876. return false;
  3877. if (D.hasAttr<SelectAnyAttr>())
  3878. return true;
  3879. GVALinkage Linkage;
  3880. if (auto *VD = dyn_cast<VarDecl>(&D))
  3881. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  3882. else
  3883. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  3884. switch (Linkage) {
  3885. case GVA_Internal:
  3886. case GVA_AvailableExternally:
  3887. case GVA_StrongExternal:
  3888. return false;
  3889. case GVA_DiscardableODR:
  3890. case GVA_StrongODR:
  3891. return true;
  3892. }
  3893. llvm_unreachable("No such linkage");
  3894. }
  3895. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  3896. llvm::GlobalObject &GO) {
  3897. if (!shouldBeInCOMDAT(*this, D))
  3898. return;
  3899. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  3900. }
  3901. /// Pass IsTentative as true if you want to create a tentative definition.
  3902. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  3903. bool IsTentative) {
  3904. // OpenCL global variables of sampler type are translated to function calls,
  3905. // therefore no need to be translated.
  3906. QualType ASTTy = D->getType();
  3907. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  3908. return;
  3909. // If this is OpenMP device, check if it is legal to emit this global
  3910. // normally.
  3911. if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
  3912. OpenMPRuntime->emitTargetGlobalVariable(D))
  3913. return;
  3914. llvm::TrackingVH<llvm::Constant> Init;
  3915. bool NeedsGlobalCtor = false;
  3916. bool NeedsGlobalDtor =
  3917. D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
  3918. const VarDecl *InitDecl;
  3919. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  3920. Optional<ConstantEmitter> emitter;
  3921. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  3922. // as part of their declaration." Sema has already checked for
  3923. // error cases, so we just need to set Init to UndefValue.
  3924. bool IsCUDASharedVar =
  3925. getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
  3926. // Shadows of initialized device-side global variables are also left
  3927. // undefined.
  3928. // Managed Variables should be initialized on both host side and device side.
  3929. bool IsCUDAShadowVar =
  3930. !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
  3931. (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
  3932. D->hasAttr<CUDASharedAttr>());
  3933. bool IsCUDADeviceShadowVar =
  3934. getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
  3935. (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
  3936. D->getType()->isCUDADeviceBuiltinTextureType());
  3937. if (getLangOpts().CUDA &&
  3938. (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
  3939. Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
  3940. else if (D->hasAttr<LoaderUninitializedAttr>())
  3941. Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
  3942. else if (!InitExpr) {
  3943. // This is a tentative definition; tentative definitions are
  3944. // implicitly initialized with { 0 }.
  3945. //
  3946. // Note that tentative definitions are only emitted at the end of
  3947. // a translation unit, so they should never have incomplete
  3948. // type. In addition, EmitTentativeDefinition makes sure that we
  3949. // never attempt to emit a tentative definition if a real one
  3950. // exists. A use may still exists, however, so we still may need
  3951. // to do a RAUW.
  3952. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  3953. Init = EmitNullConstant(D->getType());
  3954. } else {
  3955. initializedGlobalDecl = GlobalDecl(D);
  3956. emitter.emplace(*this);
  3957. llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
  3958. if (!Initializer) {
  3959. QualType T = InitExpr->getType();
  3960. if (D->getType()->isReferenceType())
  3961. T = D->getType();
  3962. if (getLangOpts().CPlusPlus) {
  3963. Init = EmitNullConstant(T);
  3964. NeedsGlobalCtor = true;
  3965. } else {
  3966. ErrorUnsupported(D, "static initializer");
  3967. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  3968. }
  3969. } else {
  3970. Init = Initializer;
  3971. // We don't need an initializer, so remove the entry for the delayed
  3972. // initializer position (just in case this entry was delayed) if we
  3973. // also don't need to register a destructor.
  3974. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  3975. DelayedCXXInitPosition.erase(D);
  3976. }
  3977. }
  3978. llvm::Type* InitType = Init->getType();
  3979. llvm::Constant *Entry =
  3980. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  3981. // Strip off pointer casts if we got them.
  3982. Entry = Entry->stripPointerCasts();
  3983. // Entry is now either a Function or GlobalVariable.
  3984. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  3985. // We have a definition after a declaration with the wrong type.
  3986. // We must make a new GlobalVariable* and update everything that used OldGV
  3987. // (a declaration or tentative definition) with the new GlobalVariable*
  3988. // (which will be a definition).
  3989. //
  3990. // This happens if there is a prototype for a global (e.g.
  3991. // "extern int x[];") and then a definition of a different type (e.g.
  3992. // "int x[10];"). This also happens when an initializer has a different type
  3993. // from the type of the global (this happens with unions).
  3994. if (!GV || GV->getValueType() != InitType ||
  3995. GV->getType()->getAddressSpace() !=
  3996. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  3997. // Move the old entry aside so that we'll create a new one.
  3998. Entry->setName(StringRef());
  3999. // Make a new global with the correct type, this is now guaranteed to work.
  4000. GV = cast<llvm::GlobalVariable>(
  4001. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
  4002. ->stripPointerCasts());
  4003. // Replace all uses of the old global with the new global
  4004. llvm::Constant *NewPtrForOldDecl =
  4005. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
  4006. Entry->getType());
  4007. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  4008. // Erase the old global, since it is no longer used.
  4009. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  4010. }
  4011. MaybeHandleStaticInExternC(D, GV);
  4012. if (D->hasAttr<AnnotateAttr>())
  4013. AddGlobalAnnotations(D, GV);
  4014. // Set the llvm linkage type as appropriate.
  4015. llvm::GlobalValue::LinkageTypes Linkage =
  4016. getLLVMLinkageVarDefinition(D, GV->isConstant());
  4017. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  4018. // the device. [...]"
  4019. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  4020. // __device__, declares a variable that: [...]
  4021. // Is accessible from all the threads within the grid and from the host
  4022. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  4023. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  4024. if (GV && LangOpts.CUDA) {
  4025. if (LangOpts.CUDAIsDevice) {
  4026. if (Linkage != llvm::GlobalValue::InternalLinkage &&
  4027. (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
  4028. D->getType()->isCUDADeviceBuiltinSurfaceType() ||
  4029. D->getType()->isCUDADeviceBuiltinTextureType()))
  4030. GV->setExternallyInitialized(true);
  4031. } else {
  4032. getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
  4033. }
  4034. getCUDARuntime().handleVarRegistration(D, *GV);
  4035. }
  4036. GV->setInitializer(Init);
  4037. if (emitter)
  4038. emitter->finalize(GV);
  4039. // If it is safe to mark the global 'constant', do so now.
  4040. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  4041. isTypeConstant(D->getType(), true));
  4042. // If it is in a read-only section, mark it 'constant'.
  4043. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  4044. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  4045. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  4046. GV->setConstant(true);
  4047. }
  4048. GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
  4049. // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
  4050. // function is only defined alongside the variable, not also alongside
  4051. // callers. Normally, all accesses to a thread_local go through the
  4052. // thread-wrapper in order to ensure initialization has occurred, underlying
  4053. // variable will never be used other than the thread-wrapper, so it can be
  4054. // converted to internal linkage.
  4055. //
  4056. // However, if the variable has the 'constinit' attribute, it _can_ be
  4057. // referenced directly, without calling the thread-wrapper, so the linkage
  4058. // must not be changed.
  4059. //
  4060. // Additionally, if the variable isn't plain external linkage, e.g. if it's
  4061. // weak or linkonce, the de-duplication semantics are important to preserve,
  4062. // so we don't change the linkage.
  4063. if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
  4064. Linkage == llvm::GlobalValue::ExternalLinkage &&
  4065. Context.getTargetInfo().getTriple().isOSDarwin() &&
  4066. !D->hasAttr<ConstInitAttr>())
  4067. Linkage = llvm::GlobalValue::InternalLinkage;
  4068. GV->setLinkage(Linkage);
  4069. if (D->hasAttr<DLLImportAttr>())
  4070. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  4071. else if (D->hasAttr<DLLExportAttr>())
  4072. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  4073. else
  4074. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  4075. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  4076. // common vars aren't constant even if declared const.
  4077. GV->setConstant(false);
  4078. // Tentative definition of global variables may be initialized with
  4079. // non-zero null pointers. In this case they should have weak linkage
  4080. // since common linkage must have zero initializer and must not have
  4081. // explicit section therefore cannot have non-zero initial value.
  4082. if (!GV->getInitializer()->isNullValue())
  4083. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  4084. }
  4085. setNonAliasAttributes(D, GV);
  4086. if (D->getTLSKind() && !GV->isThreadLocal()) {
  4087. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  4088. CXXThreadLocals.push_back(D);
  4089. setTLSMode(GV, *D);
  4090. }
  4091. maybeSetTrivialComdat(*D, *GV);
  4092. // Emit the initializer function if necessary.
  4093. if (NeedsGlobalCtor || NeedsGlobalDtor)
  4094. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  4095. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  4096. // Emit global variable debug information.
  4097. if (CGDebugInfo *DI = getModuleDebugInfo())
  4098. if (getCodeGenOpts().hasReducedDebugInfo())
  4099. DI->EmitGlobalVariable(GV, D);
  4100. }
  4101. void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
  4102. if (CGDebugInfo *DI = getModuleDebugInfo())
  4103. if (getCodeGenOpts().hasReducedDebugInfo()) {
  4104. QualType ASTTy = D->getType();
  4105. llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
  4106. llvm::Constant *GV =
  4107. GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
  4108. DI->EmitExternalVariable(
  4109. cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
  4110. }
  4111. }
  4112. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  4113. CodeGenModule &CGM, const VarDecl *D,
  4114. bool NoCommon) {
  4115. // Don't give variables common linkage if -fno-common was specified unless it
  4116. // was overridden by a NoCommon attribute.
  4117. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  4118. return true;
  4119. // C11 6.9.2/2:
  4120. // A declaration of an identifier for an object that has file scope without
  4121. // an initializer, and without a storage-class specifier or with the
  4122. // storage-class specifier static, constitutes a tentative definition.
  4123. if (D->getInit() || D->hasExternalStorage())
  4124. return true;
  4125. // A variable cannot be both common and exist in a section.
  4126. if (D->hasAttr<SectionAttr>())
  4127. return true;
  4128. // A variable cannot be both common and exist in a section.
  4129. // We don't try to determine which is the right section in the front-end.
  4130. // If no specialized section name is applicable, it will resort to default.
  4131. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  4132. D->hasAttr<PragmaClangDataSectionAttr>() ||
  4133. D->hasAttr<PragmaClangRelroSectionAttr>() ||
  4134. D->hasAttr<PragmaClangRodataSectionAttr>())
  4135. return true;
  4136. // Thread local vars aren't considered common linkage.
  4137. if (D->getTLSKind())
  4138. return true;
  4139. // Tentative definitions marked with WeakImportAttr are true definitions.
  4140. if (D->hasAttr<WeakImportAttr>())
  4141. return true;
  4142. // A variable cannot be both common and exist in a comdat.
  4143. if (shouldBeInCOMDAT(CGM, *D))
  4144. return true;
  4145. // Declarations with a required alignment do not have common linkage in MSVC
  4146. // mode.
  4147. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  4148. if (D->hasAttr<AlignedAttr>())
  4149. return true;
  4150. QualType VarType = D->getType();
  4151. if (Context.isAlignmentRequired(VarType))
  4152. return true;
  4153. if (const auto *RT = VarType->getAs<RecordType>()) {
  4154. const RecordDecl *RD = RT->getDecl();
  4155. for (const FieldDecl *FD : RD->fields()) {
  4156. if (FD->isBitField())
  4157. continue;
  4158. if (FD->hasAttr<AlignedAttr>())
  4159. return true;
  4160. if (Context.isAlignmentRequired(FD->getType()))
  4161. return true;
  4162. }
  4163. }
  4164. }
  4165. // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
  4166. // common symbols, so symbols with greater alignment requirements cannot be
  4167. // common.
  4168. // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
  4169. // alignments for common symbols via the aligncomm directive, so this
  4170. // restriction only applies to MSVC environments.
  4171. if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
  4172. Context.getTypeAlignIfKnown(D->getType()) >
  4173. Context.toBits(CharUnits::fromQuantity(32)))
  4174. return true;
  4175. return false;
  4176. }
  4177. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  4178. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  4179. if (Linkage == GVA_Internal)
  4180. return llvm::Function::InternalLinkage;
  4181. if (D->hasAttr<WeakAttr>()) {
  4182. if (IsConstantVariable)
  4183. return llvm::GlobalVariable::WeakODRLinkage;
  4184. else
  4185. return llvm::GlobalVariable::WeakAnyLinkage;
  4186. }
  4187. if (const auto *FD = D->getAsFunction())
  4188. if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
  4189. return llvm::GlobalVariable::LinkOnceAnyLinkage;
  4190. // We are guaranteed to have a strong definition somewhere else,
  4191. // so we can use available_externally linkage.
  4192. if (Linkage == GVA_AvailableExternally)
  4193. return llvm::GlobalValue::AvailableExternallyLinkage;
  4194. // Note that Apple's kernel linker doesn't support symbol
  4195. // coalescing, so we need to avoid linkonce and weak linkages there.
  4196. // Normally, this means we just map to internal, but for explicit
  4197. // instantiations we'll map to external.
  4198. // In C++, the compiler has to emit a definition in every translation unit
  4199. // that references the function. We should use linkonce_odr because
  4200. // a) if all references in this translation unit are optimized away, we
  4201. // don't need to codegen it. b) if the function persists, it needs to be
  4202. // merged with other definitions. c) C++ has the ODR, so we know the
  4203. // definition is dependable.
  4204. if (Linkage == GVA_DiscardableODR)
  4205. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  4206. : llvm::Function::InternalLinkage;
  4207. // An explicit instantiation of a template has weak linkage, since
  4208. // explicit instantiations can occur in multiple translation units
  4209. // and must all be equivalent. However, we are not allowed to
  4210. // throw away these explicit instantiations.
  4211. //
  4212. // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
  4213. // so say that CUDA templates are either external (for kernels) or internal.
  4214. // This lets llvm perform aggressive inter-procedural optimizations. For
  4215. // -fgpu-rdc case, device function calls across multiple TU's are allowed,
  4216. // therefore we need to follow the normal linkage paradigm.
  4217. if (Linkage == GVA_StrongODR) {
  4218. if (getLangOpts().AppleKext)
  4219. return llvm::Function::ExternalLinkage;
  4220. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  4221. !getLangOpts().GPURelocatableDeviceCode)
  4222. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  4223. : llvm::Function::InternalLinkage;
  4224. return llvm::Function::WeakODRLinkage;
  4225. }
  4226. // C++ doesn't have tentative definitions and thus cannot have common
  4227. // linkage.
  4228. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  4229. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  4230. CodeGenOpts.NoCommon))
  4231. return llvm::GlobalVariable::CommonLinkage;
  4232. // selectany symbols are externally visible, so use weak instead of
  4233. // linkonce. MSVC optimizes away references to const selectany globals, so
  4234. // all definitions should be the same and ODR linkage should be used.
  4235. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  4236. if (D->hasAttr<SelectAnyAttr>())
  4237. return llvm::GlobalVariable::WeakODRLinkage;
  4238. // Otherwise, we have strong external linkage.
  4239. assert(Linkage == GVA_StrongExternal);
  4240. return llvm::GlobalVariable::ExternalLinkage;
  4241. }
  4242. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  4243. const VarDecl *VD, bool IsConstant) {
  4244. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  4245. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  4246. }
  4247. /// Replace the uses of a function that was declared with a non-proto type.
  4248. /// We want to silently drop extra arguments from call sites
  4249. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  4250. llvm::Function *newFn) {
  4251. // Fast path.
  4252. if (old->use_empty()) return;
  4253. llvm::Type *newRetTy = newFn->getReturnType();
  4254. SmallVector<llvm::Value*, 4> newArgs;
  4255. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  4256. ui != ue; ) {
  4257. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  4258. llvm::User *user = use->getUser();
  4259. // Recognize and replace uses of bitcasts. Most calls to
  4260. // unprototyped functions will use bitcasts.
  4261. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  4262. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  4263. replaceUsesOfNonProtoConstant(bitcast, newFn);
  4264. continue;
  4265. }
  4266. // Recognize calls to the function.
  4267. llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
  4268. if (!callSite) continue;
  4269. if (!callSite->isCallee(&*use))
  4270. continue;
  4271. // If the return types don't match exactly, then we can't
  4272. // transform this call unless it's dead.
  4273. if (callSite->getType() != newRetTy && !callSite->use_empty())
  4274. continue;
  4275. // Get the call site's attribute list.
  4276. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  4277. llvm::AttributeList oldAttrs = callSite->getAttributes();
  4278. // If the function was passed too few arguments, don't transform.
  4279. unsigned newNumArgs = newFn->arg_size();
  4280. if (callSite->arg_size() < newNumArgs)
  4281. continue;
  4282. // If extra arguments were passed, we silently drop them.
  4283. // If any of the types mismatch, we don't transform.
  4284. unsigned argNo = 0;
  4285. bool dontTransform = false;
  4286. for (llvm::Argument &A : newFn->args()) {
  4287. if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
  4288. dontTransform = true;
  4289. break;
  4290. }
  4291. // Add any parameter attributes.
  4292. newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
  4293. argNo++;
  4294. }
  4295. if (dontTransform)
  4296. continue;
  4297. // Okay, we can transform this. Create the new call instruction and copy
  4298. // over the required information.
  4299. newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
  4300. // Copy over any operand bundles.
  4301. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  4302. callSite->getOperandBundlesAsDefs(newBundles);
  4303. llvm::CallBase *newCall;
  4304. if (isa<llvm::CallInst>(callSite)) {
  4305. newCall =
  4306. llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
  4307. } else {
  4308. auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
  4309. newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
  4310. oldInvoke->getUnwindDest(), newArgs,
  4311. newBundles, "", callSite);
  4312. }
  4313. newArgs.clear(); // for the next iteration
  4314. if (!newCall->getType()->isVoidTy())
  4315. newCall->takeName(callSite);
  4316. newCall->setAttributes(
  4317. llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
  4318. oldAttrs.getRetAttrs(), newArgAttrs));
  4319. newCall->setCallingConv(callSite->getCallingConv());
  4320. // Finally, remove the old call, replacing any uses with the new one.
  4321. if (!callSite->use_empty())
  4322. callSite->replaceAllUsesWith(newCall);
  4323. // Copy debug location attached to CI.
  4324. if (callSite->getDebugLoc())
  4325. newCall->setDebugLoc(callSite->getDebugLoc());
  4326. callSite->eraseFromParent();
  4327. }
  4328. }
  4329. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  4330. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  4331. /// existing call uses of the old function in the module, this adjusts them to
  4332. /// call the new function directly.
  4333. ///
  4334. /// This is not just a cleanup: the always_inline pass requires direct calls to
  4335. /// functions to be able to inline them. If there is a bitcast in the way, it
  4336. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  4337. /// run at -O0.
  4338. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  4339. llvm::Function *NewFn) {
  4340. // If we're redefining a global as a function, don't transform it.
  4341. if (!isa<llvm::Function>(Old)) return;
  4342. replaceUsesOfNonProtoConstant(Old, NewFn);
  4343. }
  4344. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  4345. auto DK = VD->isThisDeclarationADefinition();
  4346. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  4347. return;
  4348. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  4349. // If we have a definition, this might be a deferred decl. If the
  4350. // instantiation is explicit, make sure we emit it at the end.
  4351. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  4352. GetAddrOfGlobalVar(VD);
  4353. EmitTopLevelDecl(VD);
  4354. }
  4355. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  4356. llvm::GlobalValue *GV) {
  4357. const auto *D = cast<FunctionDecl>(GD.getDecl());
  4358. // Compute the function info and LLVM type.
  4359. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  4360. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  4361. // Get or create the prototype for the function.
  4362. if (!GV || (GV->getValueType() != Ty))
  4363. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  4364. /*DontDefer=*/true,
  4365. ForDefinition));
  4366. // Already emitted.
  4367. if (!GV->isDeclaration())
  4368. return;
  4369. // We need to set linkage and visibility on the function before
  4370. // generating code for it because various parts of IR generation
  4371. // want to propagate this information down (e.g. to local static
  4372. // declarations).
  4373. auto *Fn = cast<llvm::Function>(GV);
  4374. setFunctionLinkage(GD, Fn);
  4375. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  4376. setGVProperties(Fn, GD);
  4377. MaybeHandleStaticInExternC(D, Fn);
  4378. maybeSetTrivialComdat(*D, *Fn);
  4379. // Set CodeGen attributes that represent floating point environment.
  4380. setLLVMFunctionFEnvAttributes(D, Fn);
  4381. CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
  4382. setNonAliasAttributes(GD, Fn);
  4383. SetLLVMFunctionAttributesForDefinition(D, Fn);
  4384. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  4385. AddGlobalCtor(Fn, CA->getPriority());
  4386. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  4387. AddGlobalDtor(Fn, DA->getPriority(), true);
  4388. if (D->hasAttr<AnnotateAttr>())
  4389. AddGlobalAnnotations(D, Fn);
  4390. }
  4391. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  4392. const auto *D = cast<ValueDecl>(GD.getDecl());
  4393. const AliasAttr *AA = D->getAttr<AliasAttr>();
  4394. assert(AA && "Not an alias?");
  4395. StringRef MangledName = getMangledName(GD);
  4396. if (AA->getAliasee() == MangledName) {
  4397. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  4398. return;
  4399. }
  4400. // If there is a definition in the module, then it wins over the alias.
  4401. // This is dubious, but allow it to be safe. Just ignore the alias.
  4402. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  4403. if (Entry && !Entry->isDeclaration())
  4404. return;
  4405. Aliases.push_back(GD);
  4406. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  4407. // Create a reference to the named value. This ensures that it is emitted
  4408. // if a deferred decl.
  4409. llvm::Constant *Aliasee;
  4410. llvm::GlobalValue::LinkageTypes LT;
  4411. if (isa<llvm::FunctionType>(DeclTy)) {
  4412. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  4413. /*ForVTable=*/false);
  4414. LT = getFunctionLinkage(GD);
  4415. } else {
  4416. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
  4417. /*D=*/nullptr);
  4418. if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
  4419. LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
  4420. else
  4421. LT = getFunctionLinkage(GD);
  4422. }
  4423. // Create the new alias itself, but don't set a name yet.
  4424. unsigned AS = Aliasee->getType()->getPointerAddressSpace();
  4425. auto *GA =
  4426. llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
  4427. if (Entry) {
  4428. if (GA->getAliasee() == Entry) {
  4429. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  4430. return;
  4431. }
  4432. assert(Entry->isDeclaration());
  4433. // If there is a declaration in the module, then we had an extern followed
  4434. // by the alias, as in:
  4435. // extern int test6();
  4436. // ...
  4437. // int test6() __attribute__((alias("test7")));
  4438. //
  4439. // Remove it and replace uses of it with the alias.
  4440. GA->takeName(Entry);
  4441. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  4442. Entry->getType()));
  4443. Entry->eraseFromParent();
  4444. } else {
  4445. GA->setName(MangledName);
  4446. }
  4447. // Set attributes which are particular to an alias; this is a
  4448. // specialization of the attributes which may be set on a global
  4449. // variable/function.
  4450. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  4451. D->isWeakImported()) {
  4452. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  4453. }
  4454. if (const auto *VD = dyn_cast<VarDecl>(D))
  4455. if (VD->getTLSKind())
  4456. setTLSMode(GA, *VD);
  4457. SetCommonAttributes(GD, GA);
  4458. }
  4459. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  4460. const auto *D = cast<ValueDecl>(GD.getDecl());
  4461. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  4462. assert(IFA && "Not an ifunc?");
  4463. StringRef MangledName = getMangledName(GD);
  4464. if (IFA->getResolver() == MangledName) {
  4465. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  4466. return;
  4467. }
  4468. // Report an error if some definition overrides ifunc.
  4469. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  4470. if (Entry && !Entry->isDeclaration()) {
  4471. GlobalDecl OtherGD;
  4472. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  4473. DiagnosedConflictingDefinitions.insert(GD).second) {
  4474. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
  4475. << MangledName;
  4476. Diags.Report(OtherGD.getDecl()->getLocation(),
  4477. diag::note_previous_definition);
  4478. }
  4479. return;
  4480. }
  4481. Aliases.push_back(GD);
  4482. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  4483. llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
  4484. llvm::Constant *Resolver =
  4485. GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
  4486. /*ForVTable=*/false);
  4487. llvm::GlobalIFunc *GIF =
  4488. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  4489. "", Resolver, &getModule());
  4490. if (Entry) {
  4491. if (GIF->getResolver() == Entry) {
  4492. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  4493. return;
  4494. }
  4495. assert(Entry->isDeclaration());
  4496. // If there is a declaration in the module, then we had an extern followed
  4497. // by the ifunc, as in:
  4498. // extern int test();
  4499. // ...
  4500. // int test() __attribute__((ifunc("resolver")));
  4501. //
  4502. // Remove it and replace uses of it with the ifunc.
  4503. GIF->takeName(Entry);
  4504. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  4505. Entry->getType()));
  4506. Entry->eraseFromParent();
  4507. } else
  4508. GIF->setName(MangledName);
  4509. SetCommonAttributes(GD, GIF);
  4510. }
  4511. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  4512. ArrayRef<llvm::Type*> Tys) {
  4513. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  4514. Tys);
  4515. }
  4516. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  4517. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  4518. const StringLiteral *Literal, bool TargetIsLSB,
  4519. bool &IsUTF16, unsigned &StringLength) {
  4520. StringRef String = Literal->getString();
  4521. unsigned NumBytes = String.size();
  4522. // Check for simple case.
  4523. if (!Literal->containsNonAsciiOrNull()) {
  4524. StringLength = NumBytes;
  4525. return *Map.insert(std::make_pair(String, nullptr)).first;
  4526. }
  4527. // Otherwise, convert the UTF8 literals into a string of shorts.
  4528. IsUTF16 = true;
  4529. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  4530. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  4531. llvm::UTF16 *ToPtr = &ToBuf[0];
  4532. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  4533. ToPtr + NumBytes, llvm::strictConversion);
  4534. // ConvertUTF8toUTF16 returns the length in ToPtr.
  4535. StringLength = ToPtr - &ToBuf[0];
  4536. // Add an explicit null.
  4537. *ToPtr = 0;
  4538. return *Map.insert(std::make_pair(
  4539. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  4540. (StringLength + 1) * 2),
  4541. nullptr)).first;
  4542. }
  4543. ConstantAddress
  4544. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  4545. unsigned StringLength = 0;
  4546. bool isUTF16 = false;
  4547. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  4548. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  4549. getDataLayout().isLittleEndian(), isUTF16,
  4550. StringLength);
  4551. if (auto *C = Entry.second)
  4552. return ConstantAddress(
  4553. C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
  4554. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  4555. llvm::Constant *Zeros[] = { Zero, Zero };
  4556. const ASTContext &Context = getContext();
  4557. const llvm::Triple &Triple = getTriple();
  4558. const auto CFRuntime = getLangOpts().CFRuntime;
  4559. const bool IsSwiftABI =
  4560. static_cast<unsigned>(CFRuntime) >=
  4561. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
  4562. const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
  4563. // If we don't already have it, get __CFConstantStringClassReference.
  4564. if (!CFConstantStringClassRef) {
  4565. const char *CFConstantStringClassName = "__CFConstantStringClassReference";
  4566. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  4567. Ty = llvm::ArrayType::get(Ty, 0);
  4568. switch (CFRuntime) {
  4569. default: break;
  4570. case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
  4571. case LangOptions::CoreFoundationABI::Swift5_0:
  4572. CFConstantStringClassName =
  4573. Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
  4574. : "$s10Foundation19_NSCFConstantStringCN";
  4575. Ty = IntPtrTy;
  4576. break;
  4577. case LangOptions::CoreFoundationABI::Swift4_2:
  4578. CFConstantStringClassName =
  4579. Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
  4580. : "$S10Foundation19_NSCFConstantStringCN";
  4581. Ty = IntPtrTy;
  4582. break;
  4583. case LangOptions::CoreFoundationABI::Swift4_1:
  4584. CFConstantStringClassName =
  4585. Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
  4586. : "__T010Foundation19_NSCFConstantStringCN";
  4587. Ty = IntPtrTy;
  4588. break;
  4589. }
  4590. llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
  4591. if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
  4592. llvm::GlobalValue *GV = nullptr;
  4593. if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
  4594. IdentifierInfo &II = Context.Idents.get(GV->getName());
  4595. TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
  4596. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  4597. const VarDecl *VD = nullptr;
  4598. for (const auto *Result : DC->lookup(&II))
  4599. if ((VD = dyn_cast<VarDecl>(Result)))
  4600. break;
  4601. if (Triple.isOSBinFormatELF()) {
  4602. if (!VD)
  4603. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  4604. } else {
  4605. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  4606. if (!VD || !VD->hasAttr<DLLExportAttr>())
  4607. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  4608. else
  4609. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  4610. }
  4611. setDSOLocal(GV);
  4612. }
  4613. }
  4614. // Decay array -> ptr
  4615. CFConstantStringClassRef =
  4616. IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
  4617. : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
  4618. }
  4619. QualType CFTy = Context.getCFConstantStringType();
  4620. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  4621. ConstantInitBuilder Builder(*this);
  4622. auto Fields = Builder.beginStruct(STy);
  4623. // Class pointer.
  4624. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  4625. // Flags.
  4626. if (IsSwiftABI) {
  4627. Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
  4628. Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
  4629. } else {
  4630. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  4631. }
  4632. // String pointer.
  4633. llvm::Constant *C = nullptr;
  4634. if (isUTF16) {
  4635. auto Arr = llvm::makeArrayRef(
  4636. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  4637. Entry.first().size() / 2);
  4638. C = llvm::ConstantDataArray::get(VMContext, Arr);
  4639. } else {
  4640. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  4641. }
  4642. // Note: -fwritable-strings doesn't make the backing store strings of
  4643. // CFStrings writable. (See <rdar://problem/10657500>)
  4644. auto *GV =
  4645. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  4646. llvm::GlobalValue::PrivateLinkage, C, ".str");
  4647. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  4648. // Don't enforce the target's minimum global alignment, since the only use
  4649. // of the string is via this class initializer.
  4650. CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
  4651. : Context.getTypeAlignInChars(Context.CharTy);
  4652. GV->setAlignment(Align.getAsAlign());
  4653. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  4654. // Without it LLVM can merge the string with a non unnamed_addr one during
  4655. // LTO. Doing that changes the section it ends in, which surprises ld64.
  4656. if (Triple.isOSBinFormatMachO())
  4657. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  4658. : "__TEXT,__cstring,cstring_literals");
  4659. // Make sure the literal ends up in .rodata to allow for safe ICF and for
  4660. // the static linker to adjust permissions to read-only later on.
  4661. else if (Triple.isOSBinFormatELF())
  4662. GV->setSection(".rodata");
  4663. // String.
  4664. llvm::Constant *Str =
  4665. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  4666. if (isUTF16)
  4667. // Cast the UTF16 string to the correct type.
  4668. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  4669. Fields.add(Str);
  4670. // String length.
  4671. llvm::IntegerType *LengthTy =
  4672. llvm::IntegerType::get(getModule().getContext(),
  4673. Context.getTargetInfo().getLongWidth());
  4674. if (IsSwiftABI) {
  4675. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  4676. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  4677. LengthTy = Int32Ty;
  4678. else
  4679. LengthTy = IntPtrTy;
  4680. }
  4681. Fields.addInt(LengthTy, StringLength);
  4682. // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
  4683. // properly aligned on 32-bit platforms.
  4684. CharUnits Alignment =
  4685. IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
  4686. // The struct.
  4687. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  4688. /*isConstant=*/false,
  4689. llvm::GlobalVariable::PrivateLinkage);
  4690. GV->addAttribute("objc_arc_inert");
  4691. switch (Triple.getObjectFormat()) {
  4692. case llvm::Triple::UnknownObjectFormat:
  4693. llvm_unreachable("unknown file format");
  4694. case llvm::Triple::GOFF:
  4695. llvm_unreachable("GOFF is not yet implemented");
  4696. case llvm::Triple::XCOFF:
  4697. llvm_unreachable("XCOFF is not yet implemented");
  4698. case llvm::Triple::COFF:
  4699. case llvm::Triple::ELF:
  4700. case llvm::Triple::Wasm:
  4701. GV->setSection("cfstring");
  4702. break;
  4703. case llvm::Triple::MachO:
  4704. GV->setSection("__DATA,__cfstring");
  4705. break;
  4706. }
  4707. Entry.second = GV;
  4708. return ConstantAddress(GV, GV->getValueType(), Alignment);
  4709. }
  4710. bool CodeGenModule::getExpressionLocationsEnabled() const {
  4711. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  4712. }
  4713. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  4714. if (ObjCFastEnumerationStateType.isNull()) {
  4715. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  4716. D->startDefinition();
  4717. QualType FieldTypes[] = {
  4718. Context.UnsignedLongTy,
  4719. Context.getPointerType(Context.getObjCIdType()),
  4720. Context.getPointerType(Context.UnsignedLongTy),
  4721. Context.getConstantArrayType(Context.UnsignedLongTy,
  4722. llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
  4723. };
  4724. for (size_t i = 0; i < 4; ++i) {
  4725. FieldDecl *Field = FieldDecl::Create(Context,
  4726. D,
  4727. SourceLocation(),
  4728. SourceLocation(), nullptr,
  4729. FieldTypes[i], /*TInfo=*/nullptr,
  4730. /*BitWidth=*/nullptr,
  4731. /*Mutable=*/false,
  4732. ICIS_NoInit);
  4733. Field->setAccess(AS_public);
  4734. D->addDecl(Field);
  4735. }
  4736. D->completeDefinition();
  4737. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  4738. }
  4739. return ObjCFastEnumerationStateType;
  4740. }
  4741. llvm::Constant *
  4742. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  4743. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  4744. // Don't emit it as the address of the string, emit the string data itself
  4745. // as an inline array.
  4746. if (E->getCharByteWidth() == 1) {
  4747. SmallString<64> Str(E->getString());
  4748. // Resize the string to the right size, which is indicated by its type.
  4749. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  4750. Str.resize(CAT->getSize().getZExtValue());
  4751. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  4752. }
  4753. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  4754. llvm::Type *ElemTy = AType->getElementType();
  4755. unsigned NumElements = AType->getNumElements();
  4756. // Wide strings have either 2-byte or 4-byte elements.
  4757. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  4758. SmallVector<uint16_t, 32> Elements;
  4759. Elements.reserve(NumElements);
  4760. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  4761. Elements.push_back(E->getCodeUnit(i));
  4762. Elements.resize(NumElements);
  4763. return llvm::ConstantDataArray::get(VMContext, Elements);
  4764. }
  4765. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  4766. SmallVector<uint32_t, 32> Elements;
  4767. Elements.reserve(NumElements);
  4768. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  4769. Elements.push_back(E->getCodeUnit(i));
  4770. Elements.resize(NumElements);
  4771. return llvm::ConstantDataArray::get(VMContext, Elements);
  4772. }
  4773. static llvm::GlobalVariable *
  4774. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  4775. CodeGenModule &CGM, StringRef GlobalName,
  4776. CharUnits Alignment) {
  4777. unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
  4778. CGM.GetGlobalConstantAddressSpace());
  4779. llvm::Module &M = CGM.getModule();
  4780. // Create a global variable for this string
  4781. auto *GV = new llvm::GlobalVariable(
  4782. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  4783. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  4784. GV->setAlignment(Alignment.getAsAlign());
  4785. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  4786. if (GV->isWeakForLinker()) {
  4787. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  4788. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  4789. }
  4790. CGM.setDSOLocal(GV);
  4791. return GV;
  4792. }
  4793. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  4794. /// constant array for the given string literal.
  4795. ConstantAddress
  4796. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  4797. StringRef Name) {
  4798. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  4799. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  4800. llvm::GlobalVariable **Entry = nullptr;
  4801. if (!LangOpts.WritableStrings) {
  4802. Entry = &ConstantStringMap[C];
  4803. if (auto GV = *Entry) {
  4804. if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
  4805. GV->setAlignment(Alignment.getAsAlign());
  4806. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4807. GV->getValueType(), Alignment);
  4808. }
  4809. }
  4810. SmallString<256> MangledNameBuffer;
  4811. StringRef GlobalVariableName;
  4812. llvm::GlobalValue::LinkageTypes LT;
  4813. // Mangle the string literal if that's how the ABI merges duplicate strings.
  4814. // Don't do it if they are writable, since we don't want writes in one TU to
  4815. // affect strings in another.
  4816. if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
  4817. !LangOpts.WritableStrings) {
  4818. llvm::raw_svector_ostream Out(MangledNameBuffer);
  4819. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  4820. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  4821. GlobalVariableName = MangledNameBuffer;
  4822. } else {
  4823. LT = llvm::GlobalValue::PrivateLinkage;
  4824. GlobalVariableName = Name;
  4825. }
  4826. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  4827. if (Entry)
  4828. *Entry = GV;
  4829. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  4830. QualType());
  4831. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4832. GV->getValueType(), Alignment);
  4833. }
  4834. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  4835. /// array for the given ObjCEncodeExpr node.
  4836. ConstantAddress
  4837. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  4838. std::string Str;
  4839. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  4840. return GetAddrOfConstantCString(Str);
  4841. }
  4842. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  4843. /// the literal and a terminating '\0' character.
  4844. /// The result has pointer to array type.
  4845. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  4846. const std::string &Str, const char *GlobalName) {
  4847. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  4848. CharUnits Alignment =
  4849. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  4850. llvm::Constant *C =
  4851. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  4852. // Don't share any string literals if strings aren't constant.
  4853. llvm::GlobalVariable **Entry = nullptr;
  4854. if (!LangOpts.WritableStrings) {
  4855. Entry = &ConstantStringMap[C];
  4856. if (auto GV = *Entry) {
  4857. if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
  4858. GV->setAlignment(Alignment.getAsAlign());
  4859. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4860. GV->getValueType(), Alignment);
  4861. }
  4862. }
  4863. // Get the default prefix if a name wasn't specified.
  4864. if (!GlobalName)
  4865. GlobalName = ".str";
  4866. // Create a global variable for this.
  4867. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  4868. GlobalName, Alignment);
  4869. if (Entry)
  4870. *Entry = GV;
  4871. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4872. GV->getValueType(), Alignment);
  4873. }
  4874. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  4875. const MaterializeTemporaryExpr *E, const Expr *Init) {
  4876. assert((E->getStorageDuration() == SD_Static ||
  4877. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  4878. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  4879. // If we're not materializing a subobject of the temporary, keep the
  4880. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  4881. QualType MaterializedType = Init->getType();
  4882. if (Init == E->getSubExpr())
  4883. MaterializedType = E->getType();
  4884. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  4885. auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
  4886. if (!InsertResult.second) {
  4887. // We've seen this before: either we already created it or we're in the
  4888. // process of doing so.
  4889. if (!InsertResult.first->second) {
  4890. // We recursively re-entered this function, probably during emission of
  4891. // the initializer. Create a placeholder. We'll clean this up in the
  4892. // outer call, at the end of this function.
  4893. llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
  4894. InsertResult.first->second = new llvm::GlobalVariable(
  4895. getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
  4896. nullptr);
  4897. }
  4898. return ConstantAddress(
  4899. InsertResult.first->second,
  4900. InsertResult.first->second->getType()->getPointerElementType(), Align);
  4901. }
  4902. // FIXME: If an externally-visible declaration extends multiple temporaries,
  4903. // we need to give each temporary the same name in every translation unit (and
  4904. // we also need to make the temporaries externally-visible).
  4905. SmallString<256> Name;
  4906. llvm::raw_svector_ostream Out(Name);
  4907. getCXXABI().getMangleContext().mangleReferenceTemporary(
  4908. VD, E->getManglingNumber(), Out);
  4909. APValue *Value = nullptr;
  4910. if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
  4911. // If the initializer of the extending declaration is a constant
  4912. // initializer, we should have a cached constant initializer for this
  4913. // temporary. Note that this might have a different value from the value
  4914. // computed by evaluating the initializer if the surrounding constant
  4915. // expression modifies the temporary.
  4916. Value = E->getOrCreateValue(false);
  4917. }
  4918. // Try evaluating it now, it might have a constant initializer.
  4919. Expr::EvalResult EvalResult;
  4920. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  4921. !EvalResult.hasSideEffects())
  4922. Value = &EvalResult.Val;
  4923. LangAS AddrSpace =
  4924. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  4925. Optional<ConstantEmitter> emitter;
  4926. llvm::Constant *InitialValue = nullptr;
  4927. bool Constant = false;
  4928. llvm::Type *Type;
  4929. if (Value) {
  4930. // The temporary has a constant initializer, use it.
  4931. emitter.emplace(*this);
  4932. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  4933. MaterializedType);
  4934. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  4935. Type = InitialValue->getType();
  4936. } else {
  4937. // No initializer, the initialization will be provided when we
  4938. // initialize the declaration which performed lifetime extension.
  4939. Type = getTypes().ConvertTypeForMem(MaterializedType);
  4940. }
  4941. // Create a global variable for this lifetime-extended temporary.
  4942. llvm::GlobalValue::LinkageTypes Linkage =
  4943. getLLVMLinkageVarDefinition(VD, Constant);
  4944. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  4945. const VarDecl *InitVD;
  4946. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  4947. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  4948. // Temporaries defined inside a class get linkonce_odr linkage because the
  4949. // class can be defined in multiple translation units.
  4950. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  4951. } else {
  4952. // There is no need for this temporary to have external linkage if the
  4953. // VarDecl has external linkage.
  4954. Linkage = llvm::GlobalVariable::InternalLinkage;
  4955. }
  4956. }
  4957. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  4958. auto *GV = new llvm::GlobalVariable(
  4959. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  4960. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  4961. if (emitter) emitter->finalize(GV);
  4962. setGVProperties(GV, VD);
  4963. GV->setAlignment(Align.getAsAlign());
  4964. if (supportsCOMDAT() && GV->isWeakForLinker())
  4965. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  4966. if (VD->getTLSKind())
  4967. setTLSMode(GV, *VD);
  4968. llvm::Constant *CV = GV;
  4969. if (AddrSpace != LangAS::Default)
  4970. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  4971. *this, GV, AddrSpace, LangAS::Default,
  4972. Type->getPointerTo(
  4973. getContext().getTargetAddressSpace(LangAS::Default)));
  4974. // Update the map with the new temporary. If we created a placeholder above,
  4975. // replace it with the new global now.
  4976. llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
  4977. if (Entry) {
  4978. Entry->replaceAllUsesWith(
  4979. llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
  4980. llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
  4981. }
  4982. Entry = CV;
  4983. return ConstantAddress(CV, Type, Align);
  4984. }
  4985. /// EmitObjCPropertyImplementations - Emit information for synthesized
  4986. /// properties for an implementation.
  4987. void CodeGenModule::EmitObjCPropertyImplementations(const
  4988. ObjCImplementationDecl *D) {
  4989. for (const auto *PID : D->property_impls()) {
  4990. // Dynamic is just for type-checking.
  4991. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  4992. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  4993. // Determine which methods need to be implemented, some may have
  4994. // been overridden. Note that ::isPropertyAccessor is not the method
  4995. // we want, that just indicates if the decl came from a
  4996. // property. What we want to know is if the method is defined in
  4997. // this implementation.
  4998. auto *Getter = PID->getGetterMethodDecl();
  4999. if (!Getter || Getter->isSynthesizedAccessorStub())
  5000. CodeGenFunction(*this).GenerateObjCGetter(
  5001. const_cast<ObjCImplementationDecl *>(D), PID);
  5002. auto *Setter = PID->getSetterMethodDecl();
  5003. if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
  5004. CodeGenFunction(*this).GenerateObjCSetter(
  5005. const_cast<ObjCImplementationDecl *>(D), PID);
  5006. }
  5007. }
  5008. }
  5009. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  5010. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  5011. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  5012. ivar; ivar = ivar->getNextIvar())
  5013. if (ivar->getType().isDestructedType())
  5014. return true;
  5015. return false;
  5016. }
  5017. static bool AllTrivialInitializers(CodeGenModule &CGM,
  5018. ObjCImplementationDecl *D) {
  5019. CodeGenFunction CGF(CGM);
  5020. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  5021. E = D->init_end(); B != E; ++B) {
  5022. CXXCtorInitializer *CtorInitExp = *B;
  5023. Expr *Init = CtorInitExp->getInit();
  5024. if (!CGF.isTrivialInitializer(Init))
  5025. return false;
  5026. }
  5027. return true;
  5028. }
  5029. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  5030. /// for an implementation.
  5031. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  5032. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  5033. if (needsDestructMethod(D)) {
  5034. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  5035. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  5036. ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
  5037. getContext(), D->getLocation(), D->getLocation(), cxxSelector,
  5038. getContext().VoidTy, nullptr, D,
  5039. /*isInstance=*/true, /*isVariadic=*/false,
  5040. /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
  5041. /*isImplicitlyDeclared=*/true,
  5042. /*isDefined=*/false, ObjCMethodDecl::Required);
  5043. D->addInstanceMethod(DTORMethod);
  5044. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  5045. D->setHasDestructors(true);
  5046. }
  5047. // If the implementation doesn't have any ivar initializers, we don't need
  5048. // a .cxx_construct.
  5049. if (D->getNumIvarInitializers() == 0 ||
  5050. AllTrivialInitializers(*this, D))
  5051. return;
  5052. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  5053. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  5054. // The constructor returns 'self'.
  5055. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
  5056. getContext(), D->getLocation(), D->getLocation(), cxxSelector,
  5057. getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
  5058. /*isVariadic=*/false,
  5059. /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
  5060. /*isImplicitlyDeclared=*/true,
  5061. /*isDefined=*/false, ObjCMethodDecl::Required);
  5062. D->addInstanceMethod(CTORMethod);
  5063. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  5064. D->setHasNonZeroConstructors(true);
  5065. }
  5066. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  5067. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  5068. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  5069. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  5070. ErrorUnsupported(LSD, "linkage spec");
  5071. return;
  5072. }
  5073. EmitDeclContext(LSD);
  5074. }
  5075. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  5076. for (auto *I : DC->decls()) {
  5077. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  5078. // are themselves considered "top-level", so EmitTopLevelDecl on an
  5079. // ObjCImplDecl does not recursively visit them. We need to do that in
  5080. // case they're nested inside another construct (LinkageSpecDecl /
  5081. // ExportDecl) that does stop them from being considered "top-level".
  5082. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  5083. for (auto *M : OID->methods())
  5084. EmitTopLevelDecl(M);
  5085. }
  5086. EmitTopLevelDecl(I);
  5087. }
  5088. }
  5089. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  5090. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  5091. // Ignore dependent declarations.
  5092. if (D->isTemplated())
  5093. return;
  5094. // Consteval function shouldn't be emitted.
  5095. if (auto *FD = dyn_cast<FunctionDecl>(D))
  5096. if (FD->isConsteval())
  5097. return;
  5098. switch (D->getKind()) {
  5099. case Decl::CXXConversion:
  5100. case Decl::CXXMethod:
  5101. case Decl::Function:
  5102. EmitGlobal(cast<FunctionDecl>(D));
  5103. // Always provide some coverage mapping
  5104. // even for the functions that aren't emitted.
  5105. AddDeferredUnusedCoverageMapping(D);
  5106. break;
  5107. case Decl::CXXDeductionGuide:
  5108. // Function-like, but does not result in code emission.
  5109. break;
  5110. case Decl::Var:
  5111. case Decl::Decomposition:
  5112. case Decl::VarTemplateSpecialization:
  5113. EmitGlobal(cast<VarDecl>(D));
  5114. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  5115. for (auto *B : DD->bindings())
  5116. if (auto *HD = B->getHoldingVar())
  5117. EmitGlobal(HD);
  5118. break;
  5119. // Indirect fields from global anonymous structs and unions can be
  5120. // ignored; only the actual variable requires IR gen support.
  5121. case Decl::IndirectField:
  5122. break;
  5123. // C++ Decls
  5124. case Decl::Namespace:
  5125. EmitDeclContext(cast<NamespaceDecl>(D));
  5126. break;
  5127. case Decl::ClassTemplateSpecialization: {
  5128. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  5129. if (CGDebugInfo *DI = getModuleDebugInfo())
  5130. if (Spec->getSpecializationKind() ==
  5131. TSK_ExplicitInstantiationDefinition &&
  5132. Spec->hasDefinition())
  5133. DI->completeTemplateDefinition(*Spec);
  5134. } LLVM_FALLTHROUGH;
  5135. case Decl::CXXRecord: {
  5136. CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
  5137. if (CGDebugInfo *DI = getModuleDebugInfo()) {
  5138. if (CRD->hasDefinition())
  5139. DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
  5140. if (auto *ES = D->getASTContext().getExternalSource())
  5141. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  5142. DI->completeUnusedClass(*CRD);
  5143. }
  5144. // Emit any static data members, they may be definitions.
  5145. for (auto *I : CRD->decls())
  5146. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  5147. EmitTopLevelDecl(I);
  5148. break;
  5149. }
  5150. // No code generation needed.
  5151. case Decl::UsingShadow:
  5152. case Decl::ClassTemplate:
  5153. case Decl::VarTemplate:
  5154. case Decl::Concept:
  5155. case Decl::VarTemplatePartialSpecialization:
  5156. case Decl::FunctionTemplate:
  5157. case Decl::TypeAliasTemplate:
  5158. case Decl::Block:
  5159. case Decl::Empty:
  5160. case Decl::Binding:
  5161. break;
  5162. case Decl::Using: // using X; [C++]
  5163. if (CGDebugInfo *DI = getModuleDebugInfo())
  5164. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  5165. break;
  5166. case Decl::UsingEnum: // using enum X; [C++]
  5167. if (CGDebugInfo *DI = getModuleDebugInfo())
  5168. DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
  5169. break;
  5170. case Decl::NamespaceAlias:
  5171. if (CGDebugInfo *DI = getModuleDebugInfo())
  5172. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  5173. break;
  5174. case Decl::UsingDirective: // using namespace X; [C++]
  5175. if (CGDebugInfo *DI = getModuleDebugInfo())
  5176. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  5177. break;
  5178. case Decl::CXXConstructor:
  5179. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  5180. break;
  5181. case Decl::CXXDestructor:
  5182. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  5183. break;
  5184. case Decl::StaticAssert:
  5185. // Nothing to do.
  5186. break;
  5187. // Objective-C Decls
  5188. // Forward declarations, no (immediate) code generation.
  5189. case Decl::ObjCInterface:
  5190. case Decl::ObjCCategory:
  5191. break;
  5192. case Decl::ObjCProtocol: {
  5193. auto *Proto = cast<ObjCProtocolDecl>(D);
  5194. if (Proto->isThisDeclarationADefinition())
  5195. ObjCRuntime->GenerateProtocol(Proto);
  5196. break;
  5197. }
  5198. case Decl::ObjCCategoryImpl:
  5199. // Categories have properties but don't support synthesize so we
  5200. // can ignore them here.
  5201. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  5202. break;
  5203. case Decl::ObjCImplementation: {
  5204. auto *OMD = cast<ObjCImplementationDecl>(D);
  5205. EmitObjCPropertyImplementations(OMD);
  5206. EmitObjCIvarInitializations(OMD);
  5207. ObjCRuntime->GenerateClass(OMD);
  5208. // Emit global variable debug information.
  5209. if (CGDebugInfo *DI = getModuleDebugInfo())
  5210. if (getCodeGenOpts().hasReducedDebugInfo())
  5211. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  5212. OMD->getClassInterface()), OMD->getLocation());
  5213. break;
  5214. }
  5215. case Decl::ObjCMethod: {
  5216. auto *OMD = cast<ObjCMethodDecl>(D);
  5217. // If this is not a prototype, emit the body.
  5218. if (OMD->getBody())
  5219. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  5220. break;
  5221. }
  5222. case Decl::ObjCCompatibleAlias:
  5223. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  5224. break;
  5225. case Decl::PragmaComment: {
  5226. const auto *PCD = cast<PragmaCommentDecl>(D);
  5227. switch (PCD->getCommentKind()) {
  5228. case PCK_Unknown:
  5229. llvm_unreachable("unexpected pragma comment kind");
  5230. case PCK_Linker:
  5231. AppendLinkerOptions(PCD->getArg());
  5232. break;
  5233. case PCK_Lib:
  5234. AddDependentLib(PCD->getArg());
  5235. break;
  5236. case PCK_Compiler:
  5237. case PCK_ExeStr:
  5238. case PCK_User:
  5239. break; // We ignore all of these.
  5240. }
  5241. break;
  5242. }
  5243. case Decl::PragmaDetectMismatch: {
  5244. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  5245. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  5246. break;
  5247. }
  5248. case Decl::LinkageSpec:
  5249. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  5250. break;
  5251. case Decl::FileScopeAsm: {
  5252. // File-scope asm is ignored during device-side CUDA compilation.
  5253. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  5254. break;
  5255. // File-scope asm is ignored during device-side OpenMP compilation.
  5256. if (LangOpts.OpenMPIsDevice)
  5257. break;
  5258. // File-scope asm is ignored during device-side SYCL compilation.
  5259. if (LangOpts.SYCLIsDevice)
  5260. break;
  5261. auto *AD = cast<FileScopeAsmDecl>(D);
  5262. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  5263. break;
  5264. }
  5265. case Decl::Import: {
  5266. auto *Import = cast<ImportDecl>(D);
  5267. // If we've already imported this module, we're done.
  5268. if (!ImportedModules.insert(Import->getImportedModule()))
  5269. break;
  5270. // Emit debug information for direct imports.
  5271. if (!Import->getImportedOwningModule()) {
  5272. if (CGDebugInfo *DI = getModuleDebugInfo())
  5273. DI->EmitImportDecl(*Import);
  5274. }
  5275. // Find all of the submodules and emit the module initializers.
  5276. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  5277. SmallVector<clang::Module *, 16> Stack;
  5278. Visited.insert(Import->getImportedModule());
  5279. Stack.push_back(Import->getImportedModule());
  5280. while (!Stack.empty()) {
  5281. clang::Module *Mod = Stack.pop_back_val();
  5282. if (!EmittedModuleInitializers.insert(Mod).second)
  5283. continue;
  5284. for (auto *D : Context.getModuleInitializers(Mod))
  5285. EmitTopLevelDecl(D);
  5286. // Visit the submodules of this module.
  5287. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  5288. SubEnd = Mod->submodule_end();
  5289. Sub != SubEnd; ++Sub) {
  5290. // Skip explicit children; they need to be explicitly imported to emit
  5291. // the initializers.
  5292. if ((*Sub)->IsExplicit)
  5293. continue;
  5294. if (Visited.insert(*Sub).second)
  5295. Stack.push_back(*Sub);
  5296. }
  5297. }
  5298. break;
  5299. }
  5300. case Decl::Export:
  5301. EmitDeclContext(cast<ExportDecl>(D));
  5302. break;
  5303. case Decl::OMPThreadPrivate:
  5304. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  5305. break;
  5306. case Decl::OMPAllocate:
  5307. EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
  5308. break;
  5309. case Decl::OMPDeclareReduction:
  5310. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  5311. break;
  5312. case Decl::OMPDeclareMapper:
  5313. EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
  5314. break;
  5315. case Decl::OMPRequires:
  5316. EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
  5317. break;
  5318. case Decl::Typedef:
  5319. case Decl::TypeAlias: // using foo = bar; [C++11]
  5320. if (CGDebugInfo *DI = getModuleDebugInfo())
  5321. DI->EmitAndRetainType(
  5322. getContext().getTypedefType(cast<TypedefNameDecl>(D)));
  5323. break;
  5324. case Decl::Record:
  5325. if (CGDebugInfo *DI = getModuleDebugInfo())
  5326. if (cast<RecordDecl>(D)->getDefinition())
  5327. DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
  5328. break;
  5329. case Decl::Enum:
  5330. if (CGDebugInfo *DI = getModuleDebugInfo())
  5331. if (cast<EnumDecl>(D)->getDefinition())
  5332. DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
  5333. break;
  5334. default:
  5335. // Make sure we handled everything we should, every other kind is a
  5336. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  5337. // function. Need to recode Decl::Kind to do that easily.
  5338. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  5339. break;
  5340. }
  5341. }
  5342. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  5343. // Do we need to generate coverage mapping?
  5344. if (!CodeGenOpts.CoverageMapping)
  5345. return;
  5346. switch (D->getKind()) {
  5347. case Decl::CXXConversion:
  5348. case Decl::CXXMethod:
  5349. case Decl::Function:
  5350. case Decl::ObjCMethod:
  5351. case Decl::CXXConstructor:
  5352. case Decl::CXXDestructor: {
  5353. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  5354. break;
  5355. SourceManager &SM = getContext().getSourceManager();
  5356. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
  5357. break;
  5358. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  5359. if (I == DeferredEmptyCoverageMappingDecls.end())
  5360. DeferredEmptyCoverageMappingDecls[D] = true;
  5361. break;
  5362. }
  5363. default:
  5364. break;
  5365. };
  5366. }
  5367. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  5368. // Do we need to generate coverage mapping?
  5369. if (!CodeGenOpts.CoverageMapping)
  5370. return;
  5371. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  5372. if (Fn->isTemplateInstantiation())
  5373. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  5374. }
  5375. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  5376. if (I == DeferredEmptyCoverageMappingDecls.end())
  5377. DeferredEmptyCoverageMappingDecls[D] = false;
  5378. else
  5379. I->second = false;
  5380. }
  5381. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  5382. // We call takeVector() here to avoid use-after-free.
  5383. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  5384. // we deserialize function bodies to emit coverage info for them, and that
  5385. // deserializes more declarations. How should we handle that case?
  5386. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  5387. if (!Entry.second)
  5388. continue;
  5389. const Decl *D = Entry.first;
  5390. switch (D->getKind()) {
  5391. case Decl::CXXConversion:
  5392. case Decl::CXXMethod:
  5393. case Decl::Function:
  5394. case Decl::ObjCMethod: {
  5395. CodeGenPGO PGO(*this);
  5396. GlobalDecl GD(cast<FunctionDecl>(D));
  5397. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  5398. getFunctionLinkage(GD));
  5399. break;
  5400. }
  5401. case Decl::CXXConstructor: {
  5402. CodeGenPGO PGO(*this);
  5403. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  5404. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  5405. getFunctionLinkage(GD));
  5406. break;
  5407. }
  5408. case Decl::CXXDestructor: {
  5409. CodeGenPGO PGO(*this);
  5410. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  5411. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  5412. getFunctionLinkage(GD));
  5413. break;
  5414. }
  5415. default:
  5416. break;
  5417. };
  5418. }
  5419. }
  5420. void CodeGenModule::EmitMainVoidAlias() {
  5421. // In order to transition away from "__original_main" gracefully, emit an
  5422. // alias for "main" in the no-argument case so that libc can detect when
  5423. // new-style no-argument main is in used.
  5424. if (llvm::Function *F = getModule().getFunction("main")) {
  5425. if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
  5426. F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
  5427. addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
  5428. }
  5429. }
  5430. /// Turns the given pointer into a constant.
  5431. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  5432. const void *Ptr) {
  5433. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  5434. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  5435. return llvm::ConstantInt::get(i64, PtrInt);
  5436. }
  5437. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  5438. llvm::NamedMDNode *&GlobalMetadata,
  5439. GlobalDecl D,
  5440. llvm::GlobalValue *Addr) {
  5441. if (!GlobalMetadata)
  5442. GlobalMetadata =
  5443. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  5444. // TODO: should we report variant information for ctors/dtors?
  5445. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  5446. llvm::ConstantAsMetadata::get(GetPointerConstant(
  5447. CGM.getLLVMContext(), D.getDecl()))};
  5448. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  5449. }
  5450. /// For each function which is declared within an extern "C" region and marked
  5451. /// as 'used', but has internal linkage, create an alias from the unmangled
  5452. /// name to the mangled name if possible. People expect to be able to refer
  5453. /// to such functions with an unmangled name from inline assembly within the
  5454. /// same translation unit.
  5455. void CodeGenModule::EmitStaticExternCAliases() {
  5456. if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
  5457. return;
  5458. for (auto &I : StaticExternCValues) {
  5459. IdentifierInfo *Name = I.first;
  5460. llvm::GlobalValue *Val = I.second;
  5461. if (Val && !getModule().getNamedValue(Name->getName()))
  5462. addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  5463. }
  5464. }
  5465. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  5466. GlobalDecl &Result) const {
  5467. auto Res = Manglings.find(MangledName);
  5468. if (Res == Manglings.end())
  5469. return false;
  5470. Result = Res->getValue();
  5471. return true;
  5472. }
  5473. /// Emits metadata nodes associating all the global values in the
  5474. /// current module with the Decls they came from. This is useful for
  5475. /// projects using IR gen as a subroutine.
  5476. ///
  5477. /// Since there's currently no way to associate an MDNode directly
  5478. /// with an llvm::GlobalValue, we create a global named metadata
  5479. /// with the name 'clang.global.decl.ptrs'.
  5480. void CodeGenModule::EmitDeclMetadata() {
  5481. llvm::NamedMDNode *GlobalMetadata = nullptr;
  5482. for (auto &I : MangledDeclNames) {
  5483. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  5484. // Some mangled names don't necessarily have an associated GlobalValue
  5485. // in this module, e.g. if we mangled it for DebugInfo.
  5486. if (Addr)
  5487. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  5488. }
  5489. }
  5490. /// Emits metadata nodes for all the local variables in the current
  5491. /// function.
  5492. void CodeGenFunction::EmitDeclMetadata() {
  5493. if (LocalDeclMap.empty()) return;
  5494. llvm::LLVMContext &Context = getLLVMContext();
  5495. // Find the unique metadata ID for this name.
  5496. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  5497. llvm::NamedMDNode *GlobalMetadata = nullptr;
  5498. for (auto &I : LocalDeclMap) {
  5499. const Decl *D = I.first;
  5500. llvm::Value *Addr = I.second.getPointer();
  5501. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  5502. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  5503. Alloca->setMetadata(
  5504. DeclPtrKind, llvm::MDNode::get(
  5505. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  5506. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  5507. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  5508. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  5509. }
  5510. }
  5511. }
  5512. void CodeGenModule::EmitVersionIdentMetadata() {
  5513. llvm::NamedMDNode *IdentMetadata =
  5514. TheModule.getOrInsertNamedMetadata("llvm.ident");
  5515. std::string Version = getClangFullVersion();
  5516. llvm::LLVMContext &Ctx = TheModule.getContext();
  5517. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  5518. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  5519. }
  5520. void CodeGenModule::EmitCommandLineMetadata() {
  5521. llvm::NamedMDNode *CommandLineMetadata =
  5522. TheModule.getOrInsertNamedMetadata("llvm.commandline");
  5523. std::string CommandLine = getCodeGenOpts().RecordCommandLine;
  5524. llvm::LLVMContext &Ctx = TheModule.getContext();
  5525. llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
  5526. CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
  5527. }
  5528. void CodeGenModule::EmitCoverageFile() {
  5529. if (getCodeGenOpts().CoverageDataFile.empty() &&
  5530. getCodeGenOpts().CoverageNotesFile.empty())
  5531. return;
  5532. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  5533. if (!CUNode)
  5534. return;
  5535. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  5536. llvm::LLVMContext &Ctx = TheModule.getContext();
  5537. auto *CoverageDataFile =
  5538. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  5539. auto *CoverageNotesFile =
  5540. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  5541. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  5542. llvm::MDNode *CU = CUNode->getOperand(i);
  5543. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  5544. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  5545. }
  5546. }
  5547. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  5548. bool ForEH) {
  5549. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  5550. // FIXME: should we even be calling this method if RTTI is disabled
  5551. // and it's not for EH?
  5552. if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
  5553. (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  5554. getTriple().isNVPTX()))
  5555. return llvm::Constant::getNullValue(Int8PtrTy);
  5556. if (ForEH && Ty->isObjCObjectPointerType() &&
  5557. LangOpts.ObjCRuntime.isGNUFamily())
  5558. return ObjCRuntime->GetEHType(Ty);
  5559. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  5560. }
  5561. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  5562. // Do not emit threadprivates in simd-only mode.
  5563. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  5564. return;
  5565. for (auto RefExpr : D->varlists()) {
  5566. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  5567. bool PerformInit =
  5568. VD->getAnyInitializer() &&
  5569. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  5570. /*ForRef=*/false);
  5571. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  5572. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  5573. VD, Addr, RefExpr->getBeginLoc(), PerformInit))
  5574. CXXGlobalInits.push_back(InitFunction);
  5575. }
  5576. }
  5577. llvm::Metadata *
  5578. CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
  5579. StringRef Suffix) {
  5580. if (auto *FnType = T->getAs<FunctionProtoType>())
  5581. T = getContext().getFunctionType(
  5582. FnType->getReturnType(), FnType->getParamTypes(),
  5583. FnType->getExtProtoInfo().withExceptionSpec(EST_None));
  5584. llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
  5585. if (InternalId)
  5586. return InternalId;
  5587. if (isExternallyVisible(T->getLinkage())) {
  5588. std::string OutName;
  5589. llvm::raw_string_ostream Out(OutName);
  5590. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  5591. Out << Suffix;
  5592. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  5593. } else {
  5594. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  5595. llvm::ArrayRef<llvm::Metadata *>());
  5596. }
  5597. return InternalId;
  5598. }
  5599. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  5600. return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
  5601. }
  5602. llvm::Metadata *
  5603. CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
  5604. return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
  5605. }
  5606. // Generalize pointer types to a void pointer with the qualifiers of the
  5607. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  5608. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  5609. // 'void *'.
  5610. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  5611. if (!Ty->isPointerType())
  5612. return Ty;
  5613. return Ctx.getPointerType(
  5614. QualType(Ctx.VoidTy).withCVRQualifiers(
  5615. Ty->getPointeeType().getCVRQualifiers()));
  5616. }
  5617. // Apply type generalization to a FunctionType's return and argument types
  5618. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  5619. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  5620. SmallVector<QualType, 8> GeneralizedParams;
  5621. for (auto &Param : FnType->param_types())
  5622. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  5623. return Ctx.getFunctionType(
  5624. GeneralizeType(Ctx, FnType->getReturnType()),
  5625. GeneralizedParams, FnType->getExtProtoInfo());
  5626. }
  5627. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  5628. return Ctx.getFunctionNoProtoType(
  5629. GeneralizeType(Ctx, FnType->getReturnType()));
  5630. llvm_unreachable("Encountered unknown FunctionType");
  5631. }
  5632. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  5633. return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
  5634. GeneralizedMetadataIdMap, ".generalized");
  5635. }
  5636. /// Returns whether this module needs the "all-vtables" type identifier.
  5637. bool CodeGenModule::NeedAllVtablesTypeId() const {
  5638. // Returns true if at least one of vtable-based CFI checkers is enabled and
  5639. // is not in the trapping mode.
  5640. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  5641. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  5642. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  5643. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  5644. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  5645. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  5646. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  5647. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  5648. }
  5649. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  5650. CharUnits Offset,
  5651. const CXXRecordDecl *RD) {
  5652. llvm::Metadata *MD =
  5653. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  5654. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  5655. if (CodeGenOpts.SanitizeCfiCrossDso)
  5656. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  5657. VTable->addTypeMetadata(Offset.getQuantity(),
  5658. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  5659. if (NeedAllVtablesTypeId()) {
  5660. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  5661. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  5662. }
  5663. }
  5664. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  5665. if (!SanStats)
  5666. SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
  5667. return *SanStats;
  5668. }
  5669. llvm::Value *
  5670. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  5671. CodeGenFunction &CGF) {
  5672. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  5673. auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  5674. auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  5675. auto *Call = CGF.EmitRuntimeCall(
  5676. CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
  5677. return Call;
  5678. }
  5679. CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
  5680. QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
  5681. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  5682. /* forPointeeType= */ true);
  5683. }
  5684. CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
  5685. LValueBaseInfo *BaseInfo,
  5686. TBAAAccessInfo *TBAAInfo,
  5687. bool forPointeeType) {
  5688. if (TBAAInfo)
  5689. *TBAAInfo = getTBAAAccessInfo(T);
  5690. // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
  5691. // that doesn't return the information we need to compute BaseInfo.
  5692. // Honor alignment typedef attributes even on incomplete types.
  5693. // We also honor them straight for C++ class types, even as pointees;
  5694. // there's an expressivity gap here.
  5695. if (auto TT = T->getAs<TypedefType>()) {
  5696. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  5697. if (BaseInfo)
  5698. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  5699. return getContext().toCharUnitsFromBits(Align);
  5700. }
  5701. }
  5702. bool AlignForArray = T->isArrayType();
  5703. // Analyze the base element type, so we don't get confused by incomplete
  5704. // array types.
  5705. T = getContext().getBaseElementType(T);
  5706. if (T->isIncompleteType()) {
  5707. // We could try to replicate the logic from
  5708. // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
  5709. // type is incomplete, so it's impossible to test. We could try to reuse
  5710. // getTypeAlignIfKnown, but that doesn't return the information we need
  5711. // to set BaseInfo. So just ignore the possibility that the alignment is
  5712. // greater than one.
  5713. if (BaseInfo)
  5714. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  5715. return CharUnits::One();
  5716. }
  5717. if (BaseInfo)
  5718. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  5719. CharUnits Alignment;
  5720. const CXXRecordDecl *RD;
  5721. if (T.getQualifiers().hasUnaligned()) {
  5722. Alignment = CharUnits::One();
  5723. } else if (forPointeeType && !AlignForArray &&
  5724. (RD = T->getAsCXXRecordDecl())) {
  5725. // For C++ class pointees, we don't know whether we're pointing at a
  5726. // base or a complete object, so we generally need to use the
  5727. // non-virtual alignment.
  5728. Alignment = getClassPointerAlignment(RD);
  5729. } else {
  5730. Alignment = getContext().getTypeAlignInChars(T);
  5731. }
  5732. // Cap to the global maximum type alignment unless the alignment
  5733. // was somehow explicit on the type.
  5734. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  5735. if (Alignment.getQuantity() > MaxAlign &&
  5736. !getContext().isAlignmentRequired(T))
  5737. Alignment = CharUnits::fromQuantity(MaxAlign);
  5738. }
  5739. return Alignment;
  5740. }
  5741. bool CodeGenModule::stopAutoInit() {
  5742. unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
  5743. if (StopAfter) {
  5744. // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
  5745. // used
  5746. if (NumAutoVarInit >= StopAfter) {
  5747. return true;
  5748. }
  5749. if (!NumAutoVarInit) {
  5750. unsigned DiagID = getDiags().getCustomDiagID(
  5751. DiagnosticsEngine::Warning,
  5752. "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
  5753. "number of times ftrivial-auto-var-init=%1 gets applied.");
  5754. getDiags().Report(DiagID)
  5755. << StopAfter
  5756. << (getContext().getLangOpts().getTrivialAutoVarInit() ==
  5757. LangOptions::TrivialAutoVarInitKind::Zero
  5758. ? "zero"
  5759. : "pattern");
  5760. }
  5761. ++NumAutoVarInit;
  5762. }
  5763. return false;
  5764. }
  5765. void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
  5766. const Decl *D) const {
  5767. StringRef Tag;
  5768. // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
  5769. // postfix beginning with '.' since the symbol name can be demangled.
  5770. if (LangOpts.HIP)
  5771. Tag = (isa<VarDecl>(D) ? ".static." : ".intern.");
  5772. else
  5773. Tag = (isa<VarDecl>(D) ? "__static__" : "__intern__");
  5774. OS << Tag << getContext().getCUIDHash();
  5775. }