CodeGenModule.cpp 220 KB

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