CodeGenModule.cpp 208 KB

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