CodeGenModule.cpp 275 KB

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