CGExpr.cpp 217 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503
  1. //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
  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 contains code to emit Expr nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCUDARuntime.h"
  13. #include "CGCXXABI.h"
  14. #include "CGCall.h"
  15. #include "CGCleanup.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGObjCRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CGRecordLayout.h"
  20. #include "CodeGenFunction.h"
  21. #include "CodeGenModule.h"
  22. #include "ConstantEmitter.h"
  23. #include "TargetInfo.h"
  24. #include "clang/AST/ASTContext.h"
  25. #include "clang/AST/Attr.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/NSAPI.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "llvm/ADT/Hashing.h"
  32. #include "llvm/ADT/StringExtras.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/Intrinsics.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/MatrixBuilder.h"
  38. #include "llvm/Support/ConvertUTF.h"
  39. #include "llvm/Support/MathExtras.h"
  40. #include "llvm/Support/Path.h"
  41. #include "llvm/Support/SaveAndRestore.h"
  42. #include "llvm/Transforms/Utils/SanitizerStats.h"
  43. #include <string>
  44. using namespace clang;
  45. using namespace CodeGen;
  46. //===--------------------------------------------------------------------===//
  47. // Miscellaneous Helper Methods
  48. //===--------------------------------------------------------------------===//
  49. llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
  50. unsigned addressSpace =
  51. cast<llvm::PointerType>(value->getType())->getAddressSpace();
  52. llvm::PointerType *destType = Int8PtrTy;
  53. if (addressSpace)
  54. destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
  55. if (value->getType() == destType) return value;
  56. return Builder.CreateBitCast(value, destType);
  57. }
  58. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  59. /// block.
  60. Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
  61. CharUnits Align,
  62. const Twine &Name,
  63. llvm::Value *ArraySize) {
  64. auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
  65. Alloca->setAlignment(Align.getAsAlign());
  66. return Address(Alloca, Ty, Align);
  67. }
  68. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  69. /// block. The alloca is casted to default address space if necessary.
  70. Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
  71. const Twine &Name,
  72. llvm::Value *ArraySize,
  73. Address *AllocaAddr) {
  74. auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
  75. if (AllocaAddr)
  76. *AllocaAddr = Alloca;
  77. llvm::Value *V = Alloca.getPointer();
  78. // Alloca always returns a pointer in alloca address space, which may
  79. // be different from the type defined by the language. For example,
  80. // in C++ the auto variables are in the default address space. Therefore
  81. // cast alloca to the default address space when necessary.
  82. if (getASTAllocaAddressSpace() != LangAS::Default) {
  83. auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
  84. llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
  85. // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
  86. // otherwise alloca is inserted at the current insertion point of the
  87. // builder.
  88. if (!ArraySize)
  89. Builder.SetInsertPoint(getPostAllocaInsertPoint());
  90. V = getTargetHooks().performAddrSpaceCast(
  91. *this, V, getASTAllocaAddressSpace(), LangAS::Default,
  92. Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
  93. }
  94. return Address(V, Ty, Align);
  95. }
  96. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  97. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  98. /// insertion point of the builder.
  99. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
  100. const Twine &Name,
  101. llvm::Value *ArraySize) {
  102. if (ArraySize)
  103. return Builder.CreateAlloca(Ty, ArraySize, Name);
  104. return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
  105. ArraySize, Name, AllocaInsertPt);
  106. }
  107. /// CreateDefaultAlignTempAlloca - This creates an alloca with the
  108. /// default alignment of the corresponding LLVM type, which is *not*
  109. /// guaranteed to be related in any way to the expected alignment of
  110. /// an AST type that might have been lowered to Ty.
  111. Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  112. const Twine &Name) {
  113. CharUnits Align =
  114. CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlignment(Ty));
  115. return CreateTempAlloca(Ty, Align, Name);
  116. }
  117. Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
  118. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  119. return CreateTempAlloca(ConvertType(Ty), Align, Name);
  120. }
  121. Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
  122. Address *Alloca) {
  123. // FIXME: Should we prefer the preferred type alignment here?
  124. return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
  125. }
  126. Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
  127. const Twine &Name, Address *Alloca) {
  128. Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
  129. /*ArraySize=*/nullptr, Alloca);
  130. if (Ty->isConstantMatrixType()) {
  131. auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
  132. auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
  133. ArrayTy->getNumElements());
  134. Result = Address(
  135. Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
  136. VectorTy, Result.getAlignment());
  137. }
  138. return Result;
  139. }
  140. Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
  141. const Twine &Name) {
  142. return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
  143. }
  144. Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
  145. const Twine &Name) {
  146. return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
  147. Name);
  148. }
  149. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  150. /// expression and compare the result against zero, returning an Int1Ty value.
  151. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
  152. PGO.setCurrentStmt(E);
  153. if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
  154. llvm::Value *MemPtr = EmitScalarExpr(E);
  155. return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
  156. }
  157. QualType BoolTy = getContext().BoolTy;
  158. SourceLocation Loc = E->getExprLoc();
  159. CGFPOptionsRAII FPOptsRAII(*this, E);
  160. if (!E->getType()->isAnyComplexType())
  161. return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
  162. return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
  163. Loc);
  164. }
  165. /// EmitIgnoredExpr - Emit code to compute the specified expression,
  166. /// ignoring the result.
  167. void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
  168. if (E->isPRValue())
  169. return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
  170. // Just emit it as an l-value and drop the result.
  171. EmitLValue(E);
  172. }
  173. /// EmitAnyExpr - Emit code to compute the specified expression which
  174. /// can have any type. The result is returned as an RValue struct.
  175. /// If this is an aggregate expression, AggSlot indicates where the
  176. /// result should be returned.
  177. RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
  178. AggValueSlot aggSlot,
  179. bool ignoreResult) {
  180. switch (getEvaluationKind(E->getType())) {
  181. case TEK_Scalar:
  182. return RValue::get(EmitScalarExpr(E, ignoreResult));
  183. case TEK_Complex:
  184. return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
  185. case TEK_Aggregate:
  186. if (!ignoreResult && aggSlot.isIgnored())
  187. aggSlot = CreateAggTemp(E->getType(), "agg-temp");
  188. EmitAggExpr(E, aggSlot);
  189. return aggSlot.asRValue();
  190. }
  191. llvm_unreachable("bad evaluation kind");
  192. }
  193. /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
  194. /// always be accessible even if no aggregate location is provided.
  195. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
  196. AggValueSlot AggSlot = AggValueSlot::ignored();
  197. if (hasAggregateEvaluationKind(E->getType()))
  198. AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
  199. return EmitAnyExpr(E, AggSlot);
  200. }
  201. /// EmitAnyExprToMem - Evaluate an expression into a given memory
  202. /// location.
  203. void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
  204. Address Location,
  205. Qualifiers Quals,
  206. bool IsInit) {
  207. // FIXME: This function should take an LValue as an argument.
  208. switch (getEvaluationKind(E->getType())) {
  209. case TEK_Complex:
  210. EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
  211. /*isInit*/ false);
  212. return;
  213. case TEK_Aggregate: {
  214. EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
  215. AggValueSlot::IsDestructed_t(IsInit),
  216. AggValueSlot::DoesNotNeedGCBarriers,
  217. AggValueSlot::IsAliased_t(!IsInit),
  218. AggValueSlot::MayOverlap));
  219. return;
  220. }
  221. case TEK_Scalar: {
  222. RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
  223. LValue LV = MakeAddrLValue(Location, E->getType());
  224. EmitStoreThroughLValue(RV, LV);
  225. return;
  226. }
  227. }
  228. llvm_unreachable("bad evaluation kind");
  229. }
  230. static void
  231. pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
  232. const Expr *E, Address ReferenceTemporary) {
  233. // Objective-C++ ARC:
  234. // If we are binding a reference to a temporary that has ownership, we
  235. // need to perform retain/release operations on the temporary.
  236. //
  237. // FIXME: This should be looking at E, not M.
  238. if (auto Lifetime = M->getType().getObjCLifetime()) {
  239. switch (Lifetime) {
  240. case Qualifiers::OCL_None:
  241. case Qualifiers::OCL_ExplicitNone:
  242. // Carry on to normal cleanup handling.
  243. break;
  244. case Qualifiers::OCL_Autoreleasing:
  245. // Nothing to do; cleaned up by an autorelease pool.
  246. return;
  247. case Qualifiers::OCL_Strong:
  248. case Qualifiers::OCL_Weak:
  249. switch (StorageDuration Duration = M->getStorageDuration()) {
  250. case SD_Static:
  251. // Note: we intentionally do not register a cleanup to release
  252. // the object on program termination.
  253. return;
  254. case SD_Thread:
  255. // FIXME: We should probably register a cleanup in this case.
  256. return;
  257. case SD_Automatic:
  258. case SD_FullExpression:
  259. CodeGenFunction::Destroyer *Destroy;
  260. CleanupKind CleanupKind;
  261. if (Lifetime == Qualifiers::OCL_Strong) {
  262. const ValueDecl *VD = M->getExtendingDecl();
  263. bool Precise =
  264. VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
  265. CleanupKind = CGF.getARCCleanupKind();
  266. Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
  267. : &CodeGenFunction::destroyARCStrongImprecise;
  268. } else {
  269. // __weak objects always get EH cleanups; otherwise, exceptions
  270. // could cause really nasty crashes instead of mere leaks.
  271. CleanupKind = NormalAndEHCleanup;
  272. Destroy = &CodeGenFunction::destroyARCWeak;
  273. }
  274. if (Duration == SD_FullExpression)
  275. CGF.pushDestroy(CleanupKind, ReferenceTemporary,
  276. M->getType(), *Destroy,
  277. CleanupKind & EHCleanup);
  278. else
  279. CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
  280. M->getType(),
  281. *Destroy, CleanupKind & EHCleanup);
  282. return;
  283. case SD_Dynamic:
  284. llvm_unreachable("temporary cannot have dynamic storage duration");
  285. }
  286. llvm_unreachable("unknown storage duration");
  287. }
  288. }
  289. CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
  290. if (const RecordType *RT =
  291. E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  292. // Get the destructor for the reference temporary.
  293. auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  294. if (!ClassDecl->hasTrivialDestructor())
  295. ReferenceTemporaryDtor = ClassDecl->getDestructor();
  296. }
  297. if (!ReferenceTemporaryDtor)
  298. return;
  299. // Call the destructor for the temporary.
  300. switch (M->getStorageDuration()) {
  301. case SD_Static:
  302. case SD_Thread: {
  303. llvm::FunctionCallee CleanupFn;
  304. llvm::Constant *CleanupArg;
  305. if (E->getType()->isArrayType()) {
  306. CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
  307. ReferenceTemporary, E->getType(),
  308. CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
  309. dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
  310. CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  311. } else {
  312. CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
  313. GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
  314. CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
  315. }
  316. CGF.CGM.getCXXABI().registerGlobalDtor(
  317. CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
  318. break;
  319. }
  320. case SD_FullExpression:
  321. CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
  322. CodeGenFunction::destroyCXXObject,
  323. CGF.getLangOpts().Exceptions);
  324. break;
  325. case SD_Automatic:
  326. CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
  327. ReferenceTemporary, E->getType(),
  328. CodeGenFunction::destroyCXXObject,
  329. CGF.getLangOpts().Exceptions);
  330. break;
  331. case SD_Dynamic:
  332. llvm_unreachable("temporary cannot have dynamic storage duration");
  333. }
  334. }
  335. static Address createReferenceTemporary(CodeGenFunction &CGF,
  336. const MaterializeTemporaryExpr *M,
  337. const Expr *Inner,
  338. Address *Alloca = nullptr) {
  339. auto &TCG = CGF.getTargetHooks();
  340. switch (M->getStorageDuration()) {
  341. case SD_FullExpression:
  342. case SD_Automatic: {
  343. // If we have a constant temporary array or record try to promote it into a
  344. // constant global under the same rules a normal constant would've been
  345. // promoted. This is easier on the optimizer and generally emits fewer
  346. // instructions.
  347. QualType Ty = Inner->getType();
  348. if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
  349. (Ty->isArrayType() || Ty->isRecordType()) &&
  350. CGF.CGM.isTypeConstant(Ty, true))
  351. if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
  352. auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
  353. auto *GV = new llvm::GlobalVariable(
  354. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  355. llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
  356. llvm::GlobalValue::NotThreadLocal,
  357. CGF.getContext().getTargetAddressSpace(AS));
  358. CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
  359. GV->setAlignment(alignment.getAsAlign());
  360. llvm::Constant *C = GV;
  361. if (AS != LangAS::Default)
  362. C = TCG.performAddrSpaceCast(
  363. CGF.CGM, GV, AS, LangAS::Default,
  364. GV->getValueType()->getPointerTo(
  365. CGF.getContext().getTargetAddressSpace(LangAS::Default)));
  366. // FIXME: Should we put the new global into a COMDAT?
  367. return Address(C, alignment);
  368. }
  369. return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
  370. }
  371. case SD_Thread:
  372. case SD_Static:
  373. return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
  374. case SD_Dynamic:
  375. llvm_unreachable("temporary can't have dynamic storage duration");
  376. }
  377. llvm_unreachable("unknown storage duration");
  378. }
  379. /// Helper method to check if the underlying ABI is AAPCS
  380. static bool isAAPCS(const TargetInfo &TargetInfo) {
  381. return TargetInfo.getABI().startswith("aapcs");
  382. }
  383. LValue CodeGenFunction::
  384. EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
  385. const Expr *E = M->getSubExpr();
  386. assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
  387. !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
  388. "Reference should never be pseudo-strong!");
  389. // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
  390. // as that will cause the lifetime adjustment to be lost for ARC
  391. auto ownership = M->getType().getObjCLifetime();
  392. if (ownership != Qualifiers::OCL_None &&
  393. ownership != Qualifiers::OCL_ExplicitNone) {
  394. Address Object = createReferenceTemporary(*this, M, E);
  395. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
  396. Object = Address(llvm::ConstantExpr::getBitCast(Var,
  397. ConvertTypeForMem(E->getType())
  398. ->getPointerTo(Object.getAddressSpace())),
  399. Object.getAlignment());
  400. // createReferenceTemporary will promote the temporary to a global with a
  401. // constant initializer if it can. It can only do this to a value of
  402. // ARC-manageable type if the value is global and therefore "immune" to
  403. // ref-counting operations. Therefore we have no need to emit either a
  404. // dynamic initialization or a cleanup and we can just return the address
  405. // of the temporary.
  406. if (Var->hasInitializer())
  407. return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
  408. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  409. }
  410. LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
  411. AlignmentSource::Decl);
  412. switch (getEvaluationKind(E->getType())) {
  413. default: llvm_unreachable("expected scalar or aggregate expression");
  414. case TEK_Scalar:
  415. EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
  416. break;
  417. case TEK_Aggregate: {
  418. EmitAggExpr(E, AggValueSlot::forAddr(Object,
  419. E->getType().getQualifiers(),
  420. AggValueSlot::IsDestructed,
  421. AggValueSlot::DoesNotNeedGCBarriers,
  422. AggValueSlot::IsNotAliased,
  423. AggValueSlot::DoesNotOverlap));
  424. break;
  425. }
  426. }
  427. pushTemporaryCleanup(*this, M, E, Object);
  428. return RefTempDst;
  429. }
  430. SmallVector<const Expr *, 2> CommaLHSs;
  431. SmallVector<SubobjectAdjustment, 2> Adjustments;
  432. E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  433. for (const auto &Ignored : CommaLHSs)
  434. EmitIgnoredExpr(Ignored);
  435. if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
  436. if (opaque->getType()->isRecordType()) {
  437. assert(Adjustments.empty());
  438. return EmitOpaqueValueLValue(opaque);
  439. }
  440. }
  441. // Create and initialize the reference temporary.
  442. Address Alloca = Address::invalid();
  443. Address Object = createReferenceTemporary(*this, M, E, &Alloca);
  444. if (auto *Var = dyn_cast<llvm::GlobalVariable>(
  445. Object.getPointer()->stripPointerCasts())) {
  446. Object = Address(llvm::ConstantExpr::getBitCast(
  447. cast<llvm::Constant>(Object.getPointer()),
  448. ConvertTypeForMem(E->getType())->getPointerTo()),
  449. Object.getAlignment());
  450. // If the temporary is a global and has a constant initializer or is a
  451. // constant temporary that we promoted to a global, we may have already
  452. // initialized it.
  453. if (!Var->hasInitializer()) {
  454. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  455. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  456. }
  457. } else {
  458. switch (M->getStorageDuration()) {
  459. case SD_Automatic:
  460. if (auto *Size = EmitLifetimeStart(
  461. CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
  462. Alloca.getPointer())) {
  463. pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
  464. Alloca, Size);
  465. }
  466. break;
  467. case SD_FullExpression: {
  468. if (!ShouldEmitLifetimeMarkers)
  469. break;
  470. // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
  471. // marker. Instead, start the lifetime of a conditional temporary earlier
  472. // so that it's unconditional. Don't do this with sanitizers which need
  473. // more precise lifetime marks.
  474. ConditionalEvaluation *OldConditional = nullptr;
  475. CGBuilderTy::InsertPoint OldIP;
  476. if (isInConditionalBranch() && !E->getType().isDestructedType() &&
  477. !SanOpts.has(SanitizerKind::HWAddress) &&
  478. !SanOpts.has(SanitizerKind::Memory) &&
  479. !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
  480. OldConditional = OutermostConditional;
  481. OutermostConditional = nullptr;
  482. OldIP = Builder.saveIP();
  483. llvm::BasicBlock *Block = OldConditional->getStartingBlock();
  484. Builder.restoreIP(CGBuilderTy::InsertPoint(
  485. Block, llvm::BasicBlock::iterator(Block->back())));
  486. }
  487. if (auto *Size = EmitLifetimeStart(
  488. CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
  489. Alloca.getPointer())) {
  490. pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
  491. Size);
  492. }
  493. if (OldConditional) {
  494. OutermostConditional = OldConditional;
  495. Builder.restoreIP(OldIP);
  496. }
  497. break;
  498. }
  499. default:
  500. break;
  501. }
  502. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  503. }
  504. pushTemporaryCleanup(*this, M, E, Object);
  505. // Perform derived-to-base casts and/or field accesses, to get from the
  506. // temporary object we created (and, potentially, for which we extended
  507. // the lifetime) to the subobject we're binding the reference to.
  508. for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
  509. switch (Adjustment.Kind) {
  510. case SubobjectAdjustment::DerivedToBaseAdjustment:
  511. Object =
  512. GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
  513. Adjustment.DerivedToBase.BasePath->path_begin(),
  514. Adjustment.DerivedToBase.BasePath->path_end(),
  515. /*NullCheckValue=*/ false, E->getExprLoc());
  516. break;
  517. case SubobjectAdjustment::FieldAdjustment: {
  518. LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
  519. LV = EmitLValueForField(LV, Adjustment.Field);
  520. assert(LV.isSimple() &&
  521. "materialized temporary field is not a simple lvalue");
  522. Object = LV.getAddress(*this);
  523. break;
  524. }
  525. case SubobjectAdjustment::MemberPointerAdjustment: {
  526. llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
  527. Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
  528. Adjustment.Ptr.MPT);
  529. break;
  530. }
  531. }
  532. }
  533. return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
  534. }
  535. RValue
  536. CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
  537. // Emit the expression as an lvalue.
  538. LValue LV = EmitLValue(E);
  539. assert(LV.isSimple());
  540. llvm::Value *Value = LV.getPointer(*this);
  541. if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
  542. // C++11 [dcl.ref]p5 (as amended by core issue 453):
  543. // If a glvalue to which a reference is directly bound designates neither
  544. // an existing object or function of an appropriate type nor a region of
  545. // storage of suitable size and alignment to contain an object of the
  546. // reference's type, the behavior is undefined.
  547. QualType Ty = E->getType();
  548. EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
  549. }
  550. return RValue::get(Value);
  551. }
  552. /// getAccessedFieldNo - Given an encoded value and a result number, return the
  553. /// input field number being accessed.
  554. unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
  555. const llvm::Constant *Elts) {
  556. return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
  557. ->getZExtValue();
  558. }
  559. /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
  560. static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
  561. llvm::Value *High) {
  562. llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
  563. llvm::Value *K47 = Builder.getInt64(47);
  564. llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
  565. llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
  566. llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
  567. llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
  568. return Builder.CreateMul(B1, KMul);
  569. }
  570. bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
  571. return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
  572. TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
  573. }
  574. bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
  575. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  576. return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
  577. (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
  578. TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
  579. TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
  580. }
  581. bool CodeGenFunction::sanitizePerformTypeCheck() const {
  582. return SanOpts.has(SanitizerKind::Null) ||
  583. SanOpts.has(SanitizerKind::Alignment) ||
  584. SanOpts.has(SanitizerKind::ObjectSize) ||
  585. SanOpts.has(SanitizerKind::Vptr);
  586. }
  587. void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
  588. llvm::Value *Ptr, QualType Ty,
  589. CharUnits Alignment,
  590. SanitizerSet SkippedChecks,
  591. llvm::Value *ArraySize) {
  592. if (!sanitizePerformTypeCheck())
  593. return;
  594. // Don't check pointers outside the default address space. The null check
  595. // isn't correct, the object-size check isn't supported by LLVM, and we can't
  596. // communicate the addresses to the runtime handler for the vptr check.
  597. if (Ptr->getType()->getPointerAddressSpace())
  598. return;
  599. // Don't check pointers to volatile data. The behavior here is implementation-
  600. // defined.
  601. if (Ty.isVolatileQualified())
  602. return;
  603. SanitizerScope SanScope(this);
  604. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
  605. llvm::BasicBlock *Done = nullptr;
  606. // Quickly determine whether we have a pointer to an alloca. It's possible
  607. // to skip null checks, and some alignment checks, for these pointers. This
  608. // can reduce compile-time significantly.
  609. auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
  610. llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
  611. llvm::Value *IsNonNull = nullptr;
  612. bool IsGuaranteedNonNull =
  613. SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
  614. bool AllowNullPointers = isNullPointerAllowed(TCK);
  615. if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
  616. !IsGuaranteedNonNull) {
  617. // The glvalue must not be an empty glvalue.
  618. IsNonNull = Builder.CreateIsNotNull(Ptr);
  619. // The IR builder can constant-fold the null check if the pointer points to
  620. // a constant.
  621. IsGuaranteedNonNull = IsNonNull == True;
  622. // Skip the null check if the pointer is known to be non-null.
  623. if (!IsGuaranteedNonNull) {
  624. if (AllowNullPointers) {
  625. // When performing pointer casts, it's OK if the value is null.
  626. // Skip the remaining checks in that case.
  627. Done = createBasicBlock("null");
  628. llvm::BasicBlock *Rest = createBasicBlock("not.null");
  629. Builder.CreateCondBr(IsNonNull, Rest, Done);
  630. EmitBlock(Rest);
  631. } else {
  632. Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
  633. }
  634. }
  635. }
  636. if (SanOpts.has(SanitizerKind::ObjectSize) &&
  637. !SkippedChecks.has(SanitizerKind::ObjectSize) &&
  638. !Ty->isIncompleteType()) {
  639. uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
  640. llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
  641. if (ArraySize)
  642. Size = Builder.CreateMul(Size, ArraySize);
  643. // Degenerate case: new X[0] does not need an objectsize check.
  644. llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
  645. if (!ConstantSize || !ConstantSize->isNullValue()) {
  646. // The glvalue must refer to a large enough storage region.
  647. // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
  648. // to check this.
  649. // FIXME: Get object address space
  650. llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
  651. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
  652. llvm::Value *Min = Builder.getFalse();
  653. llvm::Value *NullIsUnknown = Builder.getFalse();
  654. llvm::Value *Dynamic = Builder.getFalse();
  655. llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
  656. llvm::Value *LargeEnough = Builder.CreateICmpUGE(
  657. Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
  658. Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
  659. }
  660. }
  661. uint64_t AlignVal = 0;
  662. llvm::Value *PtrAsInt = nullptr;
  663. if (SanOpts.has(SanitizerKind::Alignment) &&
  664. !SkippedChecks.has(SanitizerKind::Alignment)) {
  665. AlignVal = Alignment.getQuantity();
  666. if (!Ty->isIncompleteType() && !AlignVal)
  667. AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
  668. /*ForPointeeType=*/true)
  669. .getQuantity();
  670. // The glvalue must be suitably aligned.
  671. if (AlignVal > 1 &&
  672. (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
  673. PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
  674. llvm::Value *Align = Builder.CreateAnd(
  675. PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
  676. llvm::Value *Aligned =
  677. Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
  678. if (Aligned != True)
  679. Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
  680. }
  681. }
  682. if (Checks.size() > 0) {
  683. // Make sure we're not losing information. Alignment needs to be a power of
  684. // 2
  685. assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
  686. llvm::Constant *StaticData[] = {
  687. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
  688. llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
  689. llvm::ConstantInt::get(Int8Ty, TCK)};
  690. EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
  691. PtrAsInt ? PtrAsInt : Ptr);
  692. }
  693. // If possible, check that the vptr indicates that there is a subobject of
  694. // type Ty at offset zero within this object.
  695. //
  696. // C++11 [basic.life]p5,6:
  697. // [For storage which does not refer to an object within its lifetime]
  698. // The program has undefined behavior if:
  699. // -- the [pointer or glvalue] is used to access a non-static data member
  700. // or call a non-static member function
  701. if (SanOpts.has(SanitizerKind::Vptr) &&
  702. !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
  703. // Ensure that the pointer is non-null before loading it. If there is no
  704. // compile-time guarantee, reuse the run-time null check or emit a new one.
  705. if (!IsGuaranteedNonNull) {
  706. if (!IsNonNull)
  707. IsNonNull = Builder.CreateIsNotNull(Ptr);
  708. if (!Done)
  709. Done = createBasicBlock("vptr.null");
  710. llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
  711. Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
  712. EmitBlock(VptrNotNull);
  713. }
  714. // Compute a hash of the mangled name of the type.
  715. //
  716. // FIXME: This is not guaranteed to be deterministic! Move to a
  717. // fingerprinting mechanism once LLVM provides one. For the time
  718. // being the implementation happens to be deterministic.
  719. SmallString<64> MangledName;
  720. llvm::raw_svector_ostream Out(MangledName);
  721. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
  722. Out);
  723. // Contained in NoSanitizeList based on the mangled type.
  724. if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
  725. Out.str())) {
  726. llvm::hash_code TypeHash = hash_value(Out.str());
  727. // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
  728. llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
  729. llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
  730. Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
  731. llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
  732. llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
  733. llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
  734. Hash = Builder.CreateTrunc(Hash, IntPtrTy);
  735. // Look the hash up in our cache.
  736. const int CacheSize = 128;
  737. llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
  738. llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
  739. "__ubsan_vptr_type_cache");
  740. llvm::Value *Slot = Builder.CreateAnd(Hash,
  741. llvm::ConstantInt::get(IntPtrTy,
  742. CacheSize-1));
  743. llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
  744. llvm::Value *CacheVal = Builder.CreateAlignedLoad(
  745. IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
  746. getPointerAlign());
  747. // If the hash isn't in the cache, call a runtime handler to perform the
  748. // hard work of checking whether the vptr is for an object of the right
  749. // type. This will either fill in the cache and return, or produce a
  750. // diagnostic.
  751. llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
  752. llvm::Constant *StaticData[] = {
  753. EmitCheckSourceLocation(Loc),
  754. EmitCheckTypeDescriptor(Ty),
  755. CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
  756. llvm::ConstantInt::get(Int8Ty, TCK)
  757. };
  758. llvm::Value *DynamicData[] = { Ptr, Hash };
  759. EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
  760. SanitizerHandler::DynamicTypeCacheMiss, StaticData,
  761. DynamicData);
  762. }
  763. }
  764. if (Done) {
  765. Builder.CreateBr(Done);
  766. EmitBlock(Done);
  767. }
  768. }
  769. /// Determine whether this expression refers to a flexible array member in a
  770. /// struct. We disable array bounds checks for such members.
  771. static bool isFlexibleArrayMemberExpr(const Expr *E) {
  772. // For compatibility with existing code, we treat arrays of length 0 or
  773. // 1 as flexible array members.
  774. // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
  775. // the two mechanisms.
  776. const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
  777. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  778. // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
  779. // was produced by macro expansion.
  780. if (CAT->getSize().ugt(1))
  781. return false;
  782. } else if (!isa<IncompleteArrayType>(AT))
  783. return false;
  784. E = E->IgnoreParens();
  785. // A flexible array member must be the last member in the class.
  786. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  787. // FIXME: If the base type of the member expr is not FD->getParent(),
  788. // this should not be treated as a flexible array member access.
  789. if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  790. // FIXME: Sema doesn't treat a T[1] union member as a flexible array
  791. // member, only a T[0] or T[] member gets that treatment.
  792. if (FD->getParent()->isUnion())
  793. return true;
  794. RecordDecl::field_iterator FI(
  795. DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
  796. return ++FI == FD->getParent()->field_end();
  797. }
  798. } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
  799. return IRE->getDecl()->getNextIvar() == nullptr;
  800. }
  801. return false;
  802. }
  803. llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
  804. QualType EltTy) {
  805. ASTContext &C = getContext();
  806. uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
  807. if (!EltSize)
  808. return nullptr;
  809. auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  810. if (!ArrayDeclRef)
  811. return nullptr;
  812. auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
  813. if (!ParamDecl)
  814. return nullptr;
  815. auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
  816. if (!POSAttr)
  817. return nullptr;
  818. // Don't load the size if it's a lower bound.
  819. int POSType = POSAttr->getType();
  820. if (POSType != 0 && POSType != 1)
  821. return nullptr;
  822. // Find the implicit size parameter.
  823. auto PassedSizeIt = SizeArguments.find(ParamDecl);
  824. if (PassedSizeIt == SizeArguments.end())
  825. return nullptr;
  826. const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
  827. assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
  828. Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
  829. llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
  830. C.getSizeType(), E->getExprLoc());
  831. llvm::Value *SizeOfElement =
  832. llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
  833. return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
  834. }
  835. /// If Base is known to point to the start of an array, return the length of
  836. /// that array. Return 0 if the length cannot be determined.
  837. static llvm::Value *getArrayIndexingBound(
  838. CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
  839. // For the vector indexing extension, the bound is the number of elements.
  840. if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
  841. IndexedType = Base->getType();
  842. return CGF.Builder.getInt32(VT->getNumElements());
  843. }
  844. Base = Base->IgnoreParens();
  845. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  846. if (CE->getCastKind() == CK_ArrayToPointerDecay &&
  847. !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
  848. IndexedType = CE->getSubExpr()->getType();
  849. const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
  850. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  851. return CGF.Builder.getInt(CAT->getSize());
  852. else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
  853. return CGF.getVLASize(VAT).NumElts;
  854. // Ignore pass_object_size here. It's not applicable on decayed pointers.
  855. }
  856. }
  857. QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
  858. if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
  859. IndexedType = Base->getType();
  860. return POS;
  861. }
  862. return nullptr;
  863. }
  864. void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
  865. llvm::Value *Index, QualType IndexType,
  866. bool Accessed) {
  867. assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
  868. "should not be called unless adding bounds checks");
  869. SanitizerScope SanScope(this);
  870. QualType IndexedType;
  871. llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
  872. if (!Bound)
  873. return;
  874. bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
  875. llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
  876. llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
  877. llvm::Constant *StaticData[] = {
  878. EmitCheckSourceLocation(E->getExprLoc()),
  879. EmitCheckTypeDescriptor(IndexedType),
  880. EmitCheckTypeDescriptor(IndexType)
  881. };
  882. llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
  883. : Builder.CreateICmpULE(IndexVal, BoundVal);
  884. EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
  885. SanitizerHandler::OutOfBounds, StaticData, Index);
  886. }
  887. CodeGenFunction::ComplexPairTy CodeGenFunction::
  888. EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  889. bool isInc, bool isPre) {
  890. ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
  891. llvm::Value *NextVal;
  892. if (isa<llvm::IntegerType>(InVal.first->getType())) {
  893. uint64_t AmountVal = isInc ? 1 : -1;
  894. NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
  895. // Add the inc/dec to the real part.
  896. NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  897. } else {
  898. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  899. llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
  900. if (!isInc)
  901. FVal.changeSign();
  902. NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
  903. // Add the inc/dec to the real part.
  904. NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  905. }
  906. ComplexPairTy IncVal(NextVal, InVal.second);
  907. // Store the updated result through the lvalue.
  908. EmitStoreOfComplex(IncVal, LV, /*init*/ false);
  909. if (getLangOpts().OpenMP)
  910. CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
  911. E->getSubExpr());
  912. // If this is a postinc, return the value read from memory, otherwise use the
  913. // updated value.
  914. return isPre ? IncVal : InVal;
  915. }
  916. void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
  917. CodeGenFunction *CGF) {
  918. // Bind VLAs in the cast type.
  919. if (CGF && E->getType()->isVariablyModifiedType())
  920. CGF->EmitVariablyModifiedType(E->getType());
  921. if (CGDebugInfo *DI = getModuleDebugInfo())
  922. DI->EmitExplicitCastType(E->getType());
  923. }
  924. //===----------------------------------------------------------------------===//
  925. // LValue Expression Emission
  926. //===----------------------------------------------------------------------===//
  927. /// EmitPointerWithAlignment - Given an expression of pointer type, try to
  928. /// derive a more accurate bound on the alignment of the pointer.
  929. Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
  930. LValueBaseInfo *BaseInfo,
  931. TBAAAccessInfo *TBAAInfo) {
  932. // We allow this with ObjC object pointers because of fragile ABIs.
  933. assert(E->getType()->isPointerType() ||
  934. E->getType()->isObjCObjectPointerType());
  935. E = E->IgnoreParens();
  936. // Casts:
  937. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  938. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
  939. CGM.EmitExplicitCastExprType(ECE, this);
  940. switch (CE->getCastKind()) {
  941. // Non-converting casts (but not C's implicit conversion from void*).
  942. case CK_BitCast:
  943. case CK_NoOp:
  944. case CK_AddressSpaceConversion:
  945. if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
  946. if (PtrTy->getPointeeType()->isVoidType())
  947. break;
  948. LValueBaseInfo InnerBaseInfo;
  949. TBAAAccessInfo InnerTBAAInfo;
  950. Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
  951. &InnerBaseInfo,
  952. &InnerTBAAInfo);
  953. if (BaseInfo) *BaseInfo = InnerBaseInfo;
  954. if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
  955. if (isa<ExplicitCastExpr>(CE)) {
  956. LValueBaseInfo TargetTypeBaseInfo;
  957. TBAAAccessInfo TargetTypeTBAAInfo;
  958. CharUnits Align = CGM.getNaturalPointeeTypeAlignment(
  959. E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
  960. if (TBAAInfo)
  961. *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
  962. TargetTypeTBAAInfo);
  963. // If the source l-value is opaque, honor the alignment of the
  964. // casted-to type.
  965. if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
  966. if (BaseInfo)
  967. BaseInfo->mergeForCast(TargetTypeBaseInfo);
  968. Addr = Address(Addr.getPointer(), Addr.getElementType(), Align);
  969. }
  970. }
  971. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
  972. CE->getCastKind() == CK_BitCast) {
  973. if (auto PT = E->getType()->getAs<PointerType>())
  974. EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
  975. /*MayBeNull=*/true,
  976. CodeGenFunction::CFITCK_UnrelatedCast,
  977. CE->getBeginLoc());
  978. }
  979. if (CE->getCastKind() == CK_AddressSpaceConversion)
  980. return Builder.CreateAddrSpaceCast(Addr, ConvertType(E->getType()));
  981. llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
  982. return Builder.CreateElementBitCast(Addr, ElemTy);
  983. }
  984. break;
  985. // Array-to-pointer decay.
  986. case CK_ArrayToPointerDecay:
  987. return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
  988. // Derived-to-base conversions.
  989. case CK_UncheckedDerivedToBase:
  990. case CK_DerivedToBase: {
  991. // TODO: Support accesses to members of base classes in TBAA. For now, we
  992. // conservatively pretend that the complete object is of the base class
  993. // type.
  994. if (TBAAInfo)
  995. *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
  996. Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
  997. auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
  998. return GetAddressOfBaseClass(Addr, Derived,
  999. CE->path_begin(), CE->path_end(),
  1000. ShouldNullCheckClassCastValue(CE),
  1001. CE->getExprLoc());
  1002. }
  1003. // TODO: Is there any reason to treat base-to-derived conversions
  1004. // specially?
  1005. default:
  1006. break;
  1007. }
  1008. }
  1009. // Unary &.
  1010. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1011. if (UO->getOpcode() == UO_AddrOf) {
  1012. LValue LV = EmitLValue(UO->getSubExpr());
  1013. if (BaseInfo) *BaseInfo = LV.getBaseInfo();
  1014. if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
  1015. return LV.getAddress(*this);
  1016. }
  1017. }
  1018. // TODO: conditional operators, comma.
  1019. // Otherwise, use the alignment of the type.
  1020. CharUnits Align =
  1021. CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
  1022. llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
  1023. return Address(EmitScalarExpr(E), ElemTy, Align);
  1024. }
  1025. llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
  1026. llvm::Value *V = RV.getScalarVal();
  1027. if (auto MPT = T->getAs<MemberPointerType>())
  1028. return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
  1029. return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
  1030. }
  1031. RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
  1032. if (Ty->isVoidType())
  1033. return RValue::get(nullptr);
  1034. switch (getEvaluationKind(Ty)) {
  1035. case TEK_Complex: {
  1036. llvm::Type *EltTy =
  1037. ConvertType(Ty->castAs<ComplexType>()->getElementType());
  1038. llvm::Value *U = llvm::UndefValue::get(EltTy);
  1039. return RValue::getComplex(std::make_pair(U, U));
  1040. }
  1041. // If this is a use of an undefined aggregate type, the aggregate must have an
  1042. // identifiable address. Just because the contents of the value are undefined
  1043. // doesn't mean that the address can't be taken and compared.
  1044. case TEK_Aggregate: {
  1045. Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
  1046. return RValue::getAggregate(DestPtr);
  1047. }
  1048. case TEK_Scalar:
  1049. return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
  1050. }
  1051. llvm_unreachable("bad evaluation kind");
  1052. }
  1053. RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
  1054. const char *Name) {
  1055. ErrorUnsupported(E, Name);
  1056. return GetUndefRValue(E->getType());
  1057. }
  1058. LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
  1059. const char *Name) {
  1060. ErrorUnsupported(E, Name);
  1061. llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
  1062. return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
  1063. E->getType());
  1064. }
  1065. bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
  1066. const Expr *Base = Obj;
  1067. while (!isa<CXXThisExpr>(Base)) {
  1068. // The result of a dynamic_cast can be null.
  1069. if (isa<CXXDynamicCastExpr>(Base))
  1070. return false;
  1071. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  1072. Base = CE->getSubExpr();
  1073. } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
  1074. Base = PE->getSubExpr();
  1075. } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
  1076. if (UO->getOpcode() == UO_Extension)
  1077. Base = UO->getSubExpr();
  1078. else
  1079. return false;
  1080. } else {
  1081. return false;
  1082. }
  1083. }
  1084. return true;
  1085. }
  1086. LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
  1087. LValue LV;
  1088. if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
  1089. LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
  1090. else
  1091. LV = EmitLValue(E);
  1092. if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
  1093. SanitizerSet SkippedChecks;
  1094. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  1095. bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
  1096. if (IsBaseCXXThis)
  1097. SkippedChecks.set(SanitizerKind::Alignment, true);
  1098. if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
  1099. SkippedChecks.set(SanitizerKind::Null, true);
  1100. }
  1101. EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
  1102. LV.getAlignment(), SkippedChecks);
  1103. }
  1104. return LV;
  1105. }
  1106. /// EmitLValue - Emit code to compute a designator that specifies the location
  1107. /// of the expression.
  1108. ///
  1109. /// This can return one of two things: a simple address or a bitfield reference.
  1110. /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
  1111. /// an LLVM pointer type.
  1112. ///
  1113. /// If this returns a bitfield reference, nothing about the pointee type of the
  1114. /// LLVM value is known: For example, it may not be a pointer to an integer.
  1115. ///
  1116. /// If this returns a normal address, and if the lvalue's C type is fixed size,
  1117. /// this method guarantees that the returned pointer type will point to an LLVM
  1118. /// type of the same size of the lvalue's type. If the lvalue has a variable
  1119. /// length type, this is not possible.
  1120. ///
  1121. LValue CodeGenFunction::EmitLValue(const Expr *E) {
  1122. ApplyDebugLocation DL(*this, E);
  1123. switch (E->getStmtClass()) {
  1124. default: return EmitUnsupportedLValue(E, "l-value expression");
  1125. case Expr::ObjCPropertyRefExprClass:
  1126. llvm_unreachable("cannot emit a property reference directly");
  1127. case Expr::ObjCSelectorExprClass:
  1128. return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
  1129. case Expr::ObjCIsaExprClass:
  1130. return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
  1131. case Expr::BinaryOperatorClass:
  1132. return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
  1133. case Expr::CompoundAssignOperatorClass: {
  1134. QualType Ty = E->getType();
  1135. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  1136. Ty = AT->getValueType();
  1137. if (!Ty->isAnyComplexType())
  1138. return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  1139. return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  1140. }
  1141. case Expr::CallExprClass:
  1142. case Expr::CXXMemberCallExprClass:
  1143. case Expr::CXXOperatorCallExprClass:
  1144. case Expr::UserDefinedLiteralClass:
  1145. return EmitCallExprLValue(cast<CallExpr>(E));
  1146. case Expr::CXXRewrittenBinaryOperatorClass:
  1147. return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
  1148. case Expr::VAArgExprClass:
  1149. return EmitVAArgExprLValue(cast<VAArgExpr>(E));
  1150. case Expr::DeclRefExprClass:
  1151. return EmitDeclRefLValue(cast<DeclRefExpr>(E));
  1152. case Expr::ConstantExprClass: {
  1153. const ConstantExpr *CE = cast<ConstantExpr>(E);
  1154. if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
  1155. QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
  1156. ->getCallReturnType(getContext())
  1157. ->getPointeeType();
  1158. return MakeNaturalAlignAddrLValue(Result, RetType);
  1159. }
  1160. return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
  1161. }
  1162. case Expr::ParenExprClass:
  1163. return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
  1164. case Expr::GenericSelectionExprClass:
  1165. return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
  1166. case Expr::PredefinedExprClass:
  1167. return EmitPredefinedLValue(cast<PredefinedExpr>(E));
  1168. case Expr::StringLiteralClass:
  1169. return EmitStringLiteralLValue(cast<StringLiteral>(E));
  1170. case Expr::ObjCEncodeExprClass:
  1171. return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
  1172. case Expr::PseudoObjectExprClass:
  1173. return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
  1174. case Expr::InitListExprClass:
  1175. return EmitInitListLValue(cast<InitListExpr>(E));
  1176. case Expr::CXXTemporaryObjectExprClass:
  1177. case Expr::CXXConstructExprClass:
  1178. return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
  1179. case Expr::CXXBindTemporaryExprClass:
  1180. return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
  1181. case Expr::CXXUuidofExprClass:
  1182. return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
  1183. case Expr::LambdaExprClass:
  1184. return EmitAggExprToLValue(E);
  1185. case Expr::ExprWithCleanupsClass: {
  1186. const auto *cleanups = cast<ExprWithCleanups>(E);
  1187. RunCleanupsScope Scope(*this);
  1188. LValue LV = EmitLValue(cleanups->getSubExpr());
  1189. if (LV.isSimple()) {
  1190. // Defend against branches out of gnu statement expressions surrounded by
  1191. // cleanups.
  1192. Address Addr = LV.getAddress(*this);
  1193. llvm::Value *V = Addr.getPointer();
  1194. Scope.ForceCleanup({&V});
  1195. return LValue::MakeAddr(Addr.withPointer(V), LV.getType(), getContext(),
  1196. LV.getBaseInfo(), LV.getTBAAInfo());
  1197. }
  1198. // FIXME: Is it possible to create an ExprWithCleanups that produces a
  1199. // bitfield lvalue or some other non-simple lvalue?
  1200. return LV;
  1201. }
  1202. case Expr::CXXDefaultArgExprClass: {
  1203. auto *DAE = cast<CXXDefaultArgExpr>(E);
  1204. CXXDefaultArgExprScope Scope(*this, DAE);
  1205. return EmitLValue(DAE->getExpr());
  1206. }
  1207. case Expr::CXXDefaultInitExprClass: {
  1208. auto *DIE = cast<CXXDefaultInitExpr>(E);
  1209. CXXDefaultInitExprScope Scope(*this, DIE);
  1210. return EmitLValue(DIE->getExpr());
  1211. }
  1212. case Expr::CXXTypeidExprClass:
  1213. return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
  1214. case Expr::ObjCMessageExprClass:
  1215. return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
  1216. case Expr::ObjCIvarRefExprClass:
  1217. return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
  1218. case Expr::StmtExprClass:
  1219. return EmitStmtExprLValue(cast<StmtExpr>(E));
  1220. case Expr::UnaryOperatorClass:
  1221. return EmitUnaryOpLValue(cast<UnaryOperator>(E));
  1222. case Expr::ArraySubscriptExprClass:
  1223. return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
  1224. case Expr::MatrixSubscriptExprClass:
  1225. return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
  1226. case Expr::OMPArraySectionExprClass:
  1227. return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
  1228. case Expr::ExtVectorElementExprClass:
  1229. return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
  1230. case Expr::MemberExprClass:
  1231. return EmitMemberExpr(cast<MemberExpr>(E));
  1232. case Expr::CompoundLiteralExprClass:
  1233. return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
  1234. case Expr::ConditionalOperatorClass:
  1235. return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
  1236. case Expr::BinaryConditionalOperatorClass:
  1237. return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
  1238. case Expr::ChooseExprClass:
  1239. return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
  1240. case Expr::OpaqueValueExprClass:
  1241. return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
  1242. case Expr::SubstNonTypeTemplateParmExprClass:
  1243. return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
  1244. case Expr::ImplicitCastExprClass:
  1245. case Expr::CStyleCastExprClass:
  1246. case Expr::CXXFunctionalCastExprClass:
  1247. case Expr::CXXStaticCastExprClass:
  1248. case Expr::CXXDynamicCastExprClass:
  1249. case Expr::CXXReinterpretCastExprClass:
  1250. case Expr::CXXConstCastExprClass:
  1251. case Expr::CXXAddrspaceCastExprClass:
  1252. case Expr::ObjCBridgedCastExprClass:
  1253. return EmitCastLValue(cast<CastExpr>(E));
  1254. case Expr::MaterializeTemporaryExprClass:
  1255. return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
  1256. case Expr::CoawaitExprClass:
  1257. return EmitCoawaitLValue(cast<CoawaitExpr>(E));
  1258. case Expr::CoyieldExprClass:
  1259. return EmitCoyieldLValue(cast<CoyieldExpr>(E));
  1260. }
  1261. }
  1262. /// Given an object of the given canonical type, can we safely copy a
  1263. /// value out of it based on its initializer?
  1264. static bool isConstantEmittableObjectType(QualType type) {
  1265. assert(type.isCanonical());
  1266. assert(!type->isReferenceType());
  1267. // Must be const-qualified but non-volatile.
  1268. Qualifiers qs = type.getLocalQualifiers();
  1269. if (!qs.hasConst() || qs.hasVolatile()) return false;
  1270. // Otherwise, all object types satisfy this except C++ classes with
  1271. // mutable subobjects or non-trivial copy/destroy behavior.
  1272. if (const auto *RT = dyn_cast<RecordType>(type))
  1273. if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1274. if (RD->hasMutableFields() || !RD->isTrivial())
  1275. return false;
  1276. return true;
  1277. }
  1278. /// Can we constant-emit a load of a reference to a variable of the
  1279. /// given type? This is different from predicates like
  1280. /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
  1281. /// in situations that don't necessarily satisfy the language's rules
  1282. /// for this (e.g. C++'s ODR-use rules). For example, we want to able
  1283. /// to do this with const float variables even if those variables
  1284. /// aren't marked 'constexpr'.
  1285. enum ConstantEmissionKind {
  1286. CEK_None,
  1287. CEK_AsReferenceOnly,
  1288. CEK_AsValueOrReference,
  1289. CEK_AsValueOnly
  1290. };
  1291. static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
  1292. type = type.getCanonicalType();
  1293. if (const auto *ref = dyn_cast<ReferenceType>(type)) {
  1294. if (isConstantEmittableObjectType(ref->getPointeeType()))
  1295. return CEK_AsValueOrReference;
  1296. return CEK_AsReferenceOnly;
  1297. }
  1298. if (isConstantEmittableObjectType(type))
  1299. return CEK_AsValueOnly;
  1300. return CEK_None;
  1301. }
  1302. /// Try to emit a reference to the given value without producing it as
  1303. /// an l-value. This is just an optimization, but it avoids us needing
  1304. /// to emit global copies of variables if they're named without triggering
  1305. /// a formal use in a context where we can't emit a direct reference to them,
  1306. /// for instance if a block or lambda or a member of a local class uses a
  1307. /// const int variable or constexpr variable from an enclosing function.
  1308. CodeGenFunction::ConstantEmission
  1309. CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
  1310. ValueDecl *value = refExpr->getDecl();
  1311. // The value needs to be an enum constant or a constant variable.
  1312. ConstantEmissionKind CEK;
  1313. if (isa<ParmVarDecl>(value)) {
  1314. CEK = CEK_None;
  1315. } else if (auto *var = dyn_cast<VarDecl>(value)) {
  1316. CEK = checkVarTypeForConstantEmission(var->getType());
  1317. } else if (isa<EnumConstantDecl>(value)) {
  1318. CEK = CEK_AsValueOnly;
  1319. } else {
  1320. CEK = CEK_None;
  1321. }
  1322. if (CEK == CEK_None) return ConstantEmission();
  1323. Expr::EvalResult result;
  1324. bool resultIsReference;
  1325. QualType resultType;
  1326. // It's best to evaluate all the way as an r-value if that's permitted.
  1327. if (CEK != CEK_AsReferenceOnly &&
  1328. refExpr->EvaluateAsRValue(result, getContext())) {
  1329. resultIsReference = false;
  1330. resultType = refExpr->getType();
  1331. // Otherwise, try to evaluate as an l-value.
  1332. } else if (CEK != CEK_AsValueOnly &&
  1333. refExpr->EvaluateAsLValue(result, getContext())) {
  1334. resultIsReference = true;
  1335. resultType = value->getType();
  1336. // Failure.
  1337. } else {
  1338. return ConstantEmission();
  1339. }
  1340. // In any case, if the initializer has side-effects, abandon ship.
  1341. if (result.HasSideEffects)
  1342. return ConstantEmission();
  1343. // In CUDA/HIP device compilation, a lambda may capture a reference variable
  1344. // referencing a global host variable by copy. In this case the lambda should
  1345. // make a copy of the value of the global host variable. The DRE of the
  1346. // captured reference variable cannot be emitted as load from the host
  1347. // global variable as compile time constant, since the host variable is not
  1348. // accessible on device. The DRE of the captured reference variable has to be
  1349. // loaded from captures.
  1350. if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
  1351. refExpr->refersToEnclosingVariableOrCapture()) {
  1352. auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
  1353. if (MD && MD->getParent()->isLambda() &&
  1354. MD->getOverloadedOperator() == OO_Call) {
  1355. const APValue::LValueBase &base = result.Val.getLValueBase();
  1356. if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
  1357. if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
  1358. if (!VD->hasAttr<CUDADeviceAttr>()) {
  1359. return ConstantEmission();
  1360. }
  1361. }
  1362. }
  1363. }
  1364. }
  1365. // Emit as a constant.
  1366. auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
  1367. result.Val, resultType);
  1368. // Make sure we emit a debug reference to the global variable.
  1369. // This should probably fire even for
  1370. if (isa<VarDecl>(value)) {
  1371. if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
  1372. EmitDeclRefExprDbgValue(refExpr, result.Val);
  1373. } else {
  1374. assert(isa<EnumConstantDecl>(value));
  1375. EmitDeclRefExprDbgValue(refExpr, result.Val);
  1376. }
  1377. // If we emitted a reference constant, we need to dereference that.
  1378. if (resultIsReference)
  1379. return ConstantEmission::forReference(C);
  1380. return ConstantEmission::forValue(C);
  1381. }
  1382. static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
  1383. const MemberExpr *ME) {
  1384. if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
  1385. // Try to emit static variable member expressions as DREs.
  1386. return DeclRefExpr::Create(
  1387. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
  1388. /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
  1389. ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
  1390. }
  1391. return nullptr;
  1392. }
  1393. CodeGenFunction::ConstantEmission
  1394. CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
  1395. if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
  1396. return tryEmitAsConstant(DRE);
  1397. return ConstantEmission();
  1398. }
  1399. llvm::Value *CodeGenFunction::emitScalarConstant(
  1400. const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
  1401. assert(Constant && "not a constant");
  1402. if (Constant.isReference())
  1403. return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
  1404. E->getExprLoc())
  1405. .getScalarVal();
  1406. return Constant.getValue();
  1407. }
  1408. llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
  1409. SourceLocation Loc) {
  1410. return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
  1411. lvalue.getType(), Loc, lvalue.getBaseInfo(),
  1412. lvalue.getTBAAInfo(), lvalue.isNontemporal());
  1413. }
  1414. static bool hasBooleanRepresentation(QualType Ty) {
  1415. if (Ty->isBooleanType())
  1416. return true;
  1417. if (const EnumType *ET = Ty->getAs<EnumType>())
  1418. return ET->getDecl()->getIntegerType()->isBooleanType();
  1419. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  1420. return hasBooleanRepresentation(AT->getValueType());
  1421. return false;
  1422. }
  1423. static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
  1424. llvm::APInt &Min, llvm::APInt &End,
  1425. bool StrictEnums, bool IsBool) {
  1426. const EnumType *ET = Ty->getAs<EnumType>();
  1427. bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
  1428. ET && !ET->getDecl()->isFixed();
  1429. if (!IsBool && !IsRegularCPlusPlusEnum)
  1430. return false;
  1431. if (IsBool) {
  1432. Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
  1433. End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
  1434. } else {
  1435. const EnumDecl *ED = ET->getDecl();
  1436. llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
  1437. unsigned Bitwidth = LTy->getScalarSizeInBits();
  1438. unsigned NumNegativeBits = ED->getNumNegativeBits();
  1439. unsigned NumPositiveBits = ED->getNumPositiveBits();
  1440. if (NumNegativeBits) {
  1441. unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
  1442. assert(NumBits <= Bitwidth);
  1443. End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
  1444. Min = -End;
  1445. } else {
  1446. assert(NumPositiveBits <= Bitwidth);
  1447. End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
  1448. Min = llvm::APInt::getZero(Bitwidth);
  1449. }
  1450. }
  1451. return true;
  1452. }
  1453. llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
  1454. llvm::APInt Min, End;
  1455. if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
  1456. hasBooleanRepresentation(Ty)))
  1457. return nullptr;
  1458. llvm::MDBuilder MDHelper(getLLVMContext());
  1459. return MDHelper.createRange(Min, End);
  1460. }
  1461. bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  1462. SourceLocation Loc) {
  1463. bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
  1464. bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
  1465. if (!HasBoolCheck && !HasEnumCheck)
  1466. return false;
  1467. bool IsBool = hasBooleanRepresentation(Ty) ||
  1468. NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
  1469. bool NeedsBoolCheck = HasBoolCheck && IsBool;
  1470. bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
  1471. if (!NeedsBoolCheck && !NeedsEnumCheck)
  1472. return false;
  1473. // Single-bit booleans don't need to be checked. Special-case this to avoid
  1474. // a bit width mismatch when handling bitfield values. This is handled by
  1475. // EmitFromMemory for the non-bitfield case.
  1476. if (IsBool &&
  1477. cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
  1478. return false;
  1479. llvm::APInt Min, End;
  1480. if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
  1481. return true;
  1482. auto &Ctx = getLLVMContext();
  1483. SanitizerScope SanScope(this);
  1484. llvm::Value *Check;
  1485. --End;
  1486. if (!Min) {
  1487. Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
  1488. } else {
  1489. llvm::Value *Upper =
  1490. Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
  1491. llvm::Value *Lower =
  1492. Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
  1493. Check = Builder.CreateAnd(Upper, Lower);
  1494. }
  1495. llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
  1496. EmitCheckTypeDescriptor(Ty)};
  1497. SanitizerMask Kind =
  1498. NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
  1499. EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
  1500. StaticArgs, EmitCheckValue(Value));
  1501. return true;
  1502. }
  1503. llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
  1504. QualType Ty,
  1505. SourceLocation Loc,
  1506. LValueBaseInfo BaseInfo,
  1507. TBAAAccessInfo TBAAInfo,
  1508. bool isNontemporal) {
  1509. if (!CGM.getCodeGenOpts().PreserveVec3Type) {
  1510. // For better performance, handle vector loads differently.
  1511. if (Ty->isVectorType()) {
  1512. const llvm::Type *EltTy = Addr.getElementType();
  1513. const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
  1514. // Handle vectors of size 3 like size 4 for better performance.
  1515. if (VTy->getNumElements() == 3) {
  1516. // Bitcast to vec4 type.
  1517. auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4);
  1518. Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
  1519. // Now load value.
  1520. llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
  1521. // Shuffle vector to get vec3.
  1522. V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2},
  1523. "extractVec");
  1524. return EmitFromMemory(V, Ty);
  1525. }
  1526. }
  1527. }
  1528. // Atomic operations have to be done on integral types.
  1529. LValue AtomicLValue =
  1530. LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
  1531. if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
  1532. return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
  1533. }
  1534. llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
  1535. if (isNontemporal) {
  1536. llvm::MDNode *Node = llvm::MDNode::get(
  1537. Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
  1538. Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
  1539. }
  1540. CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
  1541. if (EmitScalarRangeCheck(Load, Ty, Loc)) {
  1542. // In order to prevent the optimizer from throwing away the check, don't
  1543. // attach range metadata to the load.
  1544. } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
  1545. if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
  1546. Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
  1547. return EmitFromMemory(Load, Ty);
  1548. }
  1549. llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
  1550. // Bool has a different representation in memory than in registers.
  1551. if (hasBooleanRepresentation(Ty)) {
  1552. // This should really always be an i1, but sometimes it's already
  1553. // an i8, and it's awkward to track those cases down.
  1554. if (Value->getType()->isIntegerTy(1))
  1555. return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
  1556. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1557. "wrong value rep of bool");
  1558. }
  1559. return Value;
  1560. }
  1561. llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
  1562. // Bool has a different representation in memory than in registers.
  1563. if (hasBooleanRepresentation(Ty)) {
  1564. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1565. "wrong value rep of bool");
  1566. return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
  1567. }
  1568. return Value;
  1569. }
  1570. // Convert the pointer of \p Addr to a pointer to a vector (the value type of
  1571. // MatrixType), if it points to a array (the memory type of MatrixType).
  1572. static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
  1573. bool IsVector = true) {
  1574. auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
  1575. if (ArrayTy && IsVector) {
  1576. auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
  1577. ArrayTy->getNumElements());
  1578. return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
  1579. }
  1580. auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
  1581. if (VectorTy && !IsVector) {
  1582. auto *ArrayTy = llvm::ArrayType::get(
  1583. VectorTy->getElementType(),
  1584. cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
  1585. return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
  1586. }
  1587. return Addr;
  1588. }
  1589. // Emit a store of a matrix LValue. This may require casting the original
  1590. // pointer to memory address (ArrayType) to a pointer to the value type
  1591. // (VectorType).
  1592. static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
  1593. bool isInit, CodeGenFunction &CGF) {
  1594. Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
  1595. value->getType()->isVectorTy());
  1596. CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
  1597. lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
  1598. lvalue.isNontemporal());
  1599. }
  1600. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  1601. bool Volatile, QualType Ty,
  1602. LValueBaseInfo BaseInfo,
  1603. TBAAAccessInfo TBAAInfo,
  1604. bool isInit, bool isNontemporal) {
  1605. if (!CGM.getCodeGenOpts().PreserveVec3Type) {
  1606. // Handle vectors differently to get better performance.
  1607. if (Ty->isVectorType()) {
  1608. llvm::Type *SrcTy = Value->getType();
  1609. auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
  1610. // Handle vec3 special.
  1611. if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
  1612. // Our source is a vec3, do a shuffle vector to make it a vec4.
  1613. Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
  1614. "extractVec");
  1615. SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
  1616. }
  1617. if (Addr.getElementType() != SrcTy) {
  1618. Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
  1619. }
  1620. }
  1621. }
  1622. Value = EmitToMemory(Value, Ty);
  1623. LValue AtomicLValue =
  1624. LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
  1625. if (Ty->isAtomicType() ||
  1626. (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
  1627. EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
  1628. return;
  1629. }
  1630. llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
  1631. if (isNontemporal) {
  1632. llvm::MDNode *Node =
  1633. llvm::MDNode::get(Store->getContext(),
  1634. llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
  1635. Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
  1636. }
  1637. CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
  1638. }
  1639. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
  1640. bool isInit) {
  1641. if (lvalue.getType()->isConstantMatrixType()) {
  1642. EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
  1643. return;
  1644. }
  1645. EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
  1646. lvalue.getType(), lvalue.getBaseInfo(),
  1647. lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
  1648. }
  1649. // Emit a load of a LValue of matrix type. This may require casting the pointer
  1650. // to memory address (ArrayType) to a pointer to the value type (VectorType).
  1651. static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
  1652. CodeGenFunction &CGF) {
  1653. assert(LV.getType()->isConstantMatrixType());
  1654. Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
  1655. LV.setAddress(Addr);
  1656. return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
  1657. }
  1658. /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
  1659. /// method emits the address of the lvalue, then loads the result as an rvalue,
  1660. /// returning the rvalue.
  1661. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  1662. if (LV.isObjCWeak()) {
  1663. // load of a __weak object.
  1664. Address AddrWeakObj = LV.getAddress(*this);
  1665. return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
  1666. AddrWeakObj));
  1667. }
  1668. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1669. // In MRC mode, we do a load+autorelease.
  1670. if (!getLangOpts().ObjCAutoRefCount) {
  1671. return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
  1672. }
  1673. // In ARC mode, we load retained and then consume the value.
  1674. llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
  1675. Object = EmitObjCConsumeObject(LV.getType(), Object);
  1676. return RValue::get(Object);
  1677. }
  1678. if (LV.isSimple()) {
  1679. assert(!LV.getType()->isFunctionType());
  1680. if (LV.getType()->isConstantMatrixType())
  1681. return EmitLoadOfMatrixLValue(LV, Loc, *this);
  1682. // Everything needs a load.
  1683. return RValue::get(EmitLoadOfScalar(LV, Loc));
  1684. }
  1685. if (LV.isVectorElt()) {
  1686. llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
  1687. LV.isVolatileQualified());
  1688. return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
  1689. "vecext"));
  1690. }
  1691. // If this is a reference to a subset of the elements of a vector, either
  1692. // shuffle the input or extract/insert them as appropriate.
  1693. if (LV.isExtVectorElt()) {
  1694. return EmitLoadOfExtVectorElementLValue(LV);
  1695. }
  1696. // Global Register variables always invoke intrinsics
  1697. if (LV.isGlobalReg())
  1698. return EmitLoadOfGlobalRegLValue(LV);
  1699. if (LV.isMatrixElt()) {
  1700. llvm::Value *Idx = LV.getMatrixIdx();
  1701. if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
  1702. const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
  1703. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  1704. MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
  1705. }
  1706. llvm::LoadInst *Load =
  1707. Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
  1708. return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
  1709. }
  1710. assert(LV.isBitField() && "Unknown LValue type!");
  1711. return EmitLoadOfBitfieldLValue(LV, Loc);
  1712. }
  1713. RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
  1714. SourceLocation Loc) {
  1715. const CGBitFieldInfo &Info = LV.getBitFieldInfo();
  1716. // Get the output type.
  1717. llvm::Type *ResLTy = ConvertType(LV.getType());
  1718. Address Ptr = LV.getBitFieldAddress();
  1719. llvm::Value *Val =
  1720. Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
  1721. bool UseVolatile = LV.isVolatileQualified() &&
  1722. Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
  1723. const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
  1724. const unsigned StorageSize =
  1725. UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
  1726. if (Info.IsSigned) {
  1727. assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
  1728. unsigned HighBits = StorageSize - Offset - Info.Size;
  1729. if (HighBits)
  1730. Val = Builder.CreateShl(Val, HighBits, "bf.shl");
  1731. if (Offset + HighBits)
  1732. Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
  1733. } else {
  1734. if (Offset)
  1735. Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
  1736. if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
  1737. Val = Builder.CreateAnd(
  1738. Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
  1739. }
  1740. Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
  1741. EmitScalarRangeCheck(Val, LV.getType(), Loc);
  1742. return RValue::get(Val);
  1743. }
  1744. // If this is a reference to a subset of the elements of a vector, create an
  1745. // appropriate shufflevector.
  1746. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
  1747. llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
  1748. LV.isVolatileQualified());
  1749. const llvm::Constant *Elts = LV.getExtVectorElts();
  1750. // If the result of the expression is a non-vector type, we must be extracting
  1751. // a single element. Just codegen as an extractelement.
  1752. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1753. if (!ExprVT) {
  1754. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1755. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1756. return RValue::get(Builder.CreateExtractElement(Vec, Elt));
  1757. }
  1758. // Always use shuffle vector to try to retain the original program structure
  1759. unsigned NumResultElts = ExprVT->getNumElements();
  1760. SmallVector<int, 4> Mask;
  1761. for (unsigned i = 0; i != NumResultElts; ++i)
  1762. Mask.push_back(getAccessedFieldNo(i, Elts));
  1763. Vec = Builder.CreateShuffleVector(Vec, Mask);
  1764. return RValue::get(Vec);
  1765. }
  1766. /// Generates lvalue for partial ext_vector access.
  1767. Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
  1768. Address VectorAddress = LV.getExtVectorAddress();
  1769. QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
  1770. llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
  1771. Address CastToPointerElement =
  1772. Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
  1773. "conv.ptr.element");
  1774. const llvm::Constant *Elts = LV.getExtVectorElts();
  1775. unsigned ix = getAccessedFieldNo(0, Elts);
  1776. Address VectorBasePtrPlusIx =
  1777. Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
  1778. "vector.elt");
  1779. return VectorBasePtrPlusIx;
  1780. }
  1781. /// Load of global gamed gegisters are always calls to intrinsics.
  1782. RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
  1783. assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
  1784. "Bad type for register variable");
  1785. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1786. cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
  1787. // We accept integer and pointer types only
  1788. llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
  1789. llvm::Type *Ty = OrigTy;
  1790. if (OrigTy->isPointerTy())
  1791. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1792. llvm::Type *Types[] = { Ty };
  1793. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
  1794. llvm::Value *Call = Builder.CreateCall(
  1795. F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
  1796. if (OrigTy->isPointerTy())
  1797. Call = Builder.CreateIntToPtr(Call, OrigTy);
  1798. return RValue::get(Call);
  1799. }
  1800. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1801. /// lvalue, where both are guaranteed to the have the same type, and that type
  1802. /// is 'Ty'.
  1803. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  1804. bool isInit) {
  1805. if (!Dst.isSimple()) {
  1806. if (Dst.isVectorElt()) {
  1807. // Read/modify/write the vector, inserting the new element.
  1808. llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
  1809. Dst.isVolatileQualified());
  1810. Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
  1811. Dst.getVectorIdx(), "vecins");
  1812. Builder.CreateStore(Vec, Dst.getVectorAddress(),
  1813. Dst.isVolatileQualified());
  1814. return;
  1815. }
  1816. // If this is an update of extended vector elements, insert them as
  1817. // appropriate.
  1818. if (Dst.isExtVectorElt())
  1819. return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
  1820. if (Dst.isGlobalReg())
  1821. return EmitStoreThroughGlobalRegLValue(Src, Dst);
  1822. if (Dst.isMatrixElt()) {
  1823. llvm::Value *Idx = Dst.getMatrixIdx();
  1824. if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
  1825. const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
  1826. llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
  1827. MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
  1828. }
  1829. llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
  1830. llvm::Value *Vec =
  1831. Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
  1832. Builder.CreateStore(Vec, Dst.getMatrixAddress(),
  1833. Dst.isVolatileQualified());
  1834. return;
  1835. }
  1836. assert(Dst.isBitField() && "Unknown LValue type");
  1837. return EmitStoreThroughBitfieldLValue(Src, Dst);
  1838. }
  1839. // There's special magic for assigning into an ARC-qualified l-value.
  1840. if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
  1841. switch (Lifetime) {
  1842. case Qualifiers::OCL_None:
  1843. llvm_unreachable("present but none");
  1844. case Qualifiers::OCL_ExplicitNone:
  1845. // nothing special
  1846. break;
  1847. case Qualifiers::OCL_Strong:
  1848. if (isInit) {
  1849. Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
  1850. break;
  1851. }
  1852. EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
  1853. return;
  1854. case Qualifiers::OCL_Weak:
  1855. if (isInit)
  1856. // Initialize and then skip the primitive store.
  1857. EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
  1858. else
  1859. EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
  1860. /*ignore*/ true);
  1861. return;
  1862. case Qualifiers::OCL_Autoreleasing:
  1863. Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
  1864. Src.getScalarVal()));
  1865. // fall into the normal path
  1866. break;
  1867. }
  1868. }
  1869. if (Dst.isObjCWeak() && !Dst.isNonGC()) {
  1870. // load of a __weak object.
  1871. Address LvalueDst = Dst.getAddress(*this);
  1872. llvm::Value *src = Src.getScalarVal();
  1873. CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
  1874. return;
  1875. }
  1876. if (Dst.isObjCStrong() && !Dst.isNonGC()) {
  1877. // load of a __strong object.
  1878. Address LvalueDst = Dst.getAddress(*this);
  1879. llvm::Value *src = Src.getScalarVal();
  1880. if (Dst.isObjCIvar()) {
  1881. assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
  1882. llvm::Type *ResultType = IntPtrTy;
  1883. Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
  1884. llvm::Value *RHS = dst.getPointer();
  1885. RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
  1886. llvm::Value *LHS =
  1887. Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
  1888. "sub.ptr.lhs.cast");
  1889. llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
  1890. CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
  1891. BytesBetween);
  1892. } else if (Dst.isGlobalObjCRef()) {
  1893. CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
  1894. Dst.isThreadLocalRef());
  1895. }
  1896. else
  1897. CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
  1898. return;
  1899. }
  1900. assert(Src.isScalar() && "Can't emit an agg store with this method");
  1901. EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
  1902. }
  1903. void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1904. llvm::Value **Result) {
  1905. const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
  1906. llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
  1907. Address Ptr = Dst.getBitFieldAddress();
  1908. // Get the source value, truncated to the width of the bit-field.
  1909. llvm::Value *SrcVal = Src.getScalarVal();
  1910. // Cast the source to the storage type and shift it into place.
  1911. SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
  1912. /*isSigned=*/false);
  1913. llvm::Value *MaskedVal = SrcVal;
  1914. const bool UseVolatile =
  1915. CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
  1916. Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
  1917. const unsigned StorageSize =
  1918. UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
  1919. const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
  1920. // See if there are other bits in the bitfield's storage we'll need to load
  1921. // and mask together with source before storing.
  1922. if (StorageSize != Info.Size) {
  1923. assert(StorageSize > Info.Size && "Invalid bitfield size.");
  1924. llvm::Value *Val =
  1925. Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
  1926. // Mask the source value as needed.
  1927. if (!hasBooleanRepresentation(Dst.getType()))
  1928. SrcVal = Builder.CreateAnd(
  1929. SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
  1930. "bf.value");
  1931. MaskedVal = SrcVal;
  1932. if (Offset)
  1933. SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
  1934. // Mask out the original value.
  1935. Val = Builder.CreateAnd(
  1936. Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
  1937. "bf.clear");
  1938. // Or together the unchanged values and the source value.
  1939. SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
  1940. } else {
  1941. assert(Offset == 0);
  1942. // According to the AACPS:
  1943. // When a volatile bit-field is written, and its container does not overlap
  1944. // with any non-bit-field member, its container must be read exactly once
  1945. // and written exactly once using the access width appropriate to the type
  1946. // of the container. The two accesses are not atomic.
  1947. if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
  1948. CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
  1949. Builder.CreateLoad(Ptr, true, "bf.load");
  1950. }
  1951. // Write the new value back out.
  1952. Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
  1953. // Return the new value of the bit-field, if requested.
  1954. if (Result) {
  1955. llvm::Value *ResultVal = MaskedVal;
  1956. // Sign extend the value if needed.
  1957. if (Info.IsSigned) {
  1958. assert(Info.Size <= StorageSize);
  1959. unsigned HighBits = StorageSize - Info.Size;
  1960. if (HighBits) {
  1961. ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
  1962. ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
  1963. }
  1964. }
  1965. ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
  1966. "bf.result.cast");
  1967. *Result = EmitFromMemory(ResultVal, Dst.getType());
  1968. }
  1969. }
  1970. void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
  1971. LValue Dst) {
  1972. // This access turns into a read/modify/write of the vector. Load the input
  1973. // value now.
  1974. llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
  1975. Dst.isVolatileQualified());
  1976. const llvm::Constant *Elts = Dst.getExtVectorElts();
  1977. llvm::Value *SrcVal = Src.getScalarVal();
  1978. if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
  1979. unsigned NumSrcElts = VTy->getNumElements();
  1980. unsigned NumDstElts =
  1981. cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
  1982. if (NumDstElts == NumSrcElts) {
  1983. // Use shuffle vector is the src and destination are the same number of
  1984. // elements and restore the vector mask since it is on the side it will be
  1985. // stored.
  1986. SmallVector<int, 4> Mask(NumDstElts);
  1987. for (unsigned i = 0; i != NumSrcElts; ++i)
  1988. Mask[getAccessedFieldNo(i, Elts)] = i;
  1989. Vec = Builder.CreateShuffleVector(SrcVal, Mask);
  1990. } else if (NumDstElts > NumSrcElts) {
  1991. // Extended the source vector to the same length and then shuffle it
  1992. // into the destination.
  1993. // FIXME: since we're shuffling with undef, can we just use the indices
  1994. // into that? This could be simpler.
  1995. SmallVector<int, 4> ExtMask;
  1996. for (unsigned i = 0; i != NumSrcElts; ++i)
  1997. ExtMask.push_back(i);
  1998. ExtMask.resize(NumDstElts, -1);
  1999. llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
  2000. // build identity
  2001. SmallVector<int, 4> Mask;
  2002. for (unsigned i = 0; i != NumDstElts; ++i)
  2003. Mask.push_back(i);
  2004. // When the vector size is odd and .odd or .hi is used, the last element
  2005. // of the Elts constant array will be one past the size of the vector.
  2006. // Ignore the last element here, if it is greater than the mask size.
  2007. if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
  2008. NumSrcElts--;
  2009. // modify when what gets shuffled in
  2010. for (unsigned i = 0; i != NumSrcElts; ++i)
  2011. Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
  2012. Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
  2013. } else {
  2014. // We should never shorten the vector
  2015. llvm_unreachable("unexpected shorten vector length");
  2016. }
  2017. } else {
  2018. // If the Src is a scalar (not a vector) it must be updating one element.
  2019. unsigned InIdx = getAccessedFieldNo(0, Elts);
  2020. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  2021. Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
  2022. }
  2023. Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
  2024. Dst.isVolatileQualified());
  2025. }
  2026. /// Store of global named registers are always calls to intrinsics.
  2027. void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
  2028. assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
  2029. "Bad type for register variable");
  2030. llvm::MDNode *RegName = cast<llvm::MDNode>(
  2031. cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
  2032. assert(RegName && "Register LValue is not metadata");
  2033. // We accept integer and pointer types only
  2034. llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
  2035. llvm::Type *Ty = OrigTy;
  2036. if (OrigTy->isPointerTy())
  2037. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  2038. llvm::Type *Types[] = { Ty };
  2039. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
  2040. llvm::Value *Value = Src.getScalarVal();
  2041. if (OrigTy->isPointerTy())
  2042. Value = Builder.CreatePtrToInt(Value, Ty);
  2043. Builder.CreateCall(
  2044. F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
  2045. }
  2046. // setObjCGCLValueClass - sets class of the lvalue for the purpose of
  2047. // generating write-barries API. It is currently a global, ivar,
  2048. // or neither.
  2049. static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
  2050. LValue &LV,
  2051. bool IsMemberAccess=false) {
  2052. if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
  2053. return;
  2054. if (isa<ObjCIvarRefExpr>(E)) {
  2055. QualType ExpTy = E->getType();
  2056. if (IsMemberAccess && ExpTy->isPointerType()) {
  2057. // If ivar is a structure pointer, assigning to field of
  2058. // this struct follows gcc's behavior and makes it a non-ivar
  2059. // writer-barrier conservatively.
  2060. ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
  2061. if (ExpTy->isRecordType()) {
  2062. LV.setObjCIvar(false);
  2063. return;
  2064. }
  2065. }
  2066. LV.setObjCIvar(true);
  2067. auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
  2068. LV.setBaseIvarExp(Exp->getBase());
  2069. LV.setObjCArray(E->getType()->isArrayType());
  2070. return;
  2071. }
  2072. if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
  2073. if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
  2074. if (VD->hasGlobalStorage()) {
  2075. LV.setGlobalObjCRef(true);
  2076. LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
  2077. }
  2078. }
  2079. LV.setObjCArray(E->getType()->isArrayType());
  2080. return;
  2081. }
  2082. if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
  2083. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  2084. return;
  2085. }
  2086. if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
  2087. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  2088. if (LV.isObjCIvar()) {
  2089. // If cast is to a structure pointer, follow gcc's behavior and make it
  2090. // a non-ivar write-barrier.
  2091. QualType ExpTy = E->getType();
  2092. if (ExpTy->isPointerType())
  2093. ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
  2094. if (ExpTy->isRecordType())
  2095. LV.setObjCIvar(false);
  2096. }
  2097. return;
  2098. }
  2099. if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
  2100. setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
  2101. return;
  2102. }
  2103. if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
  2104. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  2105. return;
  2106. }
  2107. if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
  2108. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  2109. return;
  2110. }
  2111. if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
  2112. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  2113. return;
  2114. }
  2115. if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
  2116. setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
  2117. if (LV.isObjCIvar() && !LV.isObjCArray())
  2118. // Using array syntax to assigning to what an ivar points to is not
  2119. // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
  2120. LV.setObjCIvar(false);
  2121. else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
  2122. // Using array syntax to assigning to what global points to is not
  2123. // same as assigning to the global itself. {id *G;} G[i] = 0;
  2124. LV.setGlobalObjCRef(false);
  2125. return;
  2126. }
  2127. if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
  2128. setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
  2129. // We don't know if member is an 'ivar', but this flag is looked at
  2130. // only in the context of LV.isObjCIvar().
  2131. LV.setObjCArray(E->getType()->isArrayType());
  2132. return;
  2133. }
  2134. }
  2135. static llvm::Value *
  2136. EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
  2137. llvm::Value *V, llvm::Type *IRType,
  2138. StringRef Name = StringRef()) {
  2139. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  2140. return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
  2141. }
  2142. static LValue EmitThreadPrivateVarDeclLValue(
  2143. CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
  2144. llvm::Type *RealVarTy, SourceLocation Loc) {
  2145. if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
  2146. Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
  2147. CGF, VD, Addr, Loc);
  2148. else
  2149. Addr =
  2150. CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
  2151. Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
  2152. return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2153. }
  2154. static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
  2155. const VarDecl *VD, QualType T) {
  2156. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2157. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2158. // Return an invalid address if variable is MT_To and unified
  2159. // memory is not enabled. For all other cases: MT_Link and
  2160. // MT_To with unified memory, return a valid address.
  2161. if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2162. !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
  2163. return Address::invalid();
  2164. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  2165. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2166. CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
  2167. "Expected link clause OR to clause with unified memory enabled.");
  2168. QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
  2169. Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  2170. return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
  2171. }
  2172. Address
  2173. CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
  2174. LValueBaseInfo *PointeeBaseInfo,
  2175. TBAAAccessInfo *PointeeTBAAInfo) {
  2176. llvm::LoadInst *Load =
  2177. Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
  2178. CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
  2179. QualType PointeeType = RefLVal.getType()->getPointeeType();
  2180. CharUnits Align = CGM.getNaturalTypeAlignment(
  2181. PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
  2182. /* forPointeeType= */ true);
  2183. return Address(Load, ConvertTypeForMem(PointeeType), Align);
  2184. }
  2185. LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
  2186. LValueBaseInfo PointeeBaseInfo;
  2187. TBAAAccessInfo PointeeTBAAInfo;
  2188. Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
  2189. &PointeeTBAAInfo);
  2190. return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
  2191. PointeeBaseInfo, PointeeTBAAInfo);
  2192. }
  2193. Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
  2194. const PointerType *PtrTy,
  2195. LValueBaseInfo *BaseInfo,
  2196. TBAAAccessInfo *TBAAInfo) {
  2197. llvm::Value *Addr = Builder.CreateLoad(Ptr);
  2198. return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(),
  2199. BaseInfo, TBAAInfo,
  2200. /*forPointeeType=*/true));
  2201. }
  2202. LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
  2203. const PointerType *PtrTy) {
  2204. LValueBaseInfo BaseInfo;
  2205. TBAAAccessInfo TBAAInfo;
  2206. Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
  2207. return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
  2208. }
  2209. static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
  2210. const Expr *E, const VarDecl *VD) {
  2211. QualType T = E->getType();
  2212. // If it's thread_local, emit a call to its wrapper function instead.
  2213. if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  2214. CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
  2215. return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
  2216. // Check if the variable is marked as declare target with link clause in
  2217. // device codegen.
  2218. if (CGF.getLangOpts().OpenMPIsDevice) {
  2219. Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
  2220. if (Addr.isValid())
  2221. return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2222. }
  2223. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  2224. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  2225. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  2226. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  2227. Address Addr(V, RealVarTy, Alignment);
  2228. // Emit reference to the private copy of the variable if it is an OpenMP
  2229. // threadprivate variable.
  2230. if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
  2231. VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  2232. return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
  2233. E->getExprLoc());
  2234. }
  2235. LValue LV = VD->getType()->isReferenceType() ?
  2236. CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
  2237. AlignmentSource::Decl) :
  2238. CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2239. setObjCGCLValueClass(CGF.getContext(), E, LV);
  2240. return LV;
  2241. }
  2242. static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
  2243. GlobalDecl GD) {
  2244. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2245. if (FD->hasAttr<WeakRefAttr>()) {
  2246. ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
  2247. return aliasee.getPointer();
  2248. }
  2249. llvm::Constant *V = CGM.GetAddrOfFunction(GD);
  2250. if (!FD->hasPrototype()) {
  2251. if (const FunctionProtoType *Proto =
  2252. FD->getType()->getAs<FunctionProtoType>()) {
  2253. // Ugly case: for a K&R-style definition, the type of the definition
  2254. // isn't the same as the type of a use. Correct for this with a
  2255. // bitcast.
  2256. QualType NoProtoType =
  2257. CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
  2258. NoProtoType = CGM.getContext().getPointerType(NoProtoType);
  2259. V = llvm::ConstantExpr::getBitCast(V,
  2260. CGM.getTypes().ConvertType(NoProtoType));
  2261. }
  2262. }
  2263. return V;
  2264. }
  2265. static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
  2266. GlobalDecl GD) {
  2267. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2268. llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
  2269. CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
  2270. return CGF.MakeAddrLValue(V, E->getType(), Alignment,
  2271. AlignmentSource::Decl);
  2272. }
  2273. static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
  2274. llvm::Value *ThisValue) {
  2275. QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
  2276. LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
  2277. return CGF.EmitLValueForField(LV, FD);
  2278. }
  2279. /// Named Registers are named metadata pointing to the register name
  2280. /// which will be read from/written to as an argument to the intrinsic
  2281. /// @llvm.read/write_register.
  2282. /// So far, only the name is being passed down, but other options such as
  2283. /// register type, allocation type or even optimization options could be
  2284. /// passed down via the metadata node.
  2285. static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
  2286. SmallString<64> Name("llvm.named.register.");
  2287. AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
  2288. assert(Asm->getLabel().size() < 64-Name.size() &&
  2289. "Register name too big");
  2290. Name.append(Asm->getLabel());
  2291. llvm::NamedMDNode *M =
  2292. CGM.getModule().getOrInsertNamedMetadata(Name);
  2293. if (M->getNumOperands() == 0) {
  2294. llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
  2295. Asm->getLabel());
  2296. llvm::Metadata *Ops[] = {Str};
  2297. M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2298. }
  2299. CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
  2300. llvm::Value *Ptr =
  2301. llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
  2302. return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
  2303. }
  2304. /// Determine whether we can emit a reference to \p VD from the current
  2305. /// context, despite not necessarily having seen an odr-use of the variable in
  2306. /// this context.
  2307. static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
  2308. const DeclRefExpr *E,
  2309. const VarDecl *VD,
  2310. bool IsConstant) {
  2311. // For a variable declared in an enclosing scope, do not emit a spurious
  2312. // reference even if we have a capture, as that will emit an unwarranted
  2313. // reference to our capture state, and will likely generate worse code than
  2314. // emitting a local copy.
  2315. if (E->refersToEnclosingVariableOrCapture())
  2316. return false;
  2317. // For a local declaration declared in this function, we can always reference
  2318. // it even if we don't have an odr-use.
  2319. if (VD->hasLocalStorage()) {
  2320. return VD->getDeclContext() ==
  2321. dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
  2322. }
  2323. // For a global declaration, we can emit a reference to it if we know
  2324. // for sure that we are able to emit a definition of it.
  2325. VD = VD->getDefinition(CGF.getContext());
  2326. if (!VD)
  2327. return false;
  2328. // Don't emit a spurious reference if it might be to a variable that only
  2329. // exists on a different device / target.
  2330. // FIXME: This is unnecessarily broad. Check whether this would actually be a
  2331. // cross-target reference.
  2332. if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
  2333. CGF.getLangOpts().OpenCL) {
  2334. return false;
  2335. }
  2336. // We can emit a spurious reference only if the linkage implies that we'll
  2337. // be emitting a non-interposable symbol that will be retained until link
  2338. // time.
  2339. switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
  2340. case llvm::GlobalValue::ExternalLinkage:
  2341. case llvm::GlobalValue::LinkOnceODRLinkage:
  2342. case llvm::GlobalValue::WeakODRLinkage:
  2343. case llvm::GlobalValue::InternalLinkage:
  2344. case llvm::GlobalValue::PrivateLinkage:
  2345. return true;
  2346. default:
  2347. return false;
  2348. }
  2349. }
  2350. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  2351. const NamedDecl *ND = E->getDecl();
  2352. QualType T = E->getType();
  2353. assert(E->isNonOdrUse() != NOUR_Unevaluated &&
  2354. "should not emit an unevaluated operand");
  2355. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  2356. // Global Named registers access via intrinsics only
  2357. if (VD->getStorageClass() == SC_Register &&
  2358. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  2359. return EmitGlobalNamedRegister(VD, CGM);
  2360. // If this DeclRefExpr does not constitute an odr-use of the variable,
  2361. // we're not permitted to emit a reference to it in general, and it might
  2362. // not be captured if capture would be necessary for a use. Emit the
  2363. // constant value directly instead.
  2364. if (E->isNonOdrUse() == NOUR_Constant &&
  2365. (VD->getType()->isReferenceType() ||
  2366. !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
  2367. VD->getAnyInitializer(VD);
  2368. llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
  2369. E->getLocation(), *VD->evaluateValue(), VD->getType());
  2370. assert(Val && "failed to emit constant expression");
  2371. Address Addr = Address::invalid();
  2372. if (!VD->getType()->isReferenceType()) {
  2373. // Spill the constant value to a global.
  2374. Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
  2375. getContext().getDeclAlign(VD));
  2376. llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
  2377. auto *PTy = llvm::PointerType::get(
  2378. VarTy, getContext().getTargetAddressSpace(VD->getType()));
  2379. if (PTy != Addr.getType())
  2380. Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
  2381. } else {
  2382. // Should we be using the alignment of the constant pointer we emitted?
  2383. CharUnits Alignment =
  2384. CGM.getNaturalTypeAlignment(E->getType(),
  2385. /* BaseInfo= */ nullptr,
  2386. /* TBAAInfo= */ nullptr,
  2387. /* forPointeeType= */ true);
  2388. Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
  2389. }
  2390. return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2391. }
  2392. // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
  2393. // Check for captured variables.
  2394. if (E->refersToEnclosingVariableOrCapture()) {
  2395. VD = VD->getCanonicalDecl();
  2396. if (auto *FD = LambdaCaptureFields.lookup(VD))
  2397. return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
  2398. if (CapturedStmtInfo) {
  2399. auto I = LocalDeclMap.find(VD);
  2400. if (I != LocalDeclMap.end()) {
  2401. LValue CapLVal;
  2402. if (VD->getType()->isReferenceType())
  2403. CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
  2404. AlignmentSource::Decl);
  2405. else
  2406. CapLVal = MakeAddrLValue(I->second, T);
  2407. // Mark lvalue as nontemporal if the variable is marked as nontemporal
  2408. // in simd context.
  2409. if (getLangOpts().OpenMP &&
  2410. CGM.getOpenMPRuntime().isNontemporalDecl(VD))
  2411. CapLVal.setNontemporal(/*Value=*/true);
  2412. return CapLVal;
  2413. }
  2414. LValue CapLVal =
  2415. EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
  2416. CapturedStmtInfo->getContextValue());
  2417. CapLVal = MakeAddrLValue(
  2418. Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)),
  2419. CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
  2420. CapLVal.getTBAAInfo());
  2421. // Mark lvalue as nontemporal if the variable is marked as nontemporal
  2422. // in simd context.
  2423. if (getLangOpts().OpenMP &&
  2424. CGM.getOpenMPRuntime().isNontemporalDecl(VD))
  2425. CapLVal.setNontemporal(/*Value=*/true);
  2426. return CapLVal;
  2427. }
  2428. assert(isa<BlockDecl>(CurCodeDecl));
  2429. Address addr = GetAddrOfBlockDecl(VD);
  2430. return MakeAddrLValue(addr, T, AlignmentSource::Decl);
  2431. }
  2432. }
  2433. // FIXME: We should be able to assert this for FunctionDecls as well!
  2434. // FIXME: We should be able to assert this for all DeclRefExprs, not just
  2435. // those with a valid source location.
  2436. assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
  2437. !E->getLocation().isValid()) &&
  2438. "Should not use decl without marking it used!");
  2439. if (ND->hasAttr<WeakRefAttr>()) {
  2440. const auto *VD = cast<ValueDecl>(ND);
  2441. ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
  2442. return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
  2443. }
  2444. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  2445. // Check if this is a global variable.
  2446. if (VD->hasLinkage() || VD->isStaticDataMember())
  2447. return EmitGlobalVarDeclLValue(*this, E, VD);
  2448. Address addr = Address::invalid();
  2449. // The variable should generally be present in the local decl map.
  2450. auto iter = LocalDeclMap.find(VD);
  2451. if (iter != LocalDeclMap.end()) {
  2452. addr = iter->second;
  2453. // Otherwise, it might be static local we haven't emitted yet for
  2454. // some reason; most likely, because it's in an outer function.
  2455. } else if (VD->isStaticLocal()) {
  2456. llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
  2457. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
  2458. addr = Address(
  2459. var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
  2460. // No other cases for now.
  2461. } else {
  2462. llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
  2463. }
  2464. // Check for OpenMP threadprivate variables.
  2465. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
  2466. VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  2467. return EmitThreadPrivateVarDeclLValue(
  2468. *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
  2469. E->getExprLoc());
  2470. }
  2471. // Drill into block byref variables.
  2472. bool isBlockByref = VD->isEscapingByref();
  2473. if (isBlockByref) {
  2474. addr = emitBlockByrefAddress(addr, VD);
  2475. }
  2476. // Drill into reference types.
  2477. LValue LV = VD->getType()->isReferenceType() ?
  2478. EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
  2479. MakeAddrLValue(addr, T, AlignmentSource::Decl);
  2480. bool isLocalStorage = VD->hasLocalStorage();
  2481. bool NonGCable = isLocalStorage &&
  2482. !VD->getType()->isReferenceType() &&
  2483. !isBlockByref;
  2484. if (NonGCable) {
  2485. LV.getQuals().removeObjCGCAttr();
  2486. LV.setNonGC(true);
  2487. }
  2488. bool isImpreciseLifetime =
  2489. (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
  2490. if (isImpreciseLifetime)
  2491. LV.setARCPreciseLifetime(ARCImpreciseLifetime);
  2492. setObjCGCLValueClass(getContext(), E, LV);
  2493. return LV;
  2494. }
  2495. if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
  2496. LValue LV = EmitFunctionDeclLValue(*this, E, FD);
  2497. // Emit debuginfo for the function declaration if the target wants to.
  2498. if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
  2499. if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
  2500. auto *Fn =
  2501. cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
  2502. if (!Fn->getSubprogram())
  2503. DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
  2504. }
  2505. }
  2506. return LV;
  2507. }
  2508. // FIXME: While we're emitting a binding from an enclosing scope, all other
  2509. // DeclRefExprs we see should be implicitly treated as if they also refer to
  2510. // an enclosing scope.
  2511. if (const auto *BD = dyn_cast<BindingDecl>(ND))
  2512. return EmitLValue(BD->getBinding());
  2513. // We can form DeclRefExprs naming GUID declarations when reconstituting
  2514. // non-type template parameters into expressions.
  2515. if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
  2516. return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
  2517. AlignmentSource::Decl);
  2518. if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
  2519. return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
  2520. AlignmentSource::Decl);
  2521. llvm_unreachable("Unhandled DeclRefExpr");
  2522. }
  2523. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  2524. // __extension__ doesn't affect lvalue-ness.
  2525. if (E->getOpcode() == UO_Extension)
  2526. return EmitLValue(E->getSubExpr());
  2527. QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
  2528. switch (E->getOpcode()) {
  2529. default: llvm_unreachable("Unknown unary operator lvalue!");
  2530. case UO_Deref: {
  2531. QualType T = E->getSubExpr()->getType()->getPointeeType();
  2532. assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
  2533. LValueBaseInfo BaseInfo;
  2534. TBAAAccessInfo TBAAInfo;
  2535. Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
  2536. &TBAAInfo);
  2537. LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
  2538. LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
  2539. // We should not generate __weak write barrier on indirect reference
  2540. // of a pointer to object; as in void foo (__weak id *param); *param = 0;
  2541. // But, we continue to generate __strong write barrier on indirect write
  2542. // into a pointer to object.
  2543. if (getLangOpts().ObjC &&
  2544. getLangOpts().getGC() != LangOptions::NonGC &&
  2545. LV.isObjCWeak())
  2546. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  2547. return LV;
  2548. }
  2549. case UO_Real:
  2550. case UO_Imag: {
  2551. LValue LV = EmitLValue(E->getSubExpr());
  2552. assert(LV.isSimple() && "real/imag on non-ordinary l-value");
  2553. // __real is valid on scalars. This is a faster way of testing that.
  2554. // __imag can only produce an rvalue on scalars.
  2555. if (E->getOpcode() == UO_Real &&
  2556. !LV.getAddress(*this).getElementType()->isStructTy()) {
  2557. assert(E->getSubExpr()->getType()->isArithmeticType());
  2558. return LV;
  2559. }
  2560. QualType T = ExprTy->castAs<ComplexType>()->getElementType();
  2561. Address Component =
  2562. (E->getOpcode() == UO_Real
  2563. ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
  2564. : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
  2565. LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
  2566. CGM.getTBAAInfoForSubobject(LV, T));
  2567. ElemLV.getQuals().addQualifiers(LV.getQuals());
  2568. return ElemLV;
  2569. }
  2570. case UO_PreInc:
  2571. case UO_PreDec: {
  2572. LValue LV = EmitLValue(E->getSubExpr());
  2573. bool isInc = E->getOpcode() == UO_PreInc;
  2574. if (E->getType()->isAnyComplexType())
  2575. EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
  2576. else
  2577. EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
  2578. return LV;
  2579. }
  2580. }
  2581. }
  2582. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  2583. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
  2584. E->getType(), AlignmentSource::Decl);
  2585. }
  2586. LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
  2587. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
  2588. E->getType(), AlignmentSource::Decl);
  2589. }
  2590. LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
  2591. auto SL = E->getFunctionName();
  2592. assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
  2593. StringRef FnName = CurFn->getName();
  2594. if (FnName.startswith("\01"))
  2595. FnName = FnName.substr(1);
  2596. StringRef NameItems[] = {
  2597. PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
  2598. std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
  2599. if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
  2600. std::string Name = std::string(SL->getString());
  2601. if (!Name.empty()) {
  2602. unsigned Discriminator =
  2603. CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
  2604. if (Discriminator)
  2605. Name += "_" + Twine(Discriminator + 1).str();
  2606. auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
  2607. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2608. } else {
  2609. auto C =
  2610. CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
  2611. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2612. }
  2613. }
  2614. auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
  2615. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2616. }
  2617. /// Emit a type description suitable for use by a runtime sanitizer library. The
  2618. /// format of a type descriptor is
  2619. ///
  2620. /// \code
  2621. /// { i16 TypeKind, i16 TypeInfo }
  2622. /// \endcode
  2623. ///
  2624. /// followed by an array of i8 containing the type name. TypeKind is 0 for an
  2625. /// integer, 1 for a floating point value, and -1 for anything else.
  2626. llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
  2627. // Only emit each type's descriptor once.
  2628. if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
  2629. return C;
  2630. uint16_t TypeKind = -1;
  2631. uint16_t TypeInfo = 0;
  2632. if (T->isIntegerType()) {
  2633. TypeKind = 0;
  2634. TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
  2635. (T->isSignedIntegerType() ? 1 : 0);
  2636. } else if (T->isFloatingType()) {
  2637. TypeKind = 1;
  2638. TypeInfo = getContext().getTypeSize(T);
  2639. }
  2640. // Format the type name as if for a diagnostic, including quotes and
  2641. // optionally an 'aka'.
  2642. SmallString<32> Buffer;
  2643. CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
  2644. (intptr_t)T.getAsOpaquePtr(),
  2645. StringRef(), StringRef(), None, Buffer,
  2646. None);
  2647. llvm::Constant *Components[] = {
  2648. Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
  2649. llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
  2650. };
  2651. llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
  2652. auto *GV = new llvm::GlobalVariable(
  2653. CGM.getModule(), Descriptor->getType(),
  2654. /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
  2655. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2656. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
  2657. // Remember the descriptor for this type.
  2658. CGM.setTypeDescriptorInMap(T, GV);
  2659. return GV;
  2660. }
  2661. llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
  2662. llvm::Type *TargetTy = IntPtrTy;
  2663. if (V->getType() == TargetTy)
  2664. return V;
  2665. // Floating-point types which fit into intptr_t are bitcast to integers
  2666. // and then passed directly (after zero-extension, if necessary).
  2667. if (V->getType()->isFloatingPointTy()) {
  2668. unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedSize();
  2669. if (Bits <= TargetTy->getIntegerBitWidth())
  2670. V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
  2671. Bits));
  2672. }
  2673. // Integers which fit in intptr_t are zero-extended and passed directly.
  2674. if (V->getType()->isIntegerTy() &&
  2675. V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
  2676. return Builder.CreateZExt(V, TargetTy);
  2677. // Pointers are passed directly, everything else is passed by address.
  2678. if (!V->getType()->isPointerTy()) {
  2679. Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
  2680. Builder.CreateStore(V, Ptr);
  2681. V = Ptr.getPointer();
  2682. }
  2683. return Builder.CreatePtrToInt(V, TargetTy);
  2684. }
  2685. /// Emit a representation of a SourceLocation for passing to a handler
  2686. /// in a sanitizer runtime library. The format for this data is:
  2687. /// \code
  2688. /// struct SourceLocation {
  2689. /// const char *Filename;
  2690. /// int32_t Line, Column;
  2691. /// };
  2692. /// \endcode
  2693. /// For an invalid SourceLocation, the Filename pointer is null.
  2694. llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
  2695. llvm::Constant *Filename;
  2696. int Line, Column;
  2697. PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
  2698. if (PLoc.isValid()) {
  2699. StringRef FilenameString = PLoc.getFilename();
  2700. int PathComponentsToStrip =
  2701. CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
  2702. if (PathComponentsToStrip < 0) {
  2703. assert(PathComponentsToStrip != INT_MIN);
  2704. int PathComponentsToKeep = -PathComponentsToStrip;
  2705. auto I = llvm::sys::path::rbegin(FilenameString);
  2706. auto E = llvm::sys::path::rend(FilenameString);
  2707. while (I != E && --PathComponentsToKeep)
  2708. ++I;
  2709. FilenameString = FilenameString.substr(I - E);
  2710. } else if (PathComponentsToStrip > 0) {
  2711. auto I = llvm::sys::path::begin(FilenameString);
  2712. auto E = llvm::sys::path::end(FilenameString);
  2713. while (I != E && PathComponentsToStrip--)
  2714. ++I;
  2715. if (I != E)
  2716. FilenameString =
  2717. FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
  2718. else
  2719. FilenameString = llvm::sys::path::filename(FilenameString);
  2720. }
  2721. auto FilenameGV =
  2722. CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
  2723. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
  2724. cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
  2725. Filename = FilenameGV.getPointer();
  2726. Line = PLoc.getLine();
  2727. Column = PLoc.getColumn();
  2728. } else {
  2729. Filename = llvm::Constant::getNullValue(Int8PtrTy);
  2730. Line = Column = 0;
  2731. }
  2732. llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
  2733. Builder.getInt32(Column)};
  2734. return llvm::ConstantStruct::getAnon(Data);
  2735. }
  2736. namespace {
  2737. /// Specify under what conditions this check can be recovered
  2738. enum class CheckRecoverableKind {
  2739. /// Always terminate program execution if this check fails.
  2740. Unrecoverable,
  2741. /// Check supports recovering, runtime has both fatal (noreturn) and
  2742. /// non-fatal handlers for this check.
  2743. Recoverable,
  2744. /// Runtime conditionally aborts, always need to support recovery.
  2745. AlwaysRecoverable
  2746. };
  2747. }
  2748. static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
  2749. assert(Kind.countPopulation() == 1);
  2750. if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
  2751. return CheckRecoverableKind::AlwaysRecoverable;
  2752. else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
  2753. return CheckRecoverableKind::Unrecoverable;
  2754. else
  2755. return CheckRecoverableKind::Recoverable;
  2756. }
  2757. namespace {
  2758. struct SanitizerHandlerInfo {
  2759. char const *const Name;
  2760. unsigned Version;
  2761. };
  2762. }
  2763. const SanitizerHandlerInfo SanitizerHandlers[] = {
  2764. #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
  2765. LIST_SANITIZER_CHECKS
  2766. #undef SANITIZER_CHECK
  2767. };
  2768. static void emitCheckHandlerCall(CodeGenFunction &CGF,
  2769. llvm::FunctionType *FnType,
  2770. ArrayRef<llvm::Value *> FnArgs,
  2771. SanitizerHandler CheckHandler,
  2772. CheckRecoverableKind RecoverKind, bool IsFatal,
  2773. llvm::BasicBlock *ContBB) {
  2774. assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
  2775. Optional<ApplyDebugLocation> DL;
  2776. if (!CGF.Builder.getCurrentDebugLocation()) {
  2777. // Ensure that the call has at least an artificial debug location.
  2778. DL.emplace(CGF, SourceLocation());
  2779. }
  2780. bool NeedsAbortSuffix =
  2781. IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
  2782. bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
  2783. const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
  2784. const StringRef CheckName = CheckInfo.Name;
  2785. std::string FnName = "__ubsan_handle_" + CheckName.str();
  2786. if (CheckInfo.Version && !MinimalRuntime)
  2787. FnName += "_v" + llvm::utostr(CheckInfo.Version);
  2788. if (MinimalRuntime)
  2789. FnName += "_minimal";
  2790. if (NeedsAbortSuffix)
  2791. FnName += "_abort";
  2792. bool MayReturn =
  2793. !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
  2794. llvm::AttrBuilder B(CGF.getLLVMContext());
  2795. if (!MayReturn) {
  2796. B.addAttribute(llvm::Attribute::NoReturn)
  2797. .addAttribute(llvm::Attribute::NoUnwind);
  2798. }
  2799. B.addAttribute(llvm::Attribute::UWTable);
  2800. llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
  2801. FnType, FnName,
  2802. llvm::AttributeList::get(CGF.getLLVMContext(),
  2803. llvm::AttributeList::FunctionIndex, B),
  2804. /*Local=*/true);
  2805. llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
  2806. if (!MayReturn) {
  2807. HandlerCall->setDoesNotReturn();
  2808. CGF.Builder.CreateUnreachable();
  2809. } else {
  2810. CGF.Builder.CreateBr(ContBB);
  2811. }
  2812. }
  2813. void CodeGenFunction::EmitCheck(
  2814. ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2815. SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
  2816. ArrayRef<llvm::Value *> DynamicArgs) {
  2817. assert(IsSanitizerScope);
  2818. assert(Checked.size() > 0);
  2819. assert(CheckHandler >= 0 &&
  2820. size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
  2821. const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
  2822. llvm::Value *FatalCond = nullptr;
  2823. llvm::Value *RecoverableCond = nullptr;
  2824. llvm::Value *TrapCond = nullptr;
  2825. for (int i = 0, n = Checked.size(); i < n; ++i) {
  2826. llvm::Value *Check = Checked[i].first;
  2827. // -fsanitize-trap= overrides -fsanitize-recover=.
  2828. llvm::Value *&Cond =
  2829. CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
  2830. ? TrapCond
  2831. : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
  2832. ? RecoverableCond
  2833. : FatalCond;
  2834. Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
  2835. }
  2836. if (TrapCond)
  2837. EmitTrapCheck(TrapCond, CheckHandler);
  2838. if (!FatalCond && !RecoverableCond)
  2839. return;
  2840. llvm::Value *JointCond;
  2841. if (FatalCond && RecoverableCond)
  2842. JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
  2843. else
  2844. JointCond = FatalCond ? FatalCond : RecoverableCond;
  2845. assert(JointCond);
  2846. CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
  2847. assert(SanOpts.has(Checked[0].second));
  2848. #ifndef NDEBUG
  2849. for (int i = 1, n = Checked.size(); i < n; ++i) {
  2850. assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
  2851. "All recoverable kinds in a single check must be same!");
  2852. assert(SanOpts.has(Checked[i].second));
  2853. }
  2854. #endif
  2855. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2856. llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
  2857. llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
  2858. // Give hint that we very much don't expect to execute the handler
  2859. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  2860. llvm::MDBuilder MDHelper(getLLVMContext());
  2861. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2862. Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2863. EmitBlock(Handlers);
  2864. // Handler functions take an i8* pointing to the (handler-specific) static
  2865. // information block, followed by a sequence of intptr_t arguments
  2866. // representing operand values.
  2867. SmallVector<llvm::Value *, 4> Args;
  2868. SmallVector<llvm::Type *, 4> ArgTypes;
  2869. if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
  2870. Args.reserve(DynamicArgs.size() + 1);
  2871. ArgTypes.reserve(DynamicArgs.size() + 1);
  2872. // Emit handler arguments and create handler function type.
  2873. if (!StaticArgs.empty()) {
  2874. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2875. auto *InfoPtr =
  2876. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2877. llvm::GlobalVariable::PrivateLinkage, Info);
  2878. InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2879. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2880. Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
  2881. ArgTypes.push_back(Int8PtrTy);
  2882. }
  2883. for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
  2884. Args.push_back(EmitCheckValue(DynamicArgs[i]));
  2885. ArgTypes.push_back(IntPtrTy);
  2886. }
  2887. }
  2888. llvm::FunctionType *FnType =
  2889. llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
  2890. if (!FatalCond || !RecoverableCond) {
  2891. // Simple case: we need to generate a single handler call, either
  2892. // fatal, or non-fatal.
  2893. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
  2894. (FatalCond != nullptr), Cont);
  2895. } else {
  2896. // Emit two handler calls: first one for set of unrecoverable checks,
  2897. // another one for recoverable.
  2898. llvm::BasicBlock *NonFatalHandlerBB =
  2899. createBasicBlock("non_fatal." + CheckName);
  2900. llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
  2901. Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
  2902. EmitBlock(FatalHandlerBB);
  2903. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
  2904. NonFatalHandlerBB);
  2905. EmitBlock(NonFatalHandlerBB);
  2906. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
  2907. Cont);
  2908. }
  2909. EmitBlock(Cont);
  2910. }
  2911. void CodeGenFunction::EmitCfiSlowPathCheck(
  2912. SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
  2913. llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
  2914. llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
  2915. llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
  2916. llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
  2917. llvm::MDBuilder MDHelper(getLLVMContext());
  2918. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2919. BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2920. EmitBlock(CheckBB);
  2921. bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
  2922. llvm::CallInst *CheckCall;
  2923. llvm::FunctionCallee SlowPathFn;
  2924. if (WithDiag) {
  2925. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2926. auto *InfoPtr =
  2927. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2928. llvm::GlobalVariable::PrivateLinkage, Info);
  2929. InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2930. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2931. SlowPathFn = CGM.getModule().getOrInsertFunction(
  2932. "__cfi_slowpath_diag",
  2933. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
  2934. false));
  2935. CheckCall = Builder.CreateCall(
  2936. SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
  2937. } else {
  2938. SlowPathFn = CGM.getModule().getOrInsertFunction(
  2939. "__cfi_slowpath",
  2940. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
  2941. CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
  2942. }
  2943. CGM.setDSOLocal(
  2944. cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
  2945. CheckCall->setDoesNotThrow();
  2946. EmitBlock(Cont);
  2947. }
  2948. // Emit a stub for __cfi_check function so that the linker knows about this
  2949. // symbol in LTO mode.
  2950. void CodeGenFunction::EmitCfiCheckStub() {
  2951. llvm::Module *M = &CGM.getModule();
  2952. auto &Ctx = M->getContext();
  2953. llvm::Function *F = llvm::Function::Create(
  2954. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
  2955. llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
  2956. CGM.setDSOLocal(F);
  2957. llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
  2958. // FIXME: consider emitting an intrinsic call like
  2959. // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
  2960. // which can be lowered in CrossDSOCFI pass to the actual contents of
  2961. // __cfi_check. This would allow inlining of __cfi_check calls.
  2962. llvm::CallInst::Create(
  2963. llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
  2964. llvm::ReturnInst::Create(Ctx, nullptr, BB);
  2965. }
  2966. // This function is basically a switch over the CFI failure kind, which is
  2967. // extracted from CFICheckFailData (1st function argument). Each case is either
  2968. // llvm.trap or a call to one of the two runtime handlers, based on
  2969. // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
  2970. // failure kind) traps, but this should really never happen. CFICheckFailData
  2971. // can be nullptr if the calling module has -fsanitize-trap behavior for this
  2972. // check kind; in this case __cfi_check_fail traps as well.
  2973. void CodeGenFunction::EmitCfiCheckFail() {
  2974. SanitizerScope SanScope(this);
  2975. FunctionArgList Args;
  2976. ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
  2977. ImplicitParamDecl::Other);
  2978. ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
  2979. ImplicitParamDecl::Other);
  2980. Args.push_back(&ArgData);
  2981. Args.push_back(&ArgAddr);
  2982. const CGFunctionInfo &FI =
  2983. CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
  2984. llvm::Function *F = llvm::Function::Create(
  2985. llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
  2986. llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
  2987. CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
  2988. CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
  2989. F->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2990. StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
  2991. SourceLocation());
  2992. // This function is not affected by NoSanitizeList. This function does
  2993. // not have a source location, but "src:*" would still apply. Revert any
  2994. // changes to SanOpts made in StartFunction.
  2995. SanOpts = CGM.getLangOpts().Sanitize;
  2996. llvm::Value *Data =
  2997. EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
  2998. CGM.getContext().VoidPtrTy, ArgData.getLocation());
  2999. llvm::Value *Addr =
  3000. EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
  3001. CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
  3002. // Data == nullptr means the calling module has trap behaviour for this check.
  3003. llvm::Value *DataIsNotNullPtr =
  3004. Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
  3005. EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
  3006. llvm::StructType *SourceLocationTy =
  3007. llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
  3008. llvm::StructType *CfiCheckFailDataTy =
  3009. llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
  3010. llvm::Value *V = Builder.CreateConstGEP2_32(
  3011. CfiCheckFailDataTy,
  3012. Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
  3013. 0);
  3014. Address CheckKindAddr(V, getIntAlign());
  3015. llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
  3016. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  3017. CGM.getLLVMContext(),
  3018. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  3019. llvm::Value *ValidVtable = Builder.CreateZExt(
  3020. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  3021. {Addr, AllVtables}),
  3022. IntPtrTy);
  3023. const std::pair<int, SanitizerMask> CheckKinds[] = {
  3024. {CFITCK_VCall, SanitizerKind::CFIVCall},
  3025. {CFITCK_NVCall, SanitizerKind::CFINVCall},
  3026. {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
  3027. {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
  3028. {CFITCK_ICall, SanitizerKind::CFIICall}};
  3029. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
  3030. for (auto CheckKindMaskPair : CheckKinds) {
  3031. int Kind = CheckKindMaskPair.first;
  3032. SanitizerMask Mask = CheckKindMaskPair.second;
  3033. llvm::Value *Cond =
  3034. Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
  3035. if (CGM.getLangOpts().Sanitize.has(Mask))
  3036. EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
  3037. {Data, Addr, ValidVtable});
  3038. else
  3039. EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
  3040. }
  3041. FinishFunction();
  3042. // The only reference to this function will be created during LTO link.
  3043. // Make sure it survives until then.
  3044. CGM.addUsedGlobal(F);
  3045. }
  3046. void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
  3047. if (SanOpts.has(SanitizerKind::Unreachable)) {
  3048. SanitizerScope SanScope(this);
  3049. EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
  3050. SanitizerKind::Unreachable),
  3051. SanitizerHandler::BuiltinUnreachable,
  3052. EmitCheckSourceLocation(Loc), None);
  3053. }
  3054. Builder.CreateUnreachable();
  3055. }
  3056. void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
  3057. SanitizerHandler CheckHandlerID) {
  3058. llvm::BasicBlock *Cont = createBasicBlock("cont");
  3059. // If we're optimizing, collapse all calls to trap down to just one per
  3060. // check-type per function to save on code size.
  3061. if (TrapBBs.size() <= CheckHandlerID)
  3062. TrapBBs.resize(CheckHandlerID + 1);
  3063. llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
  3064. if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
  3065. TrapBB = createBasicBlock("trap");
  3066. Builder.CreateCondBr(Checked, Cont, TrapBB);
  3067. EmitBlock(TrapBB);
  3068. llvm::CallInst *TrapCall =
  3069. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
  3070. llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
  3071. if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
  3072. auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
  3073. CGM.getCodeGenOpts().TrapFuncName);
  3074. TrapCall->addFnAttr(A);
  3075. }
  3076. TrapCall->setDoesNotReturn();
  3077. TrapCall->setDoesNotThrow();
  3078. Builder.CreateUnreachable();
  3079. } else {
  3080. auto Call = TrapBB->begin();
  3081. assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
  3082. Call->applyMergedLocation(Call->getDebugLoc(),
  3083. Builder.getCurrentDebugLocation());
  3084. Builder.CreateCondBr(Checked, Cont, TrapBB);
  3085. }
  3086. EmitBlock(Cont);
  3087. }
  3088. llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
  3089. llvm::CallInst *TrapCall =
  3090. Builder.CreateCall(CGM.getIntrinsic(IntrID));
  3091. if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
  3092. auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
  3093. CGM.getCodeGenOpts().TrapFuncName);
  3094. TrapCall->addFnAttr(A);
  3095. }
  3096. return TrapCall;
  3097. }
  3098. Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
  3099. LValueBaseInfo *BaseInfo,
  3100. TBAAAccessInfo *TBAAInfo) {
  3101. assert(E->getType()->isArrayType() &&
  3102. "Array to pointer decay must have array source type!");
  3103. // Expressions of array type can't be bitfields or vector elements.
  3104. LValue LV = EmitLValue(E);
  3105. Address Addr = LV.getAddress(*this);
  3106. // If the array type was an incomplete type, we need to make sure
  3107. // the decay ends up being the right type.
  3108. llvm::Type *NewTy = ConvertType(E->getType());
  3109. Addr = Builder.CreateElementBitCast(Addr, NewTy);
  3110. // Note that VLA pointers are always decayed, so we don't need to do
  3111. // anything here.
  3112. if (!E->getType()->isVariableArrayType()) {
  3113. assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
  3114. "Expected pointer to array");
  3115. Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
  3116. }
  3117. // The result of this decay conversion points to an array element within the
  3118. // base lvalue. However, since TBAA currently does not support representing
  3119. // accesses to elements of member arrays, we conservatively represent accesses
  3120. // to the pointee object as if it had no any base lvalue specified.
  3121. // TODO: Support TBAA for member arrays.
  3122. QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
  3123. if (BaseInfo) *BaseInfo = LV.getBaseInfo();
  3124. if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
  3125. return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
  3126. }
  3127. /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
  3128. /// array to pointer, return the array subexpression.
  3129. static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
  3130. // If this isn't just an array->pointer decay, bail out.
  3131. const auto *CE = dyn_cast<CastExpr>(E);
  3132. if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
  3133. return nullptr;
  3134. // If this is a decay from variable width array, bail out.
  3135. const Expr *SubExpr = CE->getSubExpr();
  3136. if (SubExpr->getType()->isVariableArrayType())
  3137. return nullptr;
  3138. return SubExpr;
  3139. }
  3140. static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
  3141. llvm::Type *elemType,
  3142. llvm::Value *ptr,
  3143. ArrayRef<llvm::Value*> indices,
  3144. bool inbounds,
  3145. bool signedIndices,
  3146. SourceLocation loc,
  3147. const llvm::Twine &name = "arrayidx") {
  3148. if (inbounds) {
  3149. return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
  3150. CodeGenFunction::NotSubtraction, loc,
  3151. name);
  3152. } else {
  3153. return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
  3154. }
  3155. }
  3156. static CharUnits getArrayElementAlign(CharUnits arrayAlign,
  3157. llvm::Value *idx,
  3158. CharUnits eltSize) {
  3159. // If we have a constant index, we can use the exact offset of the
  3160. // element we're accessing.
  3161. if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
  3162. CharUnits offset = constantIdx->getZExtValue() * eltSize;
  3163. return arrayAlign.alignmentAtOffset(offset);
  3164. // Otherwise, use the worst-case alignment for any element.
  3165. } else {
  3166. return arrayAlign.alignmentOfArrayElement(eltSize);
  3167. }
  3168. }
  3169. static QualType getFixedSizeElementType(const ASTContext &ctx,
  3170. const VariableArrayType *vla) {
  3171. QualType eltType;
  3172. do {
  3173. eltType = vla->getElementType();
  3174. } while ((vla = ctx.getAsVariableArrayType(eltType)));
  3175. return eltType;
  3176. }
  3177. /// Given an array base, check whether its member access belongs to a record
  3178. /// with preserve_access_index attribute or not.
  3179. static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
  3180. if (!ArrayBase || !CGF.getDebugInfo())
  3181. return false;
  3182. // Only support base as either a MemberExpr or DeclRefExpr.
  3183. // DeclRefExpr to cover cases like:
  3184. // struct s { int a; int b[10]; };
  3185. // struct s *p;
  3186. // p[1].a
  3187. // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
  3188. // p->b[5] is a MemberExpr example.
  3189. const Expr *E = ArrayBase->IgnoreImpCasts();
  3190. if (const auto *ME = dyn_cast<MemberExpr>(E))
  3191. return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
  3192. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  3193. const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
  3194. if (!VarDef)
  3195. return false;
  3196. const auto *PtrT = VarDef->getType()->getAs<PointerType>();
  3197. if (!PtrT)
  3198. return false;
  3199. const auto *PointeeT = PtrT->getPointeeType()
  3200. ->getUnqualifiedDesugaredType();
  3201. if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
  3202. return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
  3203. return false;
  3204. }
  3205. return false;
  3206. }
  3207. static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
  3208. ArrayRef<llvm::Value *> indices,
  3209. QualType eltType, bool inbounds,
  3210. bool signedIndices, SourceLocation loc,
  3211. QualType *arrayType = nullptr,
  3212. const Expr *Base = nullptr,
  3213. const llvm::Twine &name = "arrayidx") {
  3214. // All the indices except that last must be zero.
  3215. #ifndef NDEBUG
  3216. for (auto idx : indices.drop_back())
  3217. assert(isa<llvm::ConstantInt>(idx) &&
  3218. cast<llvm::ConstantInt>(idx)->isZero());
  3219. #endif
  3220. // Determine the element size of the statically-sized base. This is
  3221. // the thing that the indices are expressed in terms of.
  3222. if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
  3223. eltType = getFixedSizeElementType(CGF.getContext(), vla);
  3224. }
  3225. // We can use that to compute the best alignment of the element.
  3226. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
  3227. CharUnits eltAlign =
  3228. getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
  3229. llvm::Value *eltPtr;
  3230. auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
  3231. if (!LastIndex ||
  3232. (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
  3233. eltPtr = emitArraySubscriptGEP(
  3234. CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
  3235. signedIndices, loc, name);
  3236. } else {
  3237. // Remember the original array subscript for bpf target
  3238. unsigned idx = LastIndex->getZExtValue();
  3239. llvm::DIType *DbgInfo = nullptr;
  3240. if (arrayType)
  3241. DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
  3242. eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
  3243. addr.getPointer(),
  3244. indices.size() - 1,
  3245. idx, DbgInfo);
  3246. }
  3247. return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
  3248. }
  3249. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  3250. bool Accessed) {
  3251. // The index must always be an integer, which is not an aggregate. Emit it
  3252. // in lexical order (this complexity is, sadly, required by C++17).
  3253. llvm::Value *IdxPre =
  3254. (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
  3255. bool SignedIndices = false;
  3256. auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
  3257. auto *Idx = IdxPre;
  3258. if (E->getLHS() != E->getIdx()) {
  3259. assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
  3260. Idx = EmitScalarExpr(E->getIdx());
  3261. }
  3262. QualType IdxTy = E->getIdx()->getType();
  3263. bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
  3264. SignedIndices |= IdxSigned;
  3265. if (SanOpts.has(SanitizerKind::ArrayBounds))
  3266. EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
  3267. // Extend or truncate the index type to 32 or 64-bits.
  3268. if (Promote && Idx->getType() != IntPtrTy)
  3269. Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
  3270. return Idx;
  3271. };
  3272. IdxPre = nullptr;
  3273. // If the base is a vector type, then we are forming a vector element lvalue
  3274. // with this subscript.
  3275. if (E->getBase()->getType()->isVectorType() &&
  3276. !isa<ExtVectorElementExpr>(E->getBase())) {
  3277. // Emit the vector as an lvalue to get its address.
  3278. LValue LHS = EmitLValue(E->getBase());
  3279. auto *Idx = EmitIdxAfterBase(/*Promote*/false);
  3280. assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
  3281. return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
  3282. E->getBase()->getType(), LHS.getBaseInfo(),
  3283. TBAAAccessInfo());
  3284. }
  3285. // All the other cases basically behave like simple offsetting.
  3286. // Handle the extvector case we ignored above.
  3287. if (isa<ExtVectorElementExpr>(E->getBase())) {
  3288. LValue LV = EmitLValue(E->getBase());
  3289. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3290. Address Addr = EmitExtVectorElementLValue(LV);
  3291. QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
  3292. Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
  3293. SignedIndices, E->getExprLoc());
  3294. return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
  3295. CGM.getTBAAInfoForSubobject(LV, EltType));
  3296. }
  3297. LValueBaseInfo EltBaseInfo;
  3298. TBAAAccessInfo EltTBAAInfo;
  3299. Address Addr = Address::invalid();
  3300. if (const VariableArrayType *vla =
  3301. getContext().getAsVariableArrayType(E->getType())) {
  3302. // The base must be a pointer, which is not an aggregate. Emit
  3303. // it. It needs to be emitted first in case it's what captures
  3304. // the VLA bounds.
  3305. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3306. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3307. // The element count here is the total number of non-VLA elements.
  3308. llvm::Value *numElements = getVLASize(vla).NumElts;
  3309. // Effectively, the multiply by the VLA size is part of the GEP.
  3310. // GEP indexes are signed, and scaling an index isn't permitted to
  3311. // signed-overflow, so we use the same semantics for our explicit
  3312. // multiply. We suppress this if overflow is not undefined behavior.
  3313. if (getLangOpts().isSignedOverflowDefined()) {
  3314. Idx = Builder.CreateMul(Idx, numElements);
  3315. } else {
  3316. Idx = Builder.CreateNSWMul(Idx, numElements);
  3317. }
  3318. Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
  3319. !getLangOpts().isSignedOverflowDefined(),
  3320. SignedIndices, E->getExprLoc());
  3321. } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
  3322. // Indexing over an interface, as in "NSString *P; P[4];"
  3323. // Emit the base pointer.
  3324. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3325. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3326. CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
  3327. llvm::Value *InterfaceSizeVal =
  3328. llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
  3329. llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
  3330. // We don't necessarily build correct LLVM struct types for ObjC
  3331. // interfaces, so we can't rely on GEP to do this scaling
  3332. // correctly, so we need to cast to i8*. FIXME: is this actually
  3333. // true? A lot of other things in the fragile ABI would break...
  3334. llvm::Type *OrigBaseTy = Addr.getType();
  3335. Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
  3336. // Do the GEP.
  3337. CharUnits EltAlign =
  3338. getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
  3339. llvm::Value *EltPtr =
  3340. emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
  3341. ScaledIdx, false, SignedIndices, E->getExprLoc());
  3342. Addr = Address(EltPtr, EltAlign);
  3343. // Cast back.
  3344. Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
  3345. } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
  3346. // If this is A[i] where A is an array, the frontend will have decayed the
  3347. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  3348. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  3349. // "gep x, i" here. Emit one "gep A, 0, i".
  3350. assert(Array->getType()->isArrayType() &&
  3351. "Array to pointer decay must have array source type!");
  3352. LValue ArrayLV;
  3353. // For simple multidimensional array indexing, set the 'accessed' flag for
  3354. // better bounds-checking of the base expression.
  3355. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  3356. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  3357. else
  3358. ArrayLV = EmitLValue(Array);
  3359. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3360. // Propagate the alignment from the array itself to the result.
  3361. QualType arrayType = Array->getType();
  3362. Addr = emitArraySubscriptGEP(
  3363. *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
  3364. E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
  3365. E->getExprLoc(), &arrayType, E->getBase());
  3366. EltBaseInfo = ArrayLV.getBaseInfo();
  3367. EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
  3368. } else {
  3369. // The base must be a pointer; emit it with an estimate of its alignment.
  3370. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3371. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3372. QualType ptrType = E->getBase()->getType();
  3373. Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
  3374. !getLangOpts().isSignedOverflowDefined(),
  3375. SignedIndices, E->getExprLoc(), &ptrType,
  3376. E->getBase());
  3377. }
  3378. LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
  3379. if (getLangOpts().ObjC &&
  3380. getLangOpts().getGC() != LangOptions::NonGC) {
  3381. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  3382. setObjCGCLValueClass(getContext(), E, LV);
  3383. }
  3384. return LV;
  3385. }
  3386. LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
  3387. assert(
  3388. !E->isIncomplete() &&
  3389. "incomplete matrix subscript expressions should be rejected during Sema");
  3390. LValue Base = EmitLValue(E->getBase());
  3391. llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
  3392. llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
  3393. llvm::Value *NumRows = Builder.getIntN(
  3394. RowIdx->getType()->getScalarSizeInBits(),
  3395. E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
  3396. llvm::Value *FinalIdx =
  3397. Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
  3398. return LValue::MakeMatrixElt(
  3399. MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
  3400. E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
  3401. }
  3402. static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
  3403. LValueBaseInfo &BaseInfo,
  3404. TBAAAccessInfo &TBAAInfo,
  3405. QualType BaseTy, QualType ElTy,
  3406. bool IsLowerBound) {
  3407. LValue BaseLVal;
  3408. if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
  3409. BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
  3410. if (BaseTy->isArrayType()) {
  3411. Address Addr = BaseLVal.getAddress(CGF);
  3412. BaseInfo = BaseLVal.getBaseInfo();
  3413. // If the array type was an incomplete type, we need to make sure
  3414. // the decay ends up being the right type.
  3415. llvm::Type *NewTy = CGF.ConvertType(BaseTy);
  3416. Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
  3417. // Note that VLA pointers are always decayed, so we don't need to do
  3418. // anything here.
  3419. if (!BaseTy->isVariableArrayType()) {
  3420. assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
  3421. "Expected pointer to array");
  3422. Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
  3423. }
  3424. return CGF.Builder.CreateElementBitCast(Addr,
  3425. CGF.ConvertTypeForMem(ElTy));
  3426. }
  3427. LValueBaseInfo TypeBaseInfo;
  3428. TBAAAccessInfo TypeTBAAInfo;
  3429. CharUnits Align =
  3430. CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
  3431. BaseInfo.mergeForCast(TypeBaseInfo);
  3432. TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
  3433. return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align);
  3434. }
  3435. return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
  3436. }
  3437. LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  3438. bool IsLowerBound) {
  3439. QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
  3440. QualType ResultExprTy;
  3441. if (auto *AT = getContext().getAsArrayType(BaseTy))
  3442. ResultExprTy = AT->getElementType();
  3443. else
  3444. ResultExprTy = BaseTy->getPointeeType();
  3445. llvm::Value *Idx = nullptr;
  3446. if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
  3447. // Requesting lower bound or upper bound, but without provided length and
  3448. // without ':' symbol for the default length -> length = 1.
  3449. // Idx = LowerBound ?: 0;
  3450. if (auto *LowerBound = E->getLowerBound()) {
  3451. Idx = Builder.CreateIntCast(
  3452. EmitScalarExpr(LowerBound), IntPtrTy,
  3453. LowerBound->getType()->hasSignedIntegerRepresentation());
  3454. } else
  3455. Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
  3456. } else {
  3457. // Try to emit length or lower bound as constant. If this is possible, 1
  3458. // is subtracted from constant length or lower bound. Otherwise, emit LLVM
  3459. // IR (LB + Len) - 1.
  3460. auto &C = CGM.getContext();
  3461. auto *Length = E->getLength();
  3462. llvm::APSInt ConstLength;
  3463. if (Length) {
  3464. // Idx = LowerBound + Length - 1;
  3465. if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
  3466. ConstLength = CL->zextOrTrunc(PointerWidthInBits);
  3467. Length = nullptr;
  3468. }
  3469. auto *LowerBound = E->getLowerBound();
  3470. llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
  3471. if (LowerBound) {
  3472. if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) {
  3473. ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
  3474. LowerBound = nullptr;
  3475. }
  3476. }
  3477. if (!Length)
  3478. --ConstLength;
  3479. else if (!LowerBound)
  3480. --ConstLowerBound;
  3481. if (Length || LowerBound) {
  3482. auto *LowerBoundVal =
  3483. LowerBound
  3484. ? Builder.CreateIntCast(
  3485. EmitScalarExpr(LowerBound), IntPtrTy,
  3486. LowerBound->getType()->hasSignedIntegerRepresentation())
  3487. : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
  3488. auto *LengthVal =
  3489. Length
  3490. ? Builder.CreateIntCast(
  3491. EmitScalarExpr(Length), IntPtrTy,
  3492. Length->getType()->hasSignedIntegerRepresentation())
  3493. : llvm::ConstantInt::get(IntPtrTy, ConstLength);
  3494. Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
  3495. /*HasNUW=*/false,
  3496. !getLangOpts().isSignedOverflowDefined());
  3497. if (Length && LowerBound) {
  3498. Idx = Builder.CreateSub(
  3499. Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
  3500. /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
  3501. }
  3502. } else
  3503. Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
  3504. } else {
  3505. // Idx = ArraySize - 1;
  3506. QualType ArrayTy = BaseTy->isPointerType()
  3507. ? E->getBase()->IgnoreParenImpCasts()->getType()
  3508. : BaseTy;
  3509. if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
  3510. Length = VAT->getSizeExpr();
  3511. if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
  3512. ConstLength = *L;
  3513. Length = nullptr;
  3514. }
  3515. } else {
  3516. auto *CAT = C.getAsConstantArrayType(ArrayTy);
  3517. ConstLength = CAT->getSize();
  3518. }
  3519. if (Length) {
  3520. auto *LengthVal = Builder.CreateIntCast(
  3521. EmitScalarExpr(Length), IntPtrTy,
  3522. Length->getType()->hasSignedIntegerRepresentation());
  3523. Idx = Builder.CreateSub(
  3524. LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
  3525. /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
  3526. } else {
  3527. ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
  3528. --ConstLength;
  3529. Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
  3530. }
  3531. }
  3532. }
  3533. assert(Idx);
  3534. Address EltPtr = Address::invalid();
  3535. LValueBaseInfo BaseInfo;
  3536. TBAAAccessInfo TBAAInfo;
  3537. if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
  3538. // The base must be a pointer, which is not an aggregate. Emit
  3539. // it. It needs to be emitted first in case it's what captures
  3540. // the VLA bounds.
  3541. Address Base =
  3542. emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
  3543. BaseTy, VLA->getElementType(), IsLowerBound);
  3544. // The element count here is the total number of non-VLA elements.
  3545. llvm::Value *NumElements = getVLASize(VLA).NumElts;
  3546. // Effectively, the multiply by the VLA size is part of the GEP.
  3547. // GEP indexes are signed, and scaling an index isn't permitted to
  3548. // signed-overflow, so we use the same semantics for our explicit
  3549. // multiply. We suppress this if overflow is not undefined behavior.
  3550. if (getLangOpts().isSignedOverflowDefined())
  3551. Idx = Builder.CreateMul(Idx, NumElements);
  3552. else
  3553. Idx = Builder.CreateNSWMul(Idx, NumElements);
  3554. EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
  3555. !getLangOpts().isSignedOverflowDefined(),
  3556. /*signedIndices=*/false, E->getExprLoc());
  3557. } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
  3558. // If this is A[i] where A is an array, the frontend will have decayed the
  3559. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  3560. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  3561. // "gep x, i" here. Emit one "gep A, 0, i".
  3562. assert(Array->getType()->isArrayType() &&
  3563. "Array to pointer decay must have array source type!");
  3564. LValue ArrayLV;
  3565. // For simple multidimensional array indexing, set the 'accessed' flag for
  3566. // better bounds-checking of the base expression.
  3567. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  3568. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  3569. else
  3570. ArrayLV = EmitLValue(Array);
  3571. // Propagate the alignment from the array itself to the result.
  3572. EltPtr = emitArraySubscriptGEP(
  3573. *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
  3574. ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
  3575. /*signedIndices=*/false, E->getExprLoc());
  3576. BaseInfo = ArrayLV.getBaseInfo();
  3577. TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
  3578. } else {
  3579. Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
  3580. TBAAInfo, BaseTy, ResultExprTy,
  3581. IsLowerBound);
  3582. EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
  3583. !getLangOpts().isSignedOverflowDefined(),
  3584. /*signedIndices=*/false, E->getExprLoc());
  3585. }
  3586. return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
  3587. }
  3588. LValue CodeGenFunction::
  3589. EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  3590. // Emit the base vector as an l-value.
  3591. LValue Base;
  3592. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  3593. if (E->isArrow()) {
  3594. // If it is a pointer to a vector, emit the address and form an lvalue with
  3595. // it.
  3596. LValueBaseInfo BaseInfo;
  3597. TBAAAccessInfo TBAAInfo;
  3598. Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
  3599. const auto *PT = E->getBase()->getType()->castAs<PointerType>();
  3600. Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
  3601. Base.getQuals().removeObjCGCAttr();
  3602. } else if (E->getBase()->isGLValue()) {
  3603. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  3604. // emit the base as an lvalue.
  3605. assert(E->getBase()->getType()->isVectorType());
  3606. Base = EmitLValue(E->getBase());
  3607. } else {
  3608. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  3609. assert(E->getBase()->getType()->isVectorType() &&
  3610. "Result must be a vector");
  3611. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  3612. // Store the vector to memory (because LValue wants an address).
  3613. Address VecMem = CreateMemTemp(E->getBase()->getType());
  3614. Builder.CreateStore(Vec, VecMem);
  3615. Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
  3616. AlignmentSource::Decl);
  3617. }
  3618. QualType type =
  3619. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  3620. // Encode the element access list into a vector of unsigned indices.
  3621. SmallVector<uint32_t, 4> Indices;
  3622. E->getEncodedElementAccess(Indices);
  3623. if (Base.isSimple()) {
  3624. llvm::Constant *CV =
  3625. llvm::ConstantDataVector::get(getLLVMContext(), Indices);
  3626. return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
  3627. Base.getBaseInfo(), TBAAAccessInfo());
  3628. }
  3629. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  3630. llvm::Constant *BaseElts = Base.getExtVectorElts();
  3631. SmallVector<llvm::Constant *, 4> CElts;
  3632. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  3633. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  3634. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  3635. return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
  3636. Base.getBaseInfo(), TBAAAccessInfo());
  3637. }
  3638. LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
  3639. if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
  3640. EmitIgnoredExpr(E->getBase());
  3641. return EmitDeclRefLValue(DRE);
  3642. }
  3643. Expr *BaseExpr = E->getBase();
  3644. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  3645. LValue BaseLV;
  3646. if (E->isArrow()) {
  3647. LValueBaseInfo BaseInfo;
  3648. TBAAAccessInfo TBAAInfo;
  3649. Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
  3650. QualType PtrTy = BaseExpr->getType()->getPointeeType();
  3651. SanitizerSet SkippedChecks;
  3652. bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
  3653. if (IsBaseCXXThis)
  3654. SkippedChecks.set(SanitizerKind::Alignment, true);
  3655. if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
  3656. SkippedChecks.set(SanitizerKind::Null, true);
  3657. EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
  3658. /*Alignment=*/CharUnits::Zero(), SkippedChecks);
  3659. BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
  3660. } else
  3661. BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
  3662. NamedDecl *ND = E->getMemberDecl();
  3663. if (auto *Field = dyn_cast<FieldDecl>(ND)) {
  3664. LValue LV = EmitLValueForField(BaseLV, Field);
  3665. setObjCGCLValueClass(getContext(), E, LV);
  3666. if (getLangOpts().OpenMP) {
  3667. // If the member was explicitly marked as nontemporal, mark it as
  3668. // nontemporal. If the base lvalue is marked as nontemporal, mark access
  3669. // to children as nontemporal too.
  3670. if ((IsWrappedCXXThis(BaseExpr) &&
  3671. CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
  3672. BaseLV.isNontemporal())
  3673. LV.setNontemporal(/*Value=*/true);
  3674. }
  3675. return LV;
  3676. }
  3677. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  3678. return EmitFunctionDeclLValue(*this, E, FD);
  3679. llvm_unreachable("Unhandled member declaration!");
  3680. }
  3681. /// Given that we are currently emitting a lambda, emit an l-value for
  3682. /// one of its members.
  3683. LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
  3684. if (CurCodeDecl) {
  3685. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
  3686. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
  3687. }
  3688. QualType LambdaTagType =
  3689. getContext().getTagDeclType(Field->getParent());
  3690. LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
  3691. return EmitLValueForField(LambdaLV, Field);
  3692. }
  3693. /// Get the field index in the debug info. The debug info structure/union
  3694. /// will ignore the unnamed bitfields.
  3695. unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
  3696. unsigned FieldIndex) {
  3697. unsigned I = 0, Skipped = 0;
  3698. for (auto F : Rec->getDefinition()->fields()) {
  3699. if (I == FieldIndex)
  3700. break;
  3701. if (F->isUnnamedBitfield())
  3702. Skipped++;
  3703. I++;
  3704. }
  3705. return FieldIndex - Skipped;
  3706. }
  3707. /// Get the address of a zero-sized field within a record. The resulting
  3708. /// address doesn't necessarily have the right type.
  3709. static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
  3710. const FieldDecl *Field) {
  3711. CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
  3712. CGF.getContext().getFieldOffset(Field));
  3713. if (Offset.isZero())
  3714. return Base;
  3715. Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
  3716. return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
  3717. }
  3718. /// Drill down to the storage of a field without walking into
  3719. /// reference types.
  3720. ///
  3721. /// The resulting address doesn't necessarily have the right type.
  3722. static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
  3723. const FieldDecl *field) {
  3724. if (field->isZeroSize(CGF.getContext()))
  3725. return emitAddrOfZeroSizeField(CGF, base, field);
  3726. const RecordDecl *rec = field->getParent();
  3727. unsigned idx =
  3728. CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  3729. return CGF.Builder.CreateStructGEP(base, idx, field->getName());
  3730. }
  3731. static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
  3732. Address addr, const FieldDecl *field) {
  3733. const RecordDecl *rec = field->getParent();
  3734. llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
  3735. base.getType(), rec->getLocation());
  3736. unsigned idx =
  3737. CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  3738. return CGF.Builder.CreatePreserveStructAccessIndex(
  3739. addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
  3740. }
  3741. static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
  3742. const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
  3743. if (!RD)
  3744. return false;
  3745. if (RD->isDynamicClass())
  3746. return true;
  3747. for (const auto &Base : RD->bases())
  3748. if (hasAnyVptr(Base.getType(), Context))
  3749. return true;
  3750. for (const FieldDecl *Field : RD->fields())
  3751. if (hasAnyVptr(Field->getType(), Context))
  3752. return true;
  3753. return false;
  3754. }
  3755. LValue CodeGenFunction::EmitLValueForField(LValue base,
  3756. const FieldDecl *field) {
  3757. LValueBaseInfo BaseInfo = base.getBaseInfo();
  3758. if (field->isBitField()) {
  3759. const CGRecordLayout &RL =
  3760. CGM.getTypes().getCGRecordLayout(field->getParent());
  3761. const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
  3762. const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
  3763. CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
  3764. Info.VolatileStorageSize != 0 &&
  3765. field->getType()
  3766. .withCVRQualifiers(base.getVRQualifiers())
  3767. .isVolatileQualified();
  3768. Address Addr = base.getAddress(*this);
  3769. unsigned Idx = RL.getLLVMFieldNo(field);
  3770. const RecordDecl *rec = field->getParent();
  3771. if (!UseVolatile) {
  3772. if (!IsInPreservedAIRegion &&
  3773. (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
  3774. if (Idx != 0)
  3775. // For structs, we GEP to the field that the record layout suggests.
  3776. Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
  3777. } else {
  3778. llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
  3779. getContext().getRecordType(rec), rec->getLocation());
  3780. Addr = Builder.CreatePreserveStructAccessIndex(
  3781. Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
  3782. DbgInfo);
  3783. }
  3784. }
  3785. const unsigned SS =
  3786. UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
  3787. // Get the access type.
  3788. llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
  3789. if (Addr.getElementType() != FieldIntTy)
  3790. Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
  3791. if (UseVolatile) {
  3792. const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
  3793. if (VolatileOffset)
  3794. Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
  3795. }
  3796. QualType fieldType =
  3797. field->getType().withCVRQualifiers(base.getVRQualifiers());
  3798. // TODO: Support TBAA for bit fields.
  3799. LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
  3800. return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
  3801. TBAAAccessInfo());
  3802. }
  3803. // Fields of may-alias structures are may-alias themselves.
  3804. // FIXME: this should get propagated down through anonymous structs
  3805. // and unions.
  3806. QualType FieldType = field->getType();
  3807. const RecordDecl *rec = field->getParent();
  3808. AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
  3809. LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
  3810. TBAAAccessInfo FieldTBAAInfo;
  3811. if (base.getTBAAInfo().isMayAlias() ||
  3812. rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
  3813. FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
  3814. } else if (rec->isUnion()) {
  3815. // TODO: Support TBAA for unions.
  3816. FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
  3817. } else {
  3818. // If no base type been assigned for the base access, then try to generate
  3819. // one for this base lvalue.
  3820. FieldTBAAInfo = base.getTBAAInfo();
  3821. if (!FieldTBAAInfo.BaseType) {
  3822. FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
  3823. assert(!FieldTBAAInfo.Offset &&
  3824. "Nonzero offset for an access with no base type!");
  3825. }
  3826. // Adjust offset to be relative to the base type.
  3827. const ASTRecordLayout &Layout =
  3828. getContext().getASTRecordLayout(field->getParent());
  3829. unsigned CharWidth = getContext().getCharWidth();
  3830. if (FieldTBAAInfo.BaseType)
  3831. FieldTBAAInfo.Offset +=
  3832. Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
  3833. // Update the final access type and size.
  3834. FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
  3835. FieldTBAAInfo.Size =
  3836. getContext().getTypeSizeInChars(FieldType).getQuantity();
  3837. }
  3838. Address addr = base.getAddress(*this);
  3839. if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
  3840. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  3841. ClassDef->isDynamicClass()) {
  3842. // Getting to any field of dynamic object requires stripping dynamic
  3843. // information provided by invariant.group. This is because accessing
  3844. // fields may leak the real address of dynamic object, which could result
  3845. // in miscompilation when leaked pointer would be compared.
  3846. auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
  3847. addr = Address(stripped, addr.getAlignment());
  3848. }
  3849. }
  3850. unsigned RecordCVR = base.getVRQualifiers();
  3851. if (rec->isUnion()) {
  3852. // For unions, there is no pointer adjustment.
  3853. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  3854. hasAnyVptr(FieldType, getContext()))
  3855. // Because unions can easily skip invariant.barriers, we need to add
  3856. // a barrier every time CXXRecord field with vptr is referenced.
  3857. addr = Builder.CreateLaunderInvariantGroup(addr);
  3858. if (IsInPreservedAIRegion ||
  3859. (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
  3860. // Remember the original union field index
  3861. llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
  3862. rec->getLocation());
  3863. addr = Address(
  3864. Builder.CreatePreserveUnionAccessIndex(
  3865. addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
  3866. addr.getAlignment());
  3867. }
  3868. if (FieldType->isReferenceType())
  3869. addr = Builder.CreateElementBitCast(
  3870. addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
  3871. } else {
  3872. if (!IsInPreservedAIRegion &&
  3873. (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
  3874. // For structs, we GEP to the field that the record layout suggests.
  3875. addr = emitAddrOfFieldStorage(*this, addr, field);
  3876. else
  3877. // Remember the original struct field index
  3878. addr = emitPreserveStructAccess(*this, base, addr, field);
  3879. }
  3880. // If this is a reference field, load the reference right now.
  3881. if (FieldType->isReferenceType()) {
  3882. LValue RefLVal =
  3883. MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
  3884. if (RecordCVR & Qualifiers::Volatile)
  3885. RefLVal.getQuals().addVolatile();
  3886. addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
  3887. // Qualifiers on the struct don't apply to the referencee.
  3888. RecordCVR = 0;
  3889. FieldType = FieldType->getPointeeType();
  3890. }
  3891. // Make sure that the address is pointing to the right type. This is critical
  3892. // for both unions and structs. A union needs a bitcast, a struct element
  3893. // will need a bitcast if the LLVM type laid out doesn't match the desired
  3894. // type.
  3895. addr = Builder.CreateElementBitCast(
  3896. addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
  3897. if (field->hasAttr<AnnotateAttr>())
  3898. addr = EmitFieldAnnotations(field, addr);
  3899. LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
  3900. LV.getQuals().addCVRQualifiers(RecordCVR);
  3901. // __weak attribute on a field is ignored.
  3902. if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
  3903. LV.getQuals().removeObjCGCAttr();
  3904. return LV;
  3905. }
  3906. LValue
  3907. CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
  3908. const FieldDecl *Field) {
  3909. QualType FieldType = Field->getType();
  3910. if (!FieldType->isReferenceType())
  3911. return EmitLValueForField(Base, Field);
  3912. Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
  3913. // Make sure that the address is pointing to the right type.
  3914. llvm::Type *llvmType = ConvertTypeForMem(FieldType);
  3915. V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
  3916. // TODO: Generate TBAA information that describes this access as a structure
  3917. // member access and not just an access to an object of the field's type. This
  3918. // should be similar to what we do in EmitLValueForField().
  3919. LValueBaseInfo BaseInfo = Base.getBaseInfo();
  3920. AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
  3921. LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
  3922. return MakeAddrLValue(V, FieldType, FieldBaseInfo,
  3923. CGM.getTBAAInfoForSubobject(Base, FieldType));
  3924. }
  3925. LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
  3926. if (E->isFileScope()) {
  3927. ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
  3928. return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
  3929. }
  3930. if (E->getType()->isVariablyModifiedType())
  3931. // make sure to emit the VLA size.
  3932. EmitVariablyModifiedType(E->getType());
  3933. Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
  3934. const Expr *InitExpr = E->getInitializer();
  3935. LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
  3936. EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
  3937. /*Init*/ true);
  3938. // Block-scope compound literals are destroyed at the end of the enclosing
  3939. // scope in C.
  3940. if (!getLangOpts().CPlusPlus)
  3941. if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
  3942. pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
  3943. E->getType(), getDestroyer(DtorKind),
  3944. DtorKind & EHCleanup);
  3945. return Result;
  3946. }
  3947. LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
  3948. if (!E->isGLValue())
  3949. // Initializing an aggregate temporary in C++11: T{...}.
  3950. return EmitAggExprToLValue(E);
  3951. // An lvalue initializer list must be initializing a reference.
  3952. assert(E->isTransparent() && "non-transparent glvalue init list");
  3953. return EmitLValue(E->getInit(0));
  3954. }
  3955. /// Emit the operand of a glvalue conditional operator. This is either a glvalue
  3956. /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
  3957. /// LValue is returned and the current block has been terminated.
  3958. static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
  3959. const Expr *Operand) {
  3960. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
  3961. CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
  3962. return None;
  3963. }
  3964. return CGF.EmitLValue(Operand);
  3965. }
  3966. LValue CodeGenFunction::
  3967. EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
  3968. if (!expr->isGLValue()) {
  3969. // ?: here should be an aggregate.
  3970. assert(hasAggregateEvaluationKind(expr->getType()) &&
  3971. "Unexpected conditional operator!");
  3972. return EmitAggExprToLValue(expr);
  3973. }
  3974. OpaqueValueMapping binding(*this, expr);
  3975. const Expr *condExpr = expr->getCond();
  3976. bool CondExprBool;
  3977. if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  3978. const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
  3979. if (!CondExprBool) std::swap(live, dead);
  3980. if (!ContainsLabel(dead)) {
  3981. // If the true case is live, we need to track its region.
  3982. if (CondExprBool)
  3983. incrementProfileCounter(expr);
  3984. // If a throw expression we emit it and return an undefined lvalue
  3985. // because it can't be used.
  3986. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
  3987. EmitCXXThrowExpr(ThrowExpr);
  3988. llvm::Type *ElemTy = ConvertType(dead->getType());
  3989. llvm::Type *Ty = llvm::PointerType::getUnqual(ElemTy);
  3990. return MakeAddrLValue(
  3991. Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
  3992. dead->getType());
  3993. }
  3994. return EmitLValue(live);
  3995. }
  3996. }
  3997. llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
  3998. llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
  3999. llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
  4000. ConditionalEvaluation eval(*this);
  4001. EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
  4002. // Any temporaries created here are conditional.
  4003. EmitBlock(lhsBlock);
  4004. incrementProfileCounter(expr);
  4005. eval.begin(*this);
  4006. Optional<LValue> lhs =
  4007. EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
  4008. eval.end(*this);
  4009. if (lhs && !lhs->isSimple())
  4010. return EmitUnsupportedLValue(expr, "conditional operator");
  4011. lhsBlock = Builder.GetInsertBlock();
  4012. if (lhs)
  4013. Builder.CreateBr(contBlock);
  4014. // Any temporaries created here are conditional.
  4015. EmitBlock(rhsBlock);
  4016. eval.begin(*this);
  4017. Optional<LValue> rhs =
  4018. EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
  4019. eval.end(*this);
  4020. if (rhs && !rhs->isSimple())
  4021. return EmitUnsupportedLValue(expr, "conditional operator");
  4022. rhsBlock = Builder.GetInsertBlock();
  4023. EmitBlock(contBlock);
  4024. if (lhs && rhs) {
  4025. Address lhsAddr = lhs->getAddress(*this);
  4026. Address rhsAddr = rhs->getAddress(*this);
  4027. llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
  4028. phi->addIncoming(lhsAddr.getPointer(), lhsBlock);
  4029. phi->addIncoming(rhsAddr.getPointer(), rhsBlock);
  4030. Address result(phi, lhsAddr.getElementType(),
  4031. std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
  4032. AlignmentSource alignSource =
  4033. std::max(lhs->getBaseInfo().getAlignmentSource(),
  4034. rhs->getBaseInfo().getAlignmentSource());
  4035. TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
  4036. lhs->getTBAAInfo(), rhs->getTBAAInfo());
  4037. return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
  4038. TBAAInfo);
  4039. } else {
  4040. assert((lhs || rhs) &&
  4041. "both operands of glvalue conditional are throw-expressions?");
  4042. return lhs ? *lhs : *rhs;
  4043. }
  4044. }
  4045. /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
  4046. /// type. If the cast is to a reference, we can have the usual lvalue result,
  4047. /// otherwise if a cast is needed by the code generator in an lvalue context,
  4048. /// then it must mean that we need the address of an aggregate in order to
  4049. /// access one of its members. This can happen for all the reasons that casts
  4050. /// are permitted with aggregate result, including noop aggregate casts, and
  4051. /// cast from scalar to union.
  4052. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
  4053. switch (E->getCastKind()) {
  4054. case CK_ToVoid:
  4055. case CK_BitCast:
  4056. case CK_LValueToRValueBitCast:
  4057. case CK_ArrayToPointerDecay:
  4058. case CK_FunctionToPointerDecay:
  4059. case CK_NullToMemberPointer:
  4060. case CK_NullToPointer:
  4061. case CK_IntegralToPointer:
  4062. case CK_PointerToIntegral:
  4063. case CK_PointerToBoolean:
  4064. case CK_VectorSplat:
  4065. case CK_IntegralCast:
  4066. case CK_BooleanToSignedIntegral:
  4067. case CK_IntegralToBoolean:
  4068. case CK_IntegralToFloating:
  4069. case CK_FloatingToIntegral:
  4070. case CK_FloatingToBoolean:
  4071. case CK_FloatingCast:
  4072. case CK_FloatingRealToComplex:
  4073. case CK_FloatingComplexToReal:
  4074. case CK_FloatingComplexToBoolean:
  4075. case CK_FloatingComplexCast:
  4076. case CK_FloatingComplexToIntegralComplex:
  4077. case CK_IntegralRealToComplex:
  4078. case CK_IntegralComplexToReal:
  4079. case CK_IntegralComplexToBoolean:
  4080. case CK_IntegralComplexCast:
  4081. case CK_IntegralComplexToFloatingComplex:
  4082. case CK_DerivedToBaseMemberPointer:
  4083. case CK_BaseToDerivedMemberPointer:
  4084. case CK_MemberPointerToBoolean:
  4085. case CK_ReinterpretMemberPointer:
  4086. case CK_AnyPointerToBlockPointerCast:
  4087. case CK_ARCProduceObject:
  4088. case CK_ARCConsumeObject:
  4089. case CK_ARCReclaimReturnedObject:
  4090. case CK_ARCExtendBlockObject:
  4091. case CK_CopyAndAutoreleaseBlockObject:
  4092. case CK_IntToOCLSampler:
  4093. case CK_FloatingToFixedPoint:
  4094. case CK_FixedPointToFloating:
  4095. case CK_FixedPointCast:
  4096. case CK_FixedPointToBoolean:
  4097. case CK_FixedPointToIntegral:
  4098. case CK_IntegralToFixedPoint:
  4099. case CK_MatrixCast:
  4100. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  4101. case CK_Dependent:
  4102. llvm_unreachable("dependent cast kind in IR gen!");
  4103. case CK_BuiltinFnToFnPtr:
  4104. llvm_unreachable("builtin functions are handled elsewhere");
  4105. // These are never l-values; just use the aggregate emission code.
  4106. case CK_NonAtomicToAtomic:
  4107. case CK_AtomicToNonAtomic:
  4108. return EmitAggExprToLValue(E);
  4109. case CK_Dynamic: {
  4110. LValue LV = EmitLValue(E->getSubExpr());
  4111. Address V = LV.getAddress(*this);
  4112. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  4113. return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  4114. }
  4115. case CK_ConstructorConversion:
  4116. case CK_UserDefinedConversion:
  4117. case CK_CPointerToObjCPointerCast:
  4118. case CK_BlockPointerToObjCPointerCast:
  4119. case CK_LValueToRValue:
  4120. return EmitLValue(E->getSubExpr());
  4121. case CK_NoOp: {
  4122. // CK_NoOp can model a qualification conversion, which can remove an array
  4123. // bound and change the IR type.
  4124. // FIXME: Once pointee types are removed from IR, remove this.
  4125. LValue LV = EmitLValue(E->getSubExpr());
  4126. if (LV.isSimple()) {
  4127. Address V = LV.getAddress(*this);
  4128. if (V.isValid()) {
  4129. llvm::Type *T = ConvertTypeForMem(E->getType());
  4130. if (V.getElementType() != T)
  4131. LV.setAddress(Builder.CreateElementBitCast(V, T));
  4132. }
  4133. }
  4134. return LV;
  4135. }
  4136. case CK_UncheckedDerivedToBase:
  4137. case CK_DerivedToBase: {
  4138. const auto *DerivedClassTy =
  4139. E->getSubExpr()->getType()->castAs<RecordType>();
  4140. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  4141. LValue LV = EmitLValue(E->getSubExpr());
  4142. Address This = LV.getAddress(*this);
  4143. // Perform the derived-to-base conversion
  4144. Address Base = GetAddressOfBaseClass(
  4145. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  4146. /*NullCheckValue=*/false, E->getExprLoc());
  4147. // TODO: Support accesses to members of base classes in TBAA. For now, we
  4148. // conservatively pretend that the complete object is of the base class
  4149. // type.
  4150. return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
  4151. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  4152. }
  4153. case CK_ToUnion:
  4154. return EmitAggExprToLValue(E);
  4155. case CK_BaseToDerived: {
  4156. const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
  4157. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  4158. LValue LV = EmitLValue(E->getSubExpr());
  4159. // Perform the base-to-derived conversion
  4160. Address Derived = GetAddressOfDerivedClass(
  4161. LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
  4162. /*NullCheckValue=*/false);
  4163. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  4164. // performed and the object is not of the derived type.
  4165. if (sanitizePerformTypeCheck())
  4166. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  4167. Derived.getPointer(), E->getType());
  4168. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  4169. EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
  4170. /*MayBeNull=*/false, CFITCK_DerivedCast,
  4171. E->getBeginLoc());
  4172. return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
  4173. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  4174. }
  4175. case CK_LValueBitCast: {
  4176. // This must be a reinterpret_cast (or c-style equivalent).
  4177. const auto *CE = cast<ExplicitCastExpr>(E);
  4178. CGM.EmitExplicitCastExprType(CE, this);
  4179. LValue LV = EmitLValue(E->getSubExpr());
  4180. Address V = Builder.CreateElementBitCast(
  4181. LV.getAddress(*this),
  4182. ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
  4183. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  4184. EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
  4185. /*MayBeNull=*/false, CFITCK_UnrelatedCast,
  4186. E->getBeginLoc());
  4187. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  4188. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  4189. }
  4190. case CK_AddressSpaceConversion: {
  4191. LValue LV = EmitLValue(E->getSubExpr());
  4192. QualType DestTy = getContext().getPointerType(E->getType());
  4193. llvm::Value *V = getTargetHooks().performAddrSpaceCast(
  4194. *this, LV.getPointer(*this),
  4195. E->getSubExpr()->getType().getAddressSpace(),
  4196. E->getType().getAddressSpace(), ConvertType(DestTy));
  4197. return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()),
  4198. E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
  4199. }
  4200. case CK_ObjCObjectLValueCast: {
  4201. LValue LV = EmitLValue(E->getSubExpr());
  4202. Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
  4203. ConvertType(E->getType()));
  4204. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  4205. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  4206. }
  4207. case CK_ZeroToOCLOpaqueType:
  4208. llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
  4209. }
  4210. llvm_unreachable("Unhandled lvalue cast kind?");
  4211. }
  4212. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  4213. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  4214. return getOrCreateOpaqueLValueMapping(e);
  4215. }
  4216. LValue
  4217. CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
  4218. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  4219. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  4220. it = OpaqueLValues.find(e);
  4221. if (it != OpaqueLValues.end())
  4222. return it->second;
  4223. assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
  4224. return EmitLValue(e->getSourceExpr());
  4225. }
  4226. RValue
  4227. CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
  4228. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  4229. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  4230. it = OpaqueRValues.find(e);
  4231. if (it != OpaqueRValues.end())
  4232. return it->second;
  4233. assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
  4234. return EmitAnyExpr(e->getSourceExpr());
  4235. }
  4236. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  4237. const FieldDecl *FD,
  4238. SourceLocation Loc) {
  4239. QualType FT = FD->getType();
  4240. LValue FieldLV = EmitLValueForField(LV, FD);
  4241. switch (getEvaluationKind(FT)) {
  4242. case TEK_Complex:
  4243. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  4244. case TEK_Aggregate:
  4245. return FieldLV.asAggregateRValue(*this);
  4246. case TEK_Scalar:
  4247. // This routine is used to load fields one-by-one to perform a copy, so
  4248. // don't load reference fields.
  4249. if (FD->getType()->isReferenceType())
  4250. return RValue::get(FieldLV.getPointer(*this));
  4251. // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
  4252. // primitive load.
  4253. if (FieldLV.isBitField())
  4254. return EmitLoadOfLValue(FieldLV, Loc);
  4255. return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
  4256. }
  4257. llvm_unreachable("bad evaluation kind");
  4258. }
  4259. //===--------------------------------------------------------------------===//
  4260. // Expression Emission
  4261. //===--------------------------------------------------------------------===//
  4262. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  4263. ReturnValueSlot ReturnValue) {
  4264. // Builtins never have block type.
  4265. if (E->getCallee()->getType()->isBlockPointerType())
  4266. return EmitBlockCallExpr(E, ReturnValue);
  4267. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  4268. return EmitCXXMemberCallExpr(CE, ReturnValue);
  4269. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  4270. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  4271. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  4272. if (const CXXMethodDecl *MD =
  4273. dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
  4274. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  4275. CGCallee callee = EmitCallee(E->getCallee());
  4276. if (callee.isBuiltin()) {
  4277. return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
  4278. E, ReturnValue);
  4279. }
  4280. if (callee.isPseudoDestructor()) {
  4281. return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
  4282. }
  4283. return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
  4284. }
  4285. /// Emit a CallExpr without considering whether it might be a subclass.
  4286. RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
  4287. ReturnValueSlot ReturnValue) {
  4288. CGCallee Callee = EmitCallee(E->getCallee());
  4289. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
  4290. }
  4291. // Detect the unusual situation where an inline version is shadowed by a
  4292. // non-inline version. In that case we should pick the external one
  4293. // everywhere. That's GCC behavior too.
  4294. static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
  4295. for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
  4296. if (!PD->isInlineBuiltinDeclaration())
  4297. return false;
  4298. return true;
  4299. }
  4300. static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
  4301. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  4302. if (auto builtinID = FD->getBuiltinID()) {
  4303. std::string FDInlineName = (FD->getName() + ".inline").str();
  4304. // When directing calling an inline builtin, call it through it's mangled
  4305. // name to make it clear it's not the actual builtin.
  4306. if (CGF.CurFn->getName() != FDInlineName &&
  4307. OnlyHasInlineBuiltinDeclaration(FD)) {
  4308. llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
  4309. llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
  4310. llvm::Module *M = Fn->getParent();
  4311. llvm::Function *Clone = M->getFunction(FDInlineName);
  4312. if (!Clone) {
  4313. Clone = llvm::Function::Create(Fn->getFunctionType(),
  4314. llvm::GlobalValue::InternalLinkage,
  4315. Fn->getAddressSpace(), FDInlineName, M);
  4316. Clone->addFnAttr(llvm::Attribute::AlwaysInline);
  4317. }
  4318. return CGCallee::forDirect(Clone, GD);
  4319. }
  4320. // Replaceable builtins provide their own implementation of a builtin. If we
  4321. // are in an inline builtin implementation, avoid trivial infinite
  4322. // recursion.
  4323. else
  4324. return CGCallee::forBuiltin(builtinID, FD);
  4325. }
  4326. llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
  4327. if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
  4328. FD->hasAttr<CUDAGlobalAttr>())
  4329. CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
  4330. cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
  4331. return CGCallee::forDirect(CalleePtr, GD);
  4332. }
  4333. CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
  4334. E = E->IgnoreParens();
  4335. // Look through function-to-pointer decay.
  4336. if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4337. if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
  4338. ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
  4339. return EmitCallee(ICE->getSubExpr());
  4340. }
  4341. // Resolve direct calls.
  4342. } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
  4343. if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  4344. return EmitDirectCallee(*this, FD);
  4345. }
  4346. } else if (auto ME = dyn_cast<MemberExpr>(E)) {
  4347. if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
  4348. EmitIgnoredExpr(ME->getBase());
  4349. return EmitDirectCallee(*this, FD);
  4350. }
  4351. // Look through template substitutions.
  4352. } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
  4353. return EmitCallee(NTTP->getReplacement());
  4354. // Treat pseudo-destructor calls differently.
  4355. } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
  4356. return CGCallee::forPseudoDestructor(PDE);
  4357. }
  4358. // Otherwise, we have an indirect reference.
  4359. llvm::Value *calleePtr;
  4360. QualType functionType;
  4361. if (auto ptrType = E->getType()->getAs<PointerType>()) {
  4362. calleePtr = EmitScalarExpr(E);
  4363. functionType = ptrType->getPointeeType();
  4364. } else {
  4365. functionType = E->getType();
  4366. calleePtr = EmitLValue(E).getPointer(*this);
  4367. }
  4368. assert(functionType->isFunctionType());
  4369. GlobalDecl GD;
  4370. if (const auto *VD =
  4371. dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
  4372. GD = GlobalDecl(VD);
  4373. CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
  4374. CGCallee callee(calleeInfo, calleePtr);
  4375. return callee;
  4376. }
  4377. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  4378. // Comma expressions just emit their LHS then their RHS as an l-value.
  4379. if (E->getOpcode() == BO_Comma) {
  4380. EmitIgnoredExpr(E->getLHS());
  4381. EnsureInsertPoint();
  4382. return EmitLValue(E->getRHS());
  4383. }
  4384. if (E->getOpcode() == BO_PtrMemD ||
  4385. E->getOpcode() == BO_PtrMemI)
  4386. return EmitPointerToDataMemberBinaryExpr(E);
  4387. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  4388. // Note that in all of these cases, __block variables need the RHS
  4389. // evaluated first just in case the variable gets moved by the RHS.
  4390. switch (getEvaluationKind(E->getType())) {
  4391. case TEK_Scalar: {
  4392. switch (E->getLHS()->getType().getObjCLifetime()) {
  4393. case Qualifiers::OCL_Strong:
  4394. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  4395. case Qualifiers::OCL_Autoreleasing:
  4396. return EmitARCStoreAutoreleasing(E).first;
  4397. // No reason to do any of these differently.
  4398. case Qualifiers::OCL_None:
  4399. case Qualifiers::OCL_ExplicitNone:
  4400. case Qualifiers::OCL_Weak:
  4401. break;
  4402. }
  4403. RValue RV = EmitAnyExpr(E->getRHS());
  4404. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  4405. if (RV.isScalar())
  4406. EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
  4407. EmitStoreThroughLValue(RV, LV);
  4408. if (getLangOpts().OpenMP)
  4409. CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
  4410. E->getLHS());
  4411. return LV;
  4412. }
  4413. case TEK_Complex:
  4414. return EmitComplexAssignmentLValue(E);
  4415. case TEK_Aggregate:
  4416. return EmitAggExprToLValue(E);
  4417. }
  4418. llvm_unreachable("bad evaluation kind");
  4419. }
  4420. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  4421. RValue RV = EmitCallExpr(E);
  4422. if (!RV.isScalar())
  4423. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4424. AlignmentSource::Decl);
  4425. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  4426. "Can't have a scalar return unless the return type is a "
  4427. "reference type!");
  4428. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4429. }
  4430. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  4431. // FIXME: This shouldn't require another copy.
  4432. return EmitAggExprToLValue(E);
  4433. }
  4434. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  4435. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  4436. && "binding l-value to type which needs a temporary");
  4437. AggValueSlot Slot = CreateAggTemp(E->getType());
  4438. EmitCXXConstructExpr(E, Slot);
  4439. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4440. }
  4441. LValue
  4442. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  4443. return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  4444. }
  4445. Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4446. return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
  4447. ConvertType(E->getType()));
  4448. }
  4449. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  4450. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
  4451. AlignmentSource::Decl);
  4452. }
  4453. LValue
  4454. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  4455. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  4456. Slot.setExternallyDestructed();
  4457. EmitAggExpr(E->getSubExpr(), Slot);
  4458. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
  4459. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4460. }
  4461. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  4462. RValue RV = EmitObjCMessageExpr(E);
  4463. if (!RV.isScalar())
  4464. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4465. AlignmentSource::Decl);
  4466. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  4467. "Can't have a scalar return unless the return type is a "
  4468. "reference type!");
  4469. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4470. }
  4471. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  4472. Address V =
  4473. CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
  4474. return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
  4475. }
  4476. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  4477. const ObjCIvarDecl *Ivar) {
  4478. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  4479. }
  4480. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  4481. llvm::Value *BaseValue,
  4482. const ObjCIvarDecl *Ivar,
  4483. unsigned CVRQualifiers) {
  4484. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  4485. Ivar, CVRQualifiers);
  4486. }
  4487. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  4488. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  4489. llvm::Value *BaseValue = nullptr;
  4490. const Expr *BaseExpr = E->getBase();
  4491. Qualifiers BaseQuals;
  4492. QualType ObjectTy;
  4493. if (E->isArrow()) {
  4494. BaseValue = EmitScalarExpr(BaseExpr);
  4495. ObjectTy = BaseExpr->getType()->getPointeeType();
  4496. BaseQuals = ObjectTy.getQualifiers();
  4497. } else {
  4498. LValue BaseLV = EmitLValue(BaseExpr);
  4499. BaseValue = BaseLV.getPointer(*this);
  4500. ObjectTy = BaseExpr->getType();
  4501. BaseQuals = ObjectTy.getQualifiers();
  4502. }
  4503. LValue LV =
  4504. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  4505. BaseQuals.getCVRQualifiers());
  4506. setObjCGCLValueClass(getContext(), E, LV);
  4507. return LV;
  4508. }
  4509. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  4510. // Can only get l-value for message expression returning aggregate type
  4511. RValue RV = EmitAnyExprToTemp(E);
  4512. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4513. AlignmentSource::Decl);
  4514. }
  4515. RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
  4516. const CallExpr *E, ReturnValueSlot ReturnValue,
  4517. llvm::Value *Chain) {
  4518. // Get the actual function type. The callee type will always be a pointer to
  4519. // function type or a block pointer type.
  4520. assert(CalleeType->isFunctionPointerType() &&
  4521. "Call must have function pointer type!");
  4522. const Decl *TargetDecl =
  4523. OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
  4524. CalleeType = getContext().getCanonicalType(CalleeType);
  4525. auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
  4526. CGCallee Callee = OrigCallee;
  4527. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  4528. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4529. if (llvm::Constant *PrefixSig =
  4530. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  4531. SanitizerScope SanScope(this);
  4532. // Remove any (C++17) exception specifications, to allow calling e.g. a
  4533. // noexcept function through a non-noexcept pointer.
  4534. auto ProtoTy =
  4535. getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
  4536. llvm::Constant *FTRTTIConst =
  4537. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  4538. llvm::Type *PrefixSigType = PrefixSig->getType();
  4539. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  4540. CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
  4541. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4542. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  4543. CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
  4544. llvm::Value *CalleeSigPtr =
  4545. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  4546. llvm::Value *CalleeSig =
  4547. Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
  4548. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  4549. llvm::BasicBlock *Cont = createBasicBlock("cont");
  4550. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  4551. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  4552. EmitBlock(TypeCheck);
  4553. llvm::Value *CalleeRTTIPtr =
  4554. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  4555. llvm::Value *CalleeRTTIEncoded =
  4556. Builder.CreateAlignedLoad(Int32Ty, CalleeRTTIPtr, getPointerAlign());
  4557. llvm::Value *CalleeRTTI =
  4558. DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
  4559. llvm::Value *CalleeRTTIMatch =
  4560. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  4561. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
  4562. EmitCheckTypeDescriptor(CalleeType)};
  4563. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  4564. SanitizerHandler::FunctionTypeMismatch, StaticData,
  4565. {CalleePtr, CalleeRTTI, FTRTTIConst});
  4566. Builder.CreateBr(Cont);
  4567. EmitBlock(Cont);
  4568. }
  4569. }
  4570. const auto *FnType = cast<FunctionType>(PointeeType);
  4571. // If we are checking indirect calls and this call is indirect, check that the
  4572. // function pointer is a member of the bit set for the function type.
  4573. if (SanOpts.has(SanitizerKind::CFIICall) &&
  4574. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4575. SanitizerScope SanScope(this);
  4576. EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
  4577. llvm::Metadata *MD;
  4578. if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
  4579. MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
  4580. else
  4581. MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
  4582. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  4583. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4584. llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
  4585. llvm::Value *TypeTest = Builder.CreateCall(
  4586. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
  4587. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  4588. llvm::Constant *StaticData[] = {
  4589. llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
  4590. EmitCheckSourceLocation(E->getBeginLoc()),
  4591. EmitCheckTypeDescriptor(QualType(FnType, 0)),
  4592. };
  4593. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  4594. EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
  4595. CastedCallee, StaticData);
  4596. } else {
  4597. EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
  4598. SanitizerHandler::CFICheckFail, StaticData,
  4599. {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
  4600. }
  4601. }
  4602. CallArgList Args;
  4603. if (Chain)
  4604. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  4605. CGM.getContext().VoidPtrTy);
  4606. // C++17 requires that we evaluate arguments to a call using assignment syntax
  4607. // right-to-left, and that we evaluate arguments to certain other operators
  4608. // left-to-right. Note that we allow this to override the order dictated by
  4609. // the calling convention on the MS ABI, which means that parameter
  4610. // destruction order is not necessarily reverse construction order.
  4611. // FIXME: Revisit this based on C++ committee response to unimplementability.
  4612. EvaluationOrder Order = EvaluationOrder::Default;
  4613. if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  4614. if (OCE->isAssignmentOp())
  4615. Order = EvaluationOrder::ForceRightToLeft;
  4616. else {
  4617. switch (OCE->getOperator()) {
  4618. case OO_LessLess:
  4619. case OO_GreaterGreater:
  4620. case OO_AmpAmp:
  4621. case OO_PipePipe:
  4622. case OO_Comma:
  4623. case OO_ArrowStar:
  4624. Order = EvaluationOrder::ForceLeftToRight;
  4625. break;
  4626. default:
  4627. break;
  4628. }
  4629. }
  4630. }
  4631. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
  4632. E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
  4633. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  4634. Args, FnType, /*ChainCall=*/Chain);
  4635. // C99 6.5.2.2p6:
  4636. // If the expression that denotes the called function has a type
  4637. // that does not include a prototype, [the default argument
  4638. // promotions are performed]. If the number of arguments does not
  4639. // equal the number of parameters, the behavior is undefined. If
  4640. // the function is defined with a type that includes a prototype,
  4641. // and either the prototype ends with an ellipsis (, ...) or the
  4642. // types of the arguments after promotion are not compatible with
  4643. // the types of the parameters, the behavior is undefined. If the
  4644. // function is defined with a type that does not include a
  4645. // prototype, and the types of the arguments after promotion are
  4646. // not compatible with those of the parameters after promotion,
  4647. // the behavior is undefined [except in some trivial cases].
  4648. // That is, in the general case, we should assume that a call
  4649. // through an unprototyped function type works like a *non-variadic*
  4650. // call. The way we make this work is to cast to the exact type
  4651. // of the promoted arguments.
  4652. //
  4653. // Chain calls use this same code path to add the invisible chain parameter
  4654. // to the function type.
  4655. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  4656. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  4657. int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
  4658. CalleeTy = CalleeTy->getPointerTo(AS);
  4659. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4660. CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
  4661. Callee.setFunctionPointer(CalleePtr);
  4662. }
  4663. // HIP function pointer contains kernel handle when it is used in triple
  4664. // chevron. The kernel stub needs to be loaded from kernel handle and used
  4665. // as callee.
  4666. if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
  4667. isa<CUDAKernelCallExpr>(E) &&
  4668. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4669. llvm::Value *Handle = Callee.getFunctionPointer();
  4670. auto *Cast =
  4671. Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
  4672. auto *Stub = Builder.CreateLoad(Address(Cast, CGM.getPointerAlign()));
  4673. Callee.setFunctionPointer(Stub);
  4674. }
  4675. llvm::CallBase *CallOrInvoke = nullptr;
  4676. RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
  4677. E == MustTailCall, E->getExprLoc());
  4678. // Generate function declaration DISuprogram in order to be used
  4679. // in debug info about call sites.
  4680. if (CGDebugInfo *DI = getDebugInfo()) {
  4681. if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
  4682. FunctionArgList Args;
  4683. QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
  4684. DI->EmitFuncDeclForCallSite(CallOrInvoke,
  4685. DI->getFunctionType(CalleeDecl, ResTy, Args),
  4686. CalleeDecl);
  4687. }
  4688. }
  4689. return Call;
  4690. }
  4691. LValue CodeGenFunction::
  4692. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  4693. Address BaseAddr = Address::invalid();
  4694. if (E->getOpcode() == BO_PtrMemI) {
  4695. BaseAddr = EmitPointerWithAlignment(E->getLHS());
  4696. } else {
  4697. BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
  4698. }
  4699. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  4700. const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
  4701. LValueBaseInfo BaseInfo;
  4702. TBAAAccessInfo TBAAInfo;
  4703. Address MemberAddr =
  4704. EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
  4705. &TBAAInfo);
  4706. return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
  4707. }
  4708. /// Given the address of a temporary variable, produce an r-value of
  4709. /// its type.
  4710. RValue CodeGenFunction::convertTempToRValue(Address addr,
  4711. QualType type,
  4712. SourceLocation loc) {
  4713. LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
  4714. switch (getEvaluationKind(type)) {
  4715. case TEK_Complex:
  4716. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  4717. case TEK_Aggregate:
  4718. return lvalue.asAggregateRValue(*this);
  4719. case TEK_Scalar:
  4720. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  4721. }
  4722. llvm_unreachable("bad evaluation kind");
  4723. }
  4724. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  4725. assert(Val->getType()->isFPOrFPVectorTy());
  4726. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  4727. return;
  4728. llvm::MDBuilder MDHelper(getLLVMContext());
  4729. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  4730. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  4731. }
  4732. namespace {
  4733. struct LValueOrRValue {
  4734. LValue LV;
  4735. RValue RV;
  4736. };
  4737. }
  4738. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  4739. const PseudoObjectExpr *E,
  4740. bool forLValue,
  4741. AggValueSlot slot) {
  4742. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  4743. // Find the result expression, if any.
  4744. const Expr *resultExpr = E->getResultExpr();
  4745. LValueOrRValue result;
  4746. for (PseudoObjectExpr::const_semantics_iterator
  4747. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  4748. const Expr *semantic = *i;
  4749. // If this semantic expression is an opaque value, bind it
  4750. // to the result of its source expression.
  4751. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  4752. // Skip unique OVEs.
  4753. if (ov->isUnique()) {
  4754. assert(ov != resultExpr &&
  4755. "A unique OVE cannot be used as the result expression");
  4756. continue;
  4757. }
  4758. // If this is the result expression, we may need to evaluate
  4759. // directly into the slot.
  4760. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  4761. OVMA opaqueData;
  4762. if (ov == resultExpr && ov->isPRValue() && !forLValue &&
  4763. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  4764. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  4765. LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
  4766. AlignmentSource::Decl);
  4767. opaqueData = OVMA::bind(CGF, ov, LV);
  4768. result.RV = slot.asRValue();
  4769. // Otherwise, emit as normal.
  4770. } else {
  4771. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  4772. // If this is the result, also evaluate the result now.
  4773. if (ov == resultExpr) {
  4774. if (forLValue)
  4775. result.LV = CGF.EmitLValue(ov);
  4776. else
  4777. result.RV = CGF.EmitAnyExpr(ov, slot);
  4778. }
  4779. }
  4780. opaques.push_back(opaqueData);
  4781. // Otherwise, if the expression is the result, evaluate it
  4782. // and remember the result.
  4783. } else if (semantic == resultExpr) {
  4784. if (forLValue)
  4785. result.LV = CGF.EmitLValue(semantic);
  4786. else
  4787. result.RV = CGF.EmitAnyExpr(semantic, slot);
  4788. // Otherwise, evaluate the expression in an ignored context.
  4789. } else {
  4790. CGF.EmitIgnoredExpr(semantic);
  4791. }
  4792. }
  4793. // Unbind all the opaques now.
  4794. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  4795. opaques[i].unbind(CGF);
  4796. return result;
  4797. }
  4798. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  4799. AggValueSlot slot) {
  4800. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  4801. }
  4802. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  4803. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  4804. }