CodeGenModule.cpp 209 KB

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