CodeGenModule.cpp 208 KB

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