ExprConstant.cpp 513 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  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 file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include <cstring>
  35. #include <functional>
  36. #include "Interp/Context.h"
  37. #include "Interp/Frame.h"
  38. #include "Interp/State.h"
  39. #include "clang/AST/APValue.h"
  40. #include "clang/AST/ASTContext.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/ASTLambda.h"
  43. #include "clang/AST/CXXInheritance.h"
  44. #include "clang/AST/CharUnits.h"
  45. #include "clang/AST/CurrentSourceLocExprScope.h"
  46. #include "clang/AST/Expr.h"
  47. #include "clang/AST/OSLog.h"
  48. #include "clang/AST/OptionalDiagnostic.h"
  49. #include "clang/AST/RecordLayout.h"
  50. #include "clang/AST/StmtVisitor.h"
  51. #include "clang/AST/TypeLoc.h"
  52. #include "clang/Basic/Builtins.h"
  53. #include "clang/Basic/FixedPoint.h"
  54. #include "clang/Basic/TargetInfo.h"
  55. #include "llvm/ADT/Optional.h"
  56. #include "llvm/ADT/SmallBitVector.h"
  57. #include "llvm/Support/SaveAndRestore.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #define DEBUG_TYPE "exprconstant"
  60. using namespace clang;
  61. using llvm::APInt;
  62. using llvm::APSInt;
  63. using llvm::APFloat;
  64. using llvm::Optional;
  65. namespace {
  66. struct LValue;
  67. class CallStackFrame;
  68. class EvalInfo;
  69. using SourceLocExprScopeGuard =
  70. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  71. static QualType getType(APValue::LValueBase B) {
  72. if (!B) return QualType();
  73. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  74. // FIXME: It's unclear where we're supposed to take the type from, and
  75. // this actually matters for arrays of unknown bound. Eg:
  76. //
  77. // extern int arr[]; void f() { extern int arr[3]; };
  78. // constexpr int *p = &arr[1]; // valid?
  79. //
  80. // For now, we take the array bound from the most recent declaration.
  81. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  82. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  83. QualType T = Redecl->getType();
  84. if (!T->isIncompleteArrayType())
  85. return T;
  86. }
  87. return D->getType();
  88. }
  89. if (B.is<TypeInfoLValue>())
  90. return B.getTypeInfoType();
  91. if (B.is<DynamicAllocLValue>())
  92. return B.getDynamicAllocType();
  93. const Expr *Base = B.get<const Expr*>();
  94. // For a materialized temporary, the type of the temporary we materialized
  95. // may not be the type of the expression.
  96. if (const MaterializeTemporaryExpr *MTE =
  97. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  98. SmallVector<const Expr *, 2> CommaLHSs;
  99. SmallVector<SubobjectAdjustment, 2> Adjustments;
  100. const Expr *Temp = MTE->GetTemporaryExpr();
  101. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  102. Adjustments);
  103. // Keep any cv-qualifiers from the reference if we generated a temporary
  104. // for it directly. Otherwise use the type after adjustment.
  105. if (!Adjustments.empty())
  106. return Inner->getType();
  107. }
  108. return Base->getType();
  109. }
  110. /// Get an LValue path entry, which is known to not be an array index, as a
  111. /// field declaration.
  112. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  113. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  114. }
  115. /// Get an LValue path entry, which is known to not be an array index, as a
  116. /// base class declaration.
  117. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  118. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  119. }
  120. /// Determine whether this LValue path entry for a base class names a virtual
  121. /// base class.
  122. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  123. return E.getAsBaseOrMember().getInt();
  124. }
  125. /// Given an expression, determine the type used to store the result of
  126. /// evaluating that expression.
  127. static QualType getStorageType(ASTContext &Ctx, Expr *E) {
  128. if (E->isRValue())
  129. return E->getType();
  130. return Ctx.getLValueReferenceType(E->getType());
  131. }
  132. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  133. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  134. const FunctionDecl *Callee = CE->getDirectCallee();
  135. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  136. }
  137. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  138. /// This will look through a single cast.
  139. ///
  140. /// Returns null if we couldn't unwrap a function with alloc_size.
  141. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  142. if (!E->getType()->isPointerType())
  143. return nullptr;
  144. E = E->IgnoreParens();
  145. // If we're doing a variable assignment from e.g. malloc(N), there will
  146. // probably be a cast of some kind. In exotic cases, we might also see a
  147. // top-level ExprWithCleanups. Ignore them either way.
  148. if (const auto *FE = dyn_cast<FullExpr>(E))
  149. E = FE->getSubExpr()->IgnoreParens();
  150. if (const auto *Cast = dyn_cast<CastExpr>(E))
  151. E = Cast->getSubExpr()->IgnoreParens();
  152. if (const auto *CE = dyn_cast<CallExpr>(E))
  153. return getAllocSizeAttr(CE) ? CE : nullptr;
  154. return nullptr;
  155. }
  156. /// Determines whether or not the given Base contains a call to a function
  157. /// with the alloc_size attribute.
  158. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  159. const auto *E = Base.dyn_cast<const Expr *>();
  160. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  161. }
  162. /// The bound to claim that an array of unknown bound has.
  163. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  164. /// to an arbitrary value that's likely to loudly break things if it's used.
  165. static const uint64_t AssumedSizeForUnsizedArray =
  166. std::numeric_limits<uint64_t>::max() / 2;
  167. /// Determines if an LValue with the given LValueBase will have an unsized
  168. /// array in its designator.
  169. /// Find the path length and type of the most-derived subobject in the given
  170. /// path, and find the size of the containing array, if any.
  171. static unsigned
  172. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  173. ArrayRef<APValue::LValuePathEntry> Path,
  174. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  175. bool &FirstEntryIsUnsizedArray) {
  176. // This only accepts LValueBases from APValues, and APValues don't support
  177. // arrays that lack size info.
  178. assert(!isBaseAnAllocSizeCall(Base) &&
  179. "Unsized arrays shouldn't appear here");
  180. unsigned MostDerivedLength = 0;
  181. Type = getType(Base);
  182. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  183. if (Type->isArrayType()) {
  184. const ArrayType *AT = Ctx.getAsArrayType(Type);
  185. Type = AT->getElementType();
  186. MostDerivedLength = I + 1;
  187. IsArray = true;
  188. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  189. ArraySize = CAT->getSize().getZExtValue();
  190. } else {
  191. assert(I == 0 && "unexpected unsized array designator");
  192. FirstEntryIsUnsizedArray = true;
  193. ArraySize = AssumedSizeForUnsizedArray;
  194. }
  195. } else if (Type->isAnyComplexType()) {
  196. const ComplexType *CT = Type->castAs<ComplexType>();
  197. Type = CT->getElementType();
  198. ArraySize = 2;
  199. MostDerivedLength = I + 1;
  200. IsArray = true;
  201. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  202. Type = FD->getType();
  203. ArraySize = 0;
  204. MostDerivedLength = I + 1;
  205. IsArray = false;
  206. } else {
  207. // Path[I] describes a base class.
  208. ArraySize = 0;
  209. IsArray = false;
  210. }
  211. }
  212. return MostDerivedLength;
  213. }
  214. /// A path from a glvalue to a subobject of that glvalue.
  215. struct SubobjectDesignator {
  216. /// True if the subobject was named in a manner not supported by C++11. Such
  217. /// lvalues can still be folded, but they are not core constant expressions
  218. /// and we cannot perform lvalue-to-rvalue conversions on them.
  219. unsigned Invalid : 1;
  220. /// Is this a pointer one past the end of an object?
  221. unsigned IsOnePastTheEnd : 1;
  222. /// Indicator of whether the first entry is an unsized array.
  223. unsigned FirstEntryIsAnUnsizedArray : 1;
  224. /// Indicator of whether the most-derived object is an array element.
  225. unsigned MostDerivedIsArrayElement : 1;
  226. /// The length of the path to the most-derived object of which this is a
  227. /// subobject.
  228. unsigned MostDerivedPathLength : 28;
  229. /// The size of the array of which the most-derived object is an element.
  230. /// This will always be 0 if the most-derived object is not an array
  231. /// element. 0 is not an indicator of whether or not the most-derived object
  232. /// is an array, however, because 0-length arrays are allowed.
  233. ///
  234. /// If the current array is an unsized array, the value of this is
  235. /// undefined.
  236. uint64_t MostDerivedArraySize;
  237. /// The type of the most derived object referred to by this address.
  238. QualType MostDerivedType;
  239. typedef APValue::LValuePathEntry PathEntry;
  240. /// The entries on the path from the glvalue to the designated subobject.
  241. SmallVector<PathEntry, 8> Entries;
  242. SubobjectDesignator() : Invalid(true) {}
  243. explicit SubobjectDesignator(QualType T)
  244. : Invalid(false), IsOnePastTheEnd(false),
  245. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  246. MostDerivedPathLength(0), MostDerivedArraySize(0),
  247. MostDerivedType(T) {}
  248. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  249. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  250. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  251. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  252. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  253. if (!Invalid) {
  254. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  255. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  256. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  257. if (V.getLValueBase()) {
  258. bool IsArray = false;
  259. bool FirstIsUnsizedArray = false;
  260. MostDerivedPathLength = findMostDerivedSubobject(
  261. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  262. MostDerivedType, IsArray, FirstIsUnsizedArray);
  263. MostDerivedIsArrayElement = IsArray;
  264. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  265. }
  266. }
  267. }
  268. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  269. unsigned NewLength) {
  270. if (Invalid)
  271. return;
  272. assert(Base && "cannot truncate path for null pointer");
  273. assert(NewLength <= Entries.size() && "not a truncation");
  274. if (NewLength == Entries.size())
  275. return;
  276. Entries.resize(NewLength);
  277. bool IsArray = false;
  278. bool FirstIsUnsizedArray = false;
  279. MostDerivedPathLength = findMostDerivedSubobject(
  280. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  281. FirstIsUnsizedArray);
  282. MostDerivedIsArrayElement = IsArray;
  283. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  284. }
  285. void setInvalid() {
  286. Invalid = true;
  287. Entries.clear();
  288. }
  289. /// Determine whether the most derived subobject is an array without a
  290. /// known bound.
  291. bool isMostDerivedAnUnsizedArray() const {
  292. assert(!Invalid && "Calling this makes no sense on invalid designators");
  293. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  294. }
  295. /// Determine what the most derived array's size is. Results in an assertion
  296. /// failure if the most derived array lacks a size.
  297. uint64_t getMostDerivedArraySize() const {
  298. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  299. return MostDerivedArraySize;
  300. }
  301. /// Determine whether this is a one-past-the-end pointer.
  302. bool isOnePastTheEnd() const {
  303. assert(!Invalid);
  304. if (IsOnePastTheEnd)
  305. return true;
  306. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  307. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  308. MostDerivedArraySize)
  309. return true;
  310. return false;
  311. }
  312. /// Get the range of valid index adjustments in the form
  313. /// {maximum value that can be subtracted from this pointer,
  314. /// maximum value that can be added to this pointer}
  315. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  316. if (Invalid || isMostDerivedAnUnsizedArray())
  317. return {0, 0};
  318. // [expr.add]p4: For the purposes of these operators, a pointer to a
  319. // nonarray object behaves the same as a pointer to the first element of
  320. // an array of length one with the type of the object as its element type.
  321. bool IsArray = MostDerivedPathLength == Entries.size() &&
  322. MostDerivedIsArrayElement;
  323. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  324. : (uint64_t)IsOnePastTheEnd;
  325. uint64_t ArraySize =
  326. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  327. return {ArrayIndex, ArraySize - ArrayIndex};
  328. }
  329. /// Check that this refers to a valid subobject.
  330. bool isValidSubobject() const {
  331. if (Invalid)
  332. return false;
  333. return !isOnePastTheEnd();
  334. }
  335. /// Check that this refers to a valid subobject, and if not, produce a
  336. /// relevant diagnostic and set the designator as invalid.
  337. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  338. /// Get the type of the designated object.
  339. QualType getType(ASTContext &Ctx) const {
  340. assert(!Invalid && "invalid designator has no subobject type");
  341. return MostDerivedPathLength == Entries.size()
  342. ? MostDerivedType
  343. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  344. }
  345. /// Update this designator to refer to the first element within this array.
  346. void addArrayUnchecked(const ConstantArrayType *CAT) {
  347. Entries.push_back(PathEntry::ArrayIndex(0));
  348. // This is a most-derived object.
  349. MostDerivedType = CAT->getElementType();
  350. MostDerivedIsArrayElement = true;
  351. MostDerivedArraySize = CAT->getSize().getZExtValue();
  352. MostDerivedPathLength = Entries.size();
  353. }
  354. /// Update this designator to refer to the first element within the array of
  355. /// elements of type T. This is an array of unknown size.
  356. void addUnsizedArrayUnchecked(QualType ElemTy) {
  357. Entries.push_back(PathEntry::ArrayIndex(0));
  358. MostDerivedType = ElemTy;
  359. MostDerivedIsArrayElement = true;
  360. // The value in MostDerivedArraySize is undefined in this case. So, set it
  361. // to an arbitrary value that's likely to loudly break things if it's
  362. // used.
  363. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  364. MostDerivedPathLength = Entries.size();
  365. }
  366. /// Update this designator to refer to the given base or member of this
  367. /// object.
  368. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  369. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  370. // If this isn't a base class, it's a new most-derived object.
  371. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  372. MostDerivedType = FD->getType();
  373. MostDerivedIsArrayElement = false;
  374. MostDerivedArraySize = 0;
  375. MostDerivedPathLength = Entries.size();
  376. }
  377. }
  378. /// Update this designator to refer to the given complex component.
  379. void addComplexUnchecked(QualType EltTy, bool Imag) {
  380. Entries.push_back(PathEntry::ArrayIndex(Imag));
  381. // This is technically a most-derived object, though in practice this
  382. // is unlikely to matter.
  383. MostDerivedType = EltTy;
  384. MostDerivedIsArrayElement = true;
  385. MostDerivedArraySize = 2;
  386. MostDerivedPathLength = Entries.size();
  387. }
  388. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  389. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  390. const APSInt &N);
  391. /// Add N to the address of this subobject.
  392. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  393. if (Invalid || !N) return;
  394. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  395. if (isMostDerivedAnUnsizedArray()) {
  396. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  397. // Can't verify -- trust that the user is doing the right thing (or if
  398. // not, trust that the caller will catch the bad behavior).
  399. // FIXME: Should we reject if this overflows, at least?
  400. Entries.back() = PathEntry::ArrayIndex(
  401. Entries.back().getAsArrayIndex() + TruncatedN);
  402. return;
  403. }
  404. // [expr.add]p4: For the purposes of these operators, a pointer to a
  405. // nonarray object behaves the same as a pointer to the first element of
  406. // an array of length one with the type of the object as its element type.
  407. bool IsArray = MostDerivedPathLength == Entries.size() &&
  408. MostDerivedIsArrayElement;
  409. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  410. : (uint64_t)IsOnePastTheEnd;
  411. uint64_t ArraySize =
  412. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  413. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  414. // Calculate the actual index in a wide enough type, so we can include
  415. // it in the note.
  416. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  417. (llvm::APInt&)N += ArrayIndex;
  418. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  419. diagnosePointerArithmetic(Info, E, N);
  420. setInvalid();
  421. return;
  422. }
  423. ArrayIndex += TruncatedN;
  424. assert(ArrayIndex <= ArraySize &&
  425. "bounds check succeeded for out-of-bounds index");
  426. if (IsArray)
  427. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  428. else
  429. IsOnePastTheEnd = (ArrayIndex != 0);
  430. }
  431. };
  432. /// A stack frame in the constexpr call stack.
  433. class CallStackFrame : public interp::Frame {
  434. public:
  435. EvalInfo &Info;
  436. /// Parent - The caller of this stack frame.
  437. CallStackFrame *Caller;
  438. /// Callee - The function which was called.
  439. const FunctionDecl *Callee;
  440. /// This - The binding for the this pointer in this call, if any.
  441. const LValue *This;
  442. /// Arguments - Parameter bindings for this function call, indexed by
  443. /// parameters' function scope indices.
  444. APValue *Arguments;
  445. /// Source location information about the default argument or default
  446. /// initializer expression we're evaluating, if any.
  447. CurrentSourceLocExprScope CurSourceLocExprScope;
  448. // Note that we intentionally use std::map here so that references to
  449. // values are stable.
  450. typedef std::pair<const void *, unsigned> MapKeyTy;
  451. typedef std::map<MapKeyTy, APValue> MapTy;
  452. /// Temporaries - Temporary lvalues materialized within this stack frame.
  453. MapTy Temporaries;
  454. /// CallLoc - The location of the call expression for this call.
  455. SourceLocation CallLoc;
  456. /// Index - The call index of this call.
  457. unsigned Index;
  458. /// The stack of integers for tracking version numbers for temporaries.
  459. SmallVector<unsigned, 2> TempVersionStack = {1};
  460. unsigned CurTempVersion = TempVersionStack.back();
  461. unsigned getTempVersion() const { return TempVersionStack.back(); }
  462. void pushTempVersion() {
  463. TempVersionStack.push_back(++CurTempVersion);
  464. }
  465. void popTempVersion() {
  466. TempVersionStack.pop_back();
  467. }
  468. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  469. // on the overall stack usage of deeply-recursing constexpr evaluations.
  470. // (We should cache this map rather than recomputing it repeatedly.)
  471. // But let's try this and see how it goes; we can look into caching the map
  472. // as a later change.
  473. /// LambdaCaptureFields - Mapping from captured variables/this to
  474. /// corresponding data members in the closure class.
  475. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  476. FieldDecl *LambdaThisCaptureField;
  477. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  478. const FunctionDecl *Callee, const LValue *This,
  479. APValue *Arguments);
  480. ~CallStackFrame();
  481. // Return the temporary for Key whose version number is Version.
  482. APValue *getTemporary(const void *Key, unsigned Version) {
  483. MapKeyTy KV(Key, Version);
  484. auto LB = Temporaries.lower_bound(KV);
  485. if (LB != Temporaries.end() && LB->first == KV)
  486. return &LB->second;
  487. // Pair (Key,Version) wasn't found in the map. Check that no elements
  488. // in the map have 'Key' as their key.
  489. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  490. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  491. "Element with key 'Key' found in map");
  492. return nullptr;
  493. }
  494. // Return the current temporary for Key in the map.
  495. APValue *getCurrentTemporary(const void *Key) {
  496. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  497. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  498. return &std::prev(UB)->second;
  499. return nullptr;
  500. }
  501. // Return the version number of the current temporary for Key.
  502. unsigned getCurrentTemporaryVersion(const void *Key) const {
  503. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  504. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  505. return std::prev(UB)->first.second;
  506. return 0;
  507. }
  508. /// Allocate storage for an object of type T in this stack frame.
  509. /// Populates LV with a handle to the created object. Key identifies
  510. /// the temporary within the stack frame, and must not be reused without
  511. /// bumping the temporary version number.
  512. template<typename KeyT>
  513. APValue &createTemporary(const KeyT *Key, QualType T,
  514. bool IsLifetimeExtended, LValue &LV);
  515. void describe(llvm::raw_ostream &OS) override;
  516. Frame *getCaller() const override { return Caller; }
  517. SourceLocation getCallLocation() const override { return CallLoc; }
  518. const FunctionDecl *getCallee() const override { return Callee; }
  519. bool isStdFunction() const {
  520. for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
  521. if (DC->isStdNamespace())
  522. return true;
  523. return false;
  524. }
  525. };
  526. /// Temporarily override 'this'.
  527. class ThisOverrideRAII {
  528. public:
  529. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  530. : Frame(Frame), OldThis(Frame.This) {
  531. if (Enable)
  532. Frame.This = NewThis;
  533. }
  534. ~ThisOverrideRAII() {
  535. Frame.This = OldThis;
  536. }
  537. private:
  538. CallStackFrame &Frame;
  539. const LValue *OldThis;
  540. };
  541. }
  542. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  543. const LValue &This, QualType ThisType);
  544. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  545. APValue::LValueBase LVBase, APValue &Value,
  546. QualType T);
  547. namespace {
  548. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  549. class Cleanup {
  550. llvm::PointerIntPair<APValue*, 1, bool> Value;
  551. APValue::LValueBase Base;
  552. QualType T;
  553. public:
  554. Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
  555. bool IsLifetimeExtended)
  556. : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
  557. bool isLifetimeExtended() const { return Value.getInt(); }
  558. bool endLifetime(EvalInfo &Info, bool RunDestructors) {
  559. if (RunDestructors) {
  560. SourceLocation Loc;
  561. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  562. Loc = VD->getLocation();
  563. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  564. Loc = E->getExprLoc();
  565. return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
  566. }
  567. *Value.getPointer() = APValue();
  568. return true;
  569. }
  570. bool hasSideEffect() {
  571. return T.isDestructedType();
  572. }
  573. };
  574. /// A reference to an object whose construction we are currently evaluating.
  575. struct ObjectUnderConstruction {
  576. APValue::LValueBase Base;
  577. ArrayRef<APValue::LValuePathEntry> Path;
  578. friend bool operator==(const ObjectUnderConstruction &LHS,
  579. const ObjectUnderConstruction &RHS) {
  580. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  581. }
  582. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  583. return llvm::hash_combine(Obj.Base, Obj.Path);
  584. }
  585. };
  586. enum class ConstructionPhase {
  587. None,
  588. Bases,
  589. AfterBases,
  590. Destroying,
  591. DestroyingBases
  592. };
  593. }
  594. namespace llvm {
  595. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  596. using Base = DenseMapInfo<APValue::LValueBase>;
  597. static ObjectUnderConstruction getEmptyKey() {
  598. return {Base::getEmptyKey(), {}}; }
  599. static ObjectUnderConstruction getTombstoneKey() {
  600. return {Base::getTombstoneKey(), {}};
  601. }
  602. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  603. return hash_value(Object);
  604. }
  605. static bool isEqual(const ObjectUnderConstruction &LHS,
  606. const ObjectUnderConstruction &RHS) {
  607. return LHS == RHS;
  608. }
  609. };
  610. }
  611. namespace {
  612. /// A dynamically-allocated heap object.
  613. struct DynAlloc {
  614. /// The value of this heap-allocated object.
  615. APValue Value;
  616. /// The allocating expression; used for diagnostics. Either a CXXNewExpr
  617. /// or a CallExpr (the latter is for direct calls to operator new inside
  618. /// std::allocator<T>::allocate).
  619. const Expr *AllocExpr = nullptr;
  620. enum Kind {
  621. New,
  622. ArrayNew,
  623. StdAllocator
  624. };
  625. /// Get the kind of the allocation. This must match between allocation
  626. /// and deallocation.
  627. Kind getKind() const {
  628. if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
  629. return NE->isArray() ? ArrayNew : New;
  630. assert(isa<CallExpr>(AllocExpr));
  631. return StdAllocator;
  632. }
  633. };
  634. struct DynAllocOrder {
  635. bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
  636. return L.getIndex() < R.getIndex();
  637. }
  638. };
  639. /// EvalInfo - This is a private struct used by the evaluator to capture
  640. /// information about a subexpression as it is folded. It retains information
  641. /// about the AST context, but also maintains information about the folded
  642. /// expression.
  643. ///
  644. /// If an expression could be evaluated, it is still possible it is not a C
  645. /// "integer constant expression" or constant expression. If not, this struct
  646. /// captures information about how and why not.
  647. ///
  648. /// One bit of information passed *into* the request for constant folding
  649. /// indicates whether the subexpression is "evaluated" or not according to C
  650. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  651. /// evaluate the expression regardless of what the RHS is, but C only allows
  652. /// certain things in certain situations.
  653. class EvalInfo : public interp::State {
  654. public:
  655. ASTContext &Ctx;
  656. /// EvalStatus - Contains information about the evaluation.
  657. Expr::EvalStatus &EvalStatus;
  658. /// CurrentCall - The top of the constexpr call stack.
  659. CallStackFrame *CurrentCall;
  660. /// CallStackDepth - The number of calls in the call stack right now.
  661. unsigned CallStackDepth;
  662. /// NextCallIndex - The next call index to assign.
  663. unsigned NextCallIndex;
  664. /// StepsLeft - The remaining number of evaluation steps we're permitted
  665. /// to perform. This is essentially a limit for the number of statements
  666. /// we will evaluate.
  667. unsigned StepsLeft;
  668. /// Force the use of the experimental new constant interpreter, bailing out
  669. /// with an error if a feature is not supported.
  670. bool ForceNewConstInterp;
  671. /// Enable the experimental new constant interpreter.
  672. bool EnableNewConstInterp;
  673. /// BottomFrame - The frame in which evaluation started. This must be
  674. /// initialized after CurrentCall and CallStackDepth.
  675. CallStackFrame BottomFrame;
  676. /// A stack of values whose lifetimes end at the end of some surrounding
  677. /// evaluation frame.
  678. llvm::SmallVector<Cleanup, 16> CleanupStack;
  679. /// EvaluatingDecl - This is the declaration whose initializer is being
  680. /// evaluated, if any.
  681. APValue::LValueBase EvaluatingDecl;
  682. enum class EvaluatingDeclKind {
  683. None,
  684. /// We're evaluating the construction of EvaluatingDecl.
  685. Ctor,
  686. /// We're evaluating the destruction of EvaluatingDecl.
  687. Dtor,
  688. };
  689. EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
  690. /// EvaluatingDeclValue - This is the value being constructed for the
  691. /// declaration whose initializer is being evaluated, if any.
  692. APValue *EvaluatingDeclValue;
  693. /// Set of objects that are currently being constructed.
  694. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  695. ObjectsUnderConstruction;
  696. /// Current heap allocations, along with the location where each was
  697. /// allocated. We use std::map here because we need stable addresses
  698. /// for the stored APValues.
  699. std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
  700. /// The number of heap allocations performed so far in this evaluation.
  701. unsigned NumHeapAllocs = 0;
  702. struct EvaluatingConstructorRAII {
  703. EvalInfo &EI;
  704. ObjectUnderConstruction Object;
  705. bool DidInsert;
  706. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  707. bool HasBases)
  708. : EI(EI), Object(Object) {
  709. DidInsert =
  710. EI.ObjectsUnderConstruction
  711. .insert({Object, HasBases ? ConstructionPhase::Bases
  712. : ConstructionPhase::AfterBases})
  713. .second;
  714. }
  715. void finishedConstructingBases() {
  716. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  717. }
  718. ~EvaluatingConstructorRAII() {
  719. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  720. }
  721. };
  722. struct EvaluatingDestructorRAII {
  723. EvalInfo &EI;
  724. ObjectUnderConstruction Object;
  725. bool DidInsert;
  726. EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
  727. : EI(EI), Object(Object) {
  728. DidInsert = EI.ObjectsUnderConstruction
  729. .insert({Object, ConstructionPhase::Destroying})
  730. .second;
  731. }
  732. void startedDestroyingBases() {
  733. EI.ObjectsUnderConstruction[Object] =
  734. ConstructionPhase::DestroyingBases;
  735. }
  736. ~EvaluatingDestructorRAII() {
  737. if (DidInsert)
  738. EI.ObjectsUnderConstruction.erase(Object);
  739. }
  740. };
  741. ConstructionPhase
  742. isEvaluatingCtorDtor(APValue::LValueBase Base,
  743. ArrayRef<APValue::LValuePathEntry> Path) {
  744. return ObjectsUnderConstruction.lookup({Base, Path});
  745. }
  746. /// If we're currently speculatively evaluating, the outermost call stack
  747. /// depth at which we can mutate state, otherwise 0.
  748. unsigned SpeculativeEvaluationDepth = 0;
  749. /// The current array initialization index, if we're performing array
  750. /// initialization.
  751. uint64_t ArrayInitIndex = -1;
  752. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  753. /// notes attached to it will also be stored, otherwise they will not be.
  754. bool HasActiveDiagnostic;
  755. /// Have we emitted a diagnostic explaining why we couldn't constant
  756. /// fold (not just why it's not strictly a constant expression)?
  757. bool HasFoldFailureDiagnostic;
  758. /// Whether or not we're in a context where the front end requires a
  759. /// constant value.
  760. bool InConstantContext;
  761. /// Whether we're checking that an expression is a potential constant
  762. /// expression. If so, do not fail on constructs that could become constant
  763. /// later on (such as a use of an undefined global).
  764. bool CheckingPotentialConstantExpression = false;
  765. /// Whether we're checking for an expression that has undefined behavior.
  766. /// If so, we will produce warnings if we encounter an operation that is
  767. /// always undefined.
  768. bool CheckingForUndefinedBehavior = false;
  769. enum EvaluationMode {
  770. /// Evaluate as a constant expression. Stop if we find that the expression
  771. /// is not a constant expression.
  772. EM_ConstantExpression,
  773. /// Evaluate as a constant expression. Stop if we find that the expression
  774. /// is not a constant expression. Some expressions can be retried in the
  775. /// optimizer if we don't constant fold them here, but in an unevaluated
  776. /// context we try to fold them immediately since the optimizer never
  777. /// gets a chance to look at it.
  778. EM_ConstantExpressionUnevaluated,
  779. /// Fold the expression to a constant. Stop if we hit a side-effect that
  780. /// we can't model.
  781. EM_ConstantFold,
  782. /// Evaluate in any way we know how. Don't worry about side-effects that
  783. /// can't be modeled.
  784. EM_IgnoreSideEffects,
  785. } EvalMode;
  786. /// Are we checking whether the expression is a potential constant
  787. /// expression?
  788. bool checkingPotentialConstantExpression() const override {
  789. return CheckingPotentialConstantExpression;
  790. }
  791. /// Are we checking an expression for overflow?
  792. // FIXME: We should check for any kind of undefined or suspicious behavior
  793. // in such constructs, not just overflow.
  794. bool checkingForUndefinedBehavior() const override {
  795. return CheckingForUndefinedBehavior;
  796. }
  797. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  798. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  799. CallStackDepth(0), NextCallIndex(1),
  800. StepsLeft(getLangOpts().ConstexprStepLimit),
  801. ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
  802. EnableNewConstInterp(ForceNewConstInterp ||
  803. getLangOpts().EnableNewConstInterp),
  804. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  805. EvaluatingDecl((const ValueDecl *)nullptr),
  806. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  807. HasFoldFailureDiagnostic(false), InConstantContext(false),
  808. EvalMode(Mode) {}
  809. ~EvalInfo() {
  810. discardCleanups();
  811. }
  812. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
  813. EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
  814. EvaluatingDecl = Base;
  815. IsEvaluatingDecl = EDK;
  816. EvaluatingDeclValue = &Value;
  817. }
  818. bool CheckCallLimit(SourceLocation Loc) {
  819. // Don't perform any constexpr calls (other than the call we're checking)
  820. // when checking a potential constant expression.
  821. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  822. return false;
  823. if (NextCallIndex == 0) {
  824. // NextCallIndex has wrapped around.
  825. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  826. return false;
  827. }
  828. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  829. return true;
  830. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  831. << getLangOpts().ConstexprCallDepth;
  832. return false;
  833. }
  834. std::pair<CallStackFrame *, unsigned>
  835. getCallFrameAndDepth(unsigned CallIndex) {
  836. assert(CallIndex && "no call index in getCallFrameAndDepth");
  837. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  838. // be null in this loop.
  839. unsigned Depth = CallStackDepth;
  840. CallStackFrame *Frame = CurrentCall;
  841. while (Frame->Index > CallIndex) {
  842. Frame = Frame->Caller;
  843. --Depth;
  844. }
  845. if (Frame->Index == CallIndex)
  846. return {Frame, Depth};
  847. return {nullptr, 0};
  848. }
  849. bool nextStep(const Stmt *S) {
  850. if (!StepsLeft) {
  851. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  852. return false;
  853. }
  854. --StepsLeft;
  855. return true;
  856. }
  857. APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
  858. Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
  859. Optional<DynAlloc*> Result;
  860. auto It = HeapAllocs.find(DA);
  861. if (It != HeapAllocs.end())
  862. Result = &It->second;
  863. return Result;
  864. }
  865. /// Information about a stack frame for std::allocator<T>::[de]allocate.
  866. struct StdAllocatorCaller {
  867. unsigned FrameIndex;
  868. QualType ElemType;
  869. explicit operator bool() const { return FrameIndex != 0; };
  870. };
  871. StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
  872. for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
  873. Call = Call->Caller) {
  874. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
  875. if (!MD)
  876. continue;
  877. const IdentifierInfo *FnII = MD->getIdentifier();
  878. if (!FnII || !FnII->isStr(FnName))
  879. continue;
  880. const auto *CTSD =
  881. dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
  882. if (!CTSD)
  883. continue;
  884. const IdentifierInfo *ClassII = CTSD->getIdentifier();
  885. const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
  886. if (CTSD->isInStdNamespace() && ClassII &&
  887. ClassII->isStr("allocator") && TAL.size() >= 1 &&
  888. TAL[0].getKind() == TemplateArgument::Type)
  889. return {Call->Index, TAL[0].getAsType()};
  890. }
  891. return {};
  892. }
  893. void performLifetimeExtension() {
  894. // Disable the cleanups for lifetime-extended temporaries.
  895. CleanupStack.erase(
  896. std::remove_if(CleanupStack.begin(), CleanupStack.end(),
  897. [](Cleanup &C) { return C.isLifetimeExtended(); }),
  898. CleanupStack.end());
  899. }
  900. /// Throw away any remaining cleanups at the end of evaluation. If any
  901. /// cleanups would have had a side-effect, note that as an unmodeled
  902. /// side-effect and return false. Otherwise, return true.
  903. bool discardCleanups() {
  904. for (Cleanup &C : CleanupStack)
  905. if (C.hasSideEffect())
  906. if (!noteSideEffect())
  907. return false;
  908. return true;
  909. }
  910. private:
  911. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  912. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  913. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  914. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  915. void setFoldFailureDiagnostic(bool Flag) override {
  916. HasFoldFailureDiagnostic = Flag;
  917. }
  918. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  919. ASTContext &getCtx() const override { return Ctx; }
  920. // If we have a prior diagnostic, it will be noting that the expression
  921. // isn't a constant expression. This diagnostic is more important,
  922. // unless we require this evaluation to produce a constant expression.
  923. //
  924. // FIXME: We might want to show both diagnostics to the user in
  925. // EM_ConstantFold mode.
  926. bool hasPriorDiagnostic() override {
  927. if (!EvalStatus.Diag->empty()) {
  928. switch (EvalMode) {
  929. case EM_ConstantFold:
  930. case EM_IgnoreSideEffects:
  931. if (!HasFoldFailureDiagnostic)
  932. break;
  933. // We've already failed to fold something. Keep that diagnostic.
  934. LLVM_FALLTHROUGH;
  935. case EM_ConstantExpression:
  936. case EM_ConstantExpressionUnevaluated:
  937. setActiveDiagnostic(false);
  938. return true;
  939. }
  940. }
  941. return false;
  942. }
  943. unsigned getCallStackDepth() override { return CallStackDepth; }
  944. public:
  945. /// Should we continue evaluation after encountering a side-effect that we
  946. /// couldn't model?
  947. bool keepEvaluatingAfterSideEffect() {
  948. switch (EvalMode) {
  949. case EM_IgnoreSideEffects:
  950. return true;
  951. case EM_ConstantExpression:
  952. case EM_ConstantExpressionUnevaluated:
  953. case EM_ConstantFold:
  954. // By default, assume any side effect might be valid in some other
  955. // evaluation of this expression from a different context.
  956. return checkingPotentialConstantExpression() ||
  957. checkingForUndefinedBehavior();
  958. }
  959. llvm_unreachable("Missed EvalMode case");
  960. }
  961. /// Note that we have had a side-effect, and determine whether we should
  962. /// keep evaluating.
  963. bool noteSideEffect() {
  964. EvalStatus.HasSideEffects = true;
  965. return keepEvaluatingAfterSideEffect();
  966. }
  967. /// Should we continue evaluation after encountering undefined behavior?
  968. bool keepEvaluatingAfterUndefinedBehavior() {
  969. switch (EvalMode) {
  970. case EM_IgnoreSideEffects:
  971. case EM_ConstantFold:
  972. return true;
  973. case EM_ConstantExpression:
  974. case EM_ConstantExpressionUnevaluated:
  975. return checkingForUndefinedBehavior();
  976. }
  977. llvm_unreachable("Missed EvalMode case");
  978. }
  979. /// Note that we hit something that was technically undefined behavior, but
  980. /// that we can evaluate past it (such as signed overflow or floating-point
  981. /// division by zero.)
  982. bool noteUndefinedBehavior() override {
  983. EvalStatus.HasUndefinedBehavior = true;
  984. return keepEvaluatingAfterUndefinedBehavior();
  985. }
  986. /// Should we continue evaluation as much as possible after encountering a
  987. /// construct which can't be reduced to a value?
  988. bool keepEvaluatingAfterFailure() const override {
  989. if (!StepsLeft)
  990. return false;
  991. switch (EvalMode) {
  992. case EM_ConstantExpression:
  993. case EM_ConstantExpressionUnevaluated:
  994. case EM_ConstantFold:
  995. case EM_IgnoreSideEffects:
  996. return checkingPotentialConstantExpression() ||
  997. checkingForUndefinedBehavior();
  998. }
  999. llvm_unreachable("Missed EvalMode case");
  1000. }
  1001. /// Notes that we failed to evaluate an expression that other expressions
  1002. /// directly depend on, and determine if we should keep evaluating. This
  1003. /// should only be called if we actually intend to keep evaluating.
  1004. ///
  1005. /// Call noteSideEffect() instead if we may be able to ignore the value that
  1006. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  1007. ///
  1008. /// (Foo(), 1) // use noteSideEffect
  1009. /// (Foo() || true) // use noteSideEffect
  1010. /// Foo() + 1 // use noteFailure
  1011. LLVM_NODISCARD bool noteFailure() {
  1012. // Failure when evaluating some expression often means there is some
  1013. // subexpression whose evaluation was skipped. Therefore, (because we
  1014. // don't track whether we skipped an expression when unwinding after an
  1015. // evaluation failure) every evaluation failure that bubbles up from a
  1016. // subexpression implies that a side-effect has potentially happened. We
  1017. // skip setting the HasSideEffects flag to true until we decide to
  1018. // continue evaluating after that point, which happens here.
  1019. bool KeepGoing = keepEvaluatingAfterFailure();
  1020. EvalStatus.HasSideEffects |= KeepGoing;
  1021. return KeepGoing;
  1022. }
  1023. class ArrayInitLoopIndex {
  1024. EvalInfo &Info;
  1025. uint64_t OuterIndex;
  1026. public:
  1027. ArrayInitLoopIndex(EvalInfo &Info)
  1028. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  1029. Info.ArrayInitIndex = 0;
  1030. }
  1031. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  1032. operator uint64_t&() { return Info.ArrayInitIndex; }
  1033. };
  1034. };
  1035. /// Object used to treat all foldable expressions as constant expressions.
  1036. struct FoldConstant {
  1037. EvalInfo &Info;
  1038. bool Enabled;
  1039. bool HadNoPriorDiags;
  1040. EvalInfo::EvaluationMode OldMode;
  1041. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  1042. : Info(Info),
  1043. Enabled(Enabled),
  1044. HadNoPriorDiags(Info.EvalStatus.Diag &&
  1045. Info.EvalStatus.Diag->empty() &&
  1046. !Info.EvalStatus.HasSideEffects),
  1047. OldMode(Info.EvalMode) {
  1048. if (Enabled)
  1049. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1050. }
  1051. void keepDiagnostics() { Enabled = false; }
  1052. ~FoldConstant() {
  1053. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1054. !Info.EvalStatus.HasSideEffects)
  1055. Info.EvalStatus.Diag->clear();
  1056. Info.EvalMode = OldMode;
  1057. }
  1058. };
  1059. /// RAII object used to set the current evaluation mode to ignore
  1060. /// side-effects.
  1061. struct IgnoreSideEffectsRAII {
  1062. EvalInfo &Info;
  1063. EvalInfo::EvaluationMode OldMode;
  1064. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1065. : Info(Info), OldMode(Info.EvalMode) {
  1066. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1067. }
  1068. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1069. };
  1070. /// RAII object used to optionally suppress diagnostics and side-effects from
  1071. /// a speculative evaluation.
  1072. class SpeculativeEvaluationRAII {
  1073. EvalInfo *Info = nullptr;
  1074. Expr::EvalStatus OldStatus;
  1075. unsigned OldSpeculativeEvaluationDepth;
  1076. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1077. Info = Other.Info;
  1078. OldStatus = Other.OldStatus;
  1079. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1080. Other.Info = nullptr;
  1081. }
  1082. void maybeRestoreState() {
  1083. if (!Info)
  1084. return;
  1085. Info->EvalStatus = OldStatus;
  1086. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1087. }
  1088. public:
  1089. SpeculativeEvaluationRAII() = default;
  1090. SpeculativeEvaluationRAII(
  1091. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1092. : Info(&Info), OldStatus(Info.EvalStatus),
  1093. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1094. Info.EvalStatus.Diag = NewDiag;
  1095. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1096. }
  1097. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1098. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1099. moveFromAndCancel(std::move(Other));
  1100. }
  1101. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1102. maybeRestoreState();
  1103. moveFromAndCancel(std::move(Other));
  1104. return *this;
  1105. }
  1106. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1107. };
  1108. /// RAII object wrapping a full-expression or block scope, and handling
  1109. /// the ending of the lifetime of temporaries created within it.
  1110. template<bool IsFullExpression>
  1111. class ScopeRAII {
  1112. EvalInfo &Info;
  1113. unsigned OldStackSize;
  1114. public:
  1115. ScopeRAII(EvalInfo &Info)
  1116. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1117. // Push a new temporary version. This is needed to distinguish between
  1118. // temporaries created in different iterations of a loop.
  1119. Info.CurrentCall->pushTempVersion();
  1120. }
  1121. bool destroy(bool RunDestructors = true) {
  1122. bool OK = cleanup(Info, RunDestructors, OldStackSize);
  1123. OldStackSize = -1U;
  1124. return OK;
  1125. }
  1126. ~ScopeRAII() {
  1127. if (OldStackSize != -1U)
  1128. destroy(false);
  1129. // Body moved to a static method to encourage the compiler to inline away
  1130. // instances of this class.
  1131. Info.CurrentCall->popTempVersion();
  1132. }
  1133. private:
  1134. static bool cleanup(EvalInfo &Info, bool RunDestructors,
  1135. unsigned OldStackSize) {
  1136. assert(OldStackSize <= Info.CleanupStack.size() &&
  1137. "running cleanups out of order?");
  1138. // Run all cleanups for a block scope, and non-lifetime-extended cleanups
  1139. // for a full-expression scope.
  1140. bool Success = true;
  1141. for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
  1142. if (!(IsFullExpression &&
  1143. Info.CleanupStack[I - 1].isLifetimeExtended())) {
  1144. if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
  1145. Success = false;
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. // Compact lifetime-extended cleanups.
  1151. auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
  1152. if (IsFullExpression)
  1153. NewEnd =
  1154. std::remove_if(NewEnd, Info.CleanupStack.end(),
  1155. [](Cleanup &C) { return !C.isLifetimeExtended(); });
  1156. Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
  1157. return Success;
  1158. }
  1159. };
  1160. typedef ScopeRAII<false> BlockScopeRAII;
  1161. typedef ScopeRAII<true> FullExpressionRAII;
  1162. }
  1163. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1164. CheckSubobjectKind CSK) {
  1165. if (Invalid)
  1166. return false;
  1167. if (isOnePastTheEnd()) {
  1168. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1169. << CSK;
  1170. setInvalid();
  1171. return false;
  1172. }
  1173. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1174. // must actually be at least one array element; even a VLA cannot have a
  1175. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1176. return true;
  1177. }
  1178. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1179. const Expr *E) {
  1180. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1181. // Do not set the designator as invalid: we can represent this situation,
  1182. // and correct handling of __builtin_object_size requires us to do so.
  1183. }
  1184. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1185. const Expr *E,
  1186. const APSInt &N) {
  1187. // If we're complaining, we must be able to statically determine the size of
  1188. // the most derived array.
  1189. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1190. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1191. << N << /*array*/ 0
  1192. << static_cast<unsigned>(getMostDerivedArraySize());
  1193. else
  1194. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1195. << N << /*non-array*/ 1;
  1196. setInvalid();
  1197. }
  1198. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1199. const FunctionDecl *Callee, const LValue *This,
  1200. APValue *Arguments)
  1201. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1202. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1203. Info.CurrentCall = this;
  1204. ++Info.CallStackDepth;
  1205. }
  1206. CallStackFrame::~CallStackFrame() {
  1207. assert(Info.CurrentCall == this && "calls retired out of order");
  1208. --Info.CallStackDepth;
  1209. Info.CurrentCall = Caller;
  1210. }
  1211. static bool isRead(AccessKinds AK) {
  1212. return AK == AK_Read || AK == AK_ReadObjectRepresentation;
  1213. }
  1214. static bool isModification(AccessKinds AK) {
  1215. switch (AK) {
  1216. case AK_Read:
  1217. case AK_ReadObjectRepresentation:
  1218. case AK_MemberCall:
  1219. case AK_DynamicCast:
  1220. case AK_TypeId:
  1221. return false;
  1222. case AK_Assign:
  1223. case AK_Increment:
  1224. case AK_Decrement:
  1225. case AK_Construct:
  1226. case AK_Destroy:
  1227. return true;
  1228. }
  1229. llvm_unreachable("unknown access kind");
  1230. }
  1231. static bool isAnyAccess(AccessKinds AK) {
  1232. return isRead(AK) || isModification(AK);
  1233. }
  1234. /// Is this an access per the C++ definition?
  1235. static bool isFormalAccess(AccessKinds AK) {
  1236. return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
  1237. }
  1238. namespace {
  1239. struct ComplexValue {
  1240. private:
  1241. bool IsInt;
  1242. public:
  1243. APSInt IntReal, IntImag;
  1244. APFloat FloatReal, FloatImag;
  1245. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1246. void makeComplexFloat() { IsInt = false; }
  1247. bool isComplexFloat() const { return !IsInt; }
  1248. APFloat &getComplexFloatReal() { return FloatReal; }
  1249. APFloat &getComplexFloatImag() { return FloatImag; }
  1250. void makeComplexInt() { IsInt = true; }
  1251. bool isComplexInt() const { return IsInt; }
  1252. APSInt &getComplexIntReal() { return IntReal; }
  1253. APSInt &getComplexIntImag() { return IntImag; }
  1254. void moveInto(APValue &v) const {
  1255. if (isComplexFloat())
  1256. v = APValue(FloatReal, FloatImag);
  1257. else
  1258. v = APValue(IntReal, IntImag);
  1259. }
  1260. void setFrom(const APValue &v) {
  1261. assert(v.isComplexFloat() || v.isComplexInt());
  1262. if (v.isComplexFloat()) {
  1263. makeComplexFloat();
  1264. FloatReal = v.getComplexFloatReal();
  1265. FloatImag = v.getComplexFloatImag();
  1266. } else {
  1267. makeComplexInt();
  1268. IntReal = v.getComplexIntReal();
  1269. IntImag = v.getComplexIntImag();
  1270. }
  1271. }
  1272. };
  1273. struct LValue {
  1274. APValue::LValueBase Base;
  1275. CharUnits Offset;
  1276. SubobjectDesignator Designator;
  1277. bool IsNullPtr : 1;
  1278. bool InvalidBase : 1;
  1279. const APValue::LValueBase getLValueBase() const { return Base; }
  1280. CharUnits &getLValueOffset() { return Offset; }
  1281. const CharUnits &getLValueOffset() const { return Offset; }
  1282. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1283. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1284. bool isNullPointer() const { return IsNullPtr;}
  1285. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1286. unsigned getLValueVersion() const { return Base.getVersion(); }
  1287. void moveInto(APValue &V) const {
  1288. if (Designator.Invalid)
  1289. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1290. else {
  1291. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1292. V = APValue(Base, Offset, Designator.Entries,
  1293. Designator.IsOnePastTheEnd, IsNullPtr);
  1294. }
  1295. }
  1296. void setFrom(ASTContext &Ctx, const APValue &V) {
  1297. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1298. Base = V.getLValueBase();
  1299. Offset = V.getLValueOffset();
  1300. InvalidBase = false;
  1301. Designator = SubobjectDesignator(Ctx, V);
  1302. IsNullPtr = V.isNullPointer();
  1303. }
  1304. void set(APValue::LValueBase B, bool BInvalid = false) {
  1305. #ifndef NDEBUG
  1306. // We only allow a few types of invalid bases. Enforce that here.
  1307. if (BInvalid) {
  1308. const auto *E = B.get<const Expr *>();
  1309. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1310. "Unexpected type of invalid base");
  1311. }
  1312. #endif
  1313. Base = B;
  1314. Offset = CharUnits::fromQuantity(0);
  1315. InvalidBase = BInvalid;
  1316. Designator = SubobjectDesignator(getType(B));
  1317. IsNullPtr = false;
  1318. }
  1319. void setNull(ASTContext &Ctx, QualType PointerTy) {
  1320. Base = (Expr *)nullptr;
  1321. Offset =
  1322. CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
  1323. InvalidBase = false;
  1324. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1325. IsNullPtr = true;
  1326. }
  1327. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1328. set(B, true);
  1329. }
  1330. std::string toString(ASTContext &Ctx, QualType T) const {
  1331. APValue Printable;
  1332. moveInto(Printable);
  1333. return Printable.getAsString(Ctx, T);
  1334. }
  1335. private:
  1336. // Check that this LValue is not based on a null pointer. If it is, produce
  1337. // a diagnostic and mark the designator as invalid.
  1338. template <typename GenDiagType>
  1339. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1340. if (Designator.Invalid)
  1341. return false;
  1342. if (IsNullPtr) {
  1343. GenDiag();
  1344. Designator.setInvalid();
  1345. return false;
  1346. }
  1347. return true;
  1348. }
  1349. public:
  1350. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1351. CheckSubobjectKind CSK) {
  1352. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1353. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1354. });
  1355. }
  1356. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1357. AccessKinds AK) {
  1358. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1359. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1360. });
  1361. }
  1362. // Check this LValue refers to an object. If not, set the designator to be
  1363. // invalid and emit a diagnostic.
  1364. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1365. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1366. Designator.checkSubobject(Info, E, CSK);
  1367. }
  1368. void addDecl(EvalInfo &Info, const Expr *E,
  1369. const Decl *D, bool Virtual = false) {
  1370. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1371. Designator.addDeclUnchecked(D, Virtual);
  1372. }
  1373. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1374. if (!Designator.Entries.empty()) {
  1375. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1376. Designator.setInvalid();
  1377. return;
  1378. }
  1379. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1380. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1381. Designator.FirstEntryIsAnUnsizedArray = true;
  1382. Designator.addUnsizedArrayUnchecked(ElemTy);
  1383. }
  1384. }
  1385. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1386. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1387. Designator.addArrayUnchecked(CAT);
  1388. }
  1389. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1390. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1391. Designator.addComplexUnchecked(EltTy, Imag);
  1392. }
  1393. void clearIsNullPointer() {
  1394. IsNullPtr = false;
  1395. }
  1396. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1397. const APSInt &Index, CharUnits ElementSize) {
  1398. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1399. // but we're not required to diagnose it and it's valid in C++.)
  1400. if (!Index)
  1401. return;
  1402. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1403. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1404. // offsets.
  1405. uint64_t Offset64 = Offset.getQuantity();
  1406. uint64_t ElemSize64 = ElementSize.getQuantity();
  1407. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1408. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1409. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1410. Designator.adjustIndex(Info, E, Index);
  1411. clearIsNullPointer();
  1412. }
  1413. void adjustOffset(CharUnits N) {
  1414. Offset += N;
  1415. if (N.getQuantity())
  1416. clearIsNullPointer();
  1417. }
  1418. };
  1419. struct MemberPtr {
  1420. MemberPtr() {}
  1421. explicit MemberPtr(const ValueDecl *Decl) :
  1422. DeclAndIsDerivedMember(Decl, false), Path() {}
  1423. /// The member or (direct or indirect) field referred to by this member
  1424. /// pointer, or 0 if this is a null member pointer.
  1425. const ValueDecl *getDecl() const {
  1426. return DeclAndIsDerivedMember.getPointer();
  1427. }
  1428. /// Is this actually a member of some type derived from the relevant class?
  1429. bool isDerivedMember() const {
  1430. return DeclAndIsDerivedMember.getInt();
  1431. }
  1432. /// Get the class which the declaration actually lives in.
  1433. const CXXRecordDecl *getContainingRecord() const {
  1434. return cast<CXXRecordDecl>(
  1435. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1436. }
  1437. void moveInto(APValue &V) const {
  1438. V = APValue(getDecl(), isDerivedMember(), Path);
  1439. }
  1440. void setFrom(const APValue &V) {
  1441. assert(V.isMemberPointer());
  1442. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1443. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1444. Path.clear();
  1445. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1446. Path.insert(Path.end(), P.begin(), P.end());
  1447. }
  1448. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1449. /// whether the member is a member of some class derived from the class type
  1450. /// of the member pointer.
  1451. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1452. /// Path - The path of base/derived classes from the member declaration's
  1453. /// class (exclusive) to the class type of the member pointer (inclusive).
  1454. SmallVector<const CXXRecordDecl*, 4> Path;
  1455. /// Perform a cast towards the class of the Decl (either up or down the
  1456. /// hierarchy).
  1457. bool castBack(const CXXRecordDecl *Class) {
  1458. assert(!Path.empty());
  1459. const CXXRecordDecl *Expected;
  1460. if (Path.size() >= 2)
  1461. Expected = Path[Path.size() - 2];
  1462. else
  1463. Expected = getContainingRecord();
  1464. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1465. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1466. // if B does not contain the original member and is not a base or
  1467. // derived class of the class containing the original member, the result
  1468. // of the cast is undefined.
  1469. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1470. // (D::*). We consider that to be a language defect.
  1471. return false;
  1472. }
  1473. Path.pop_back();
  1474. return true;
  1475. }
  1476. /// Perform a base-to-derived member pointer cast.
  1477. bool castToDerived(const CXXRecordDecl *Derived) {
  1478. if (!getDecl())
  1479. return true;
  1480. if (!isDerivedMember()) {
  1481. Path.push_back(Derived);
  1482. return true;
  1483. }
  1484. if (!castBack(Derived))
  1485. return false;
  1486. if (Path.empty())
  1487. DeclAndIsDerivedMember.setInt(false);
  1488. return true;
  1489. }
  1490. /// Perform a derived-to-base member pointer cast.
  1491. bool castToBase(const CXXRecordDecl *Base) {
  1492. if (!getDecl())
  1493. return true;
  1494. if (Path.empty())
  1495. DeclAndIsDerivedMember.setInt(true);
  1496. if (isDerivedMember()) {
  1497. Path.push_back(Base);
  1498. return true;
  1499. }
  1500. return castBack(Base);
  1501. }
  1502. };
  1503. /// Compare two member pointers, which are assumed to be of the same type.
  1504. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1505. if (!LHS.getDecl() || !RHS.getDecl())
  1506. return !LHS.getDecl() && !RHS.getDecl();
  1507. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1508. return false;
  1509. return LHS.Path == RHS.Path;
  1510. }
  1511. }
  1512. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1513. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1514. const LValue &This, const Expr *E,
  1515. bool AllowNonLiteralTypes = false);
  1516. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1517. bool InvalidBaseOK = false);
  1518. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1519. bool InvalidBaseOK = false);
  1520. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1521. EvalInfo &Info);
  1522. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1523. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1524. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1525. EvalInfo &Info);
  1526. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1527. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1528. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1529. EvalInfo &Info);
  1530. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1531. /// Evaluate an integer or fixed point expression into an APResult.
  1532. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1533. EvalInfo &Info);
  1534. /// Evaluate only a fixed point expression into an APResult.
  1535. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1536. EvalInfo &Info);
  1537. //===----------------------------------------------------------------------===//
  1538. // Misc utilities
  1539. //===----------------------------------------------------------------------===//
  1540. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1541. /// preserving its value (by extending by up to one bit as needed).
  1542. static void negateAsSigned(APSInt &Int) {
  1543. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1544. Int = Int.extend(Int.getBitWidth() + 1);
  1545. Int.setIsSigned(true);
  1546. }
  1547. Int = -Int;
  1548. }
  1549. template<typename KeyT>
  1550. APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
  1551. bool IsLifetimeExtended, LValue &LV) {
  1552. unsigned Version = getTempVersion();
  1553. APValue::LValueBase Base(Key, Index, Version);
  1554. LV.set(Base);
  1555. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1556. assert(Result.isAbsent() && "temporary created multiple times");
  1557. // If we're creating a temporary immediately in the operand of a speculative
  1558. // evaluation, don't register a cleanup to be run outside the speculative
  1559. // evaluation context, since we won't actually be able to initialize this
  1560. // object.
  1561. if (Index <= Info.SpeculativeEvaluationDepth) {
  1562. if (T.isDestructedType())
  1563. Info.noteSideEffect();
  1564. } else {
  1565. Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
  1566. }
  1567. return Result;
  1568. }
  1569. APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
  1570. if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
  1571. FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
  1572. return nullptr;
  1573. }
  1574. DynamicAllocLValue DA(NumHeapAllocs++);
  1575. LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
  1576. auto Result = HeapAllocs.emplace(std::piecewise_construct,
  1577. std::forward_as_tuple(DA), std::tuple<>());
  1578. assert(Result.second && "reused a heap alloc index?");
  1579. Result.first->second.AllocExpr = E;
  1580. return &Result.first->second.Value;
  1581. }
  1582. /// Produce a string describing the given constexpr call.
  1583. void CallStackFrame::describe(raw_ostream &Out) {
  1584. unsigned ArgIndex = 0;
  1585. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1586. !isa<CXXConstructorDecl>(Callee) &&
  1587. cast<CXXMethodDecl>(Callee)->isInstance();
  1588. if (!IsMemberCall)
  1589. Out << *Callee << '(';
  1590. if (This && IsMemberCall) {
  1591. APValue Val;
  1592. This->moveInto(Val);
  1593. Val.printPretty(Out, Info.Ctx,
  1594. This->Designator.MostDerivedType);
  1595. // FIXME: Add parens around Val if needed.
  1596. Out << "->" << *Callee << '(';
  1597. IsMemberCall = false;
  1598. }
  1599. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1600. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1601. if (ArgIndex > (unsigned)IsMemberCall)
  1602. Out << ", ";
  1603. const ParmVarDecl *Param = *I;
  1604. const APValue &Arg = Arguments[ArgIndex];
  1605. Arg.printPretty(Out, Info.Ctx, Param->getType());
  1606. if (ArgIndex == 0 && IsMemberCall)
  1607. Out << "->" << *Callee << '(';
  1608. }
  1609. Out << ')';
  1610. }
  1611. /// Evaluate an expression to see if it had side-effects, and discard its
  1612. /// result.
  1613. /// \return \c true if the caller should keep evaluating.
  1614. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1615. APValue Scratch;
  1616. if (!Evaluate(Scratch, Info, E))
  1617. // We don't need the value, but we might have skipped a side effect here.
  1618. return Info.noteSideEffect();
  1619. return true;
  1620. }
  1621. /// Should this call expression be treated as a string literal?
  1622. static bool IsStringLiteralCall(const CallExpr *E) {
  1623. unsigned Builtin = E->getBuiltinCallee();
  1624. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1625. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1626. }
  1627. static bool IsGlobalLValue(APValue::LValueBase B) {
  1628. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1629. // constant expression of pointer type that evaluates to...
  1630. // ... a null pointer value, or a prvalue core constant expression of type
  1631. // std::nullptr_t.
  1632. if (!B) return true;
  1633. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1634. // ... the address of an object with static storage duration,
  1635. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1636. return VD->hasGlobalStorage();
  1637. // ... the address of a function,
  1638. return isa<FunctionDecl>(D);
  1639. }
  1640. if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
  1641. return true;
  1642. const Expr *E = B.get<const Expr*>();
  1643. switch (E->getStmtClass()) {
  1644. default:
  1645. return false;
  1646. case Expr::CompoundLiteralExprClass: {
  1647. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1648. return CLE->isFileScope() && CLE->isLValue();
  1649. }
  1650. case Expr::MaterializeTemporaryExprClass:
  1651. // A materialized temporary might have been lifetime-extended to static
  1652. // storage duration.
  1653. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1654. // A string literal has static storage duration.
  1655. case Expr::StringLiteralClass:
  1656. case Expr::PredefinedExprClass:
  1657. case Expr::ObjCStringLiteralClass:
  1658. case Expr::ObjCEncodeExprClass:
  1659. case Expr::CXXUuidofExprClass:
  1660. return true;
  1661. case Expr::ObjCBoxedExprClass:
  1662. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1663. case Expr::CallExprClass:
  1664. return IsStringLiteralCall(cast<CallExpr>(E));
  1665. // For GCC compatibility, &&label has static storage duration.
  1666. case Expr::AddrLabelExprClass:
  1667. return true;
  1668. // A Block literal expression may be used as the initialization value for
  1669. // Block variables at global or local static scope.
  1670. case Expr::BlockExprClass:
  1671. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1672. case Expr::ImplicitValueInitExprClass:
  1673. // FIXME:
  1674. // We can never form an lvalue with an implicit value initialization as its
  1675. // base through expression evaluation, so these only appear in one case: the
  1676. // implicit variable declaration we invent when checking whether a constexpr
  1677. // constructor can produce a constant expression. We must assume that such
  1678. // an expression might be a global lvalue.
  1679. return true;
  1680. }
  1681. }
  1682. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1683. return LVal.Base.dyn_cast<const ValueDecl*>();
  1684. }
  1685. static bool IsLiteralLValue(const LValue &Value) {
  1686. if (Value.getLValueCallIndex())
  1687. return false;
  1688. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1689. return E && !isa<MaterializeTemporaryExpr>(E);
  1690. }
  1691. static bool IsWeakLValue(const LValue &Value) {
  1692. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1693. return Decl && Decl->isWeak();
  1694. }
  1695. static bool isZeroSized(const LValue &Value) {
  1696. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1697. if (Decl && isa<VarDecl>(Decl)) {
  1698. QualType Ty = Decl->getType();
  1699. if (Ty->isArrayType())
  1700. return Ty->isIncompleteType() ||
  1701. Decl->getASTContext().getTypeSize(Ty) == 0;
  1702. }
  1703. return false;
  1704. }
  1705. static bool HasSameBase(const LValue &A, const LValue &B) {
  1706. if (!A.getLValueBase())
  1707. return !B.getLValueBase();
  1708. if (!B.getLValueBase())
  1709. return false;
  1710. if (A.getLValueBase().getOpaqueValue() !=
  1711. B.getLValueBase().getOpaqueValue()) {
  1712. const Decl *ADecl = GetLValueBaseDecl(A);
  1713. if (!ADecl)
  1714. return false;
  1715. const Decl *BDecl = GetLValueBaseDecl(B);
  1716. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1717. return false;
  1718. }
  1719. return IsGlobalLValue(A.getLValueBase()) ||
  1720. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1721. A.getLValueVersion() == B.getLValueVersion());
  1722. }
  1723. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1724. assert(Base && "no location for a null lvalue");
  1725. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1726. if (VD)
  1727. Info.Note(VD->getLocation(), diag::note_declared_at);
  1728. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1729. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1730. else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  1731. // FIXME: Produce a note for dangling pointers too.
  1732. if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
  1733. Info.Note((*Alloc)->AllocExpr->getExprLoc(),
  1734. diag::note_constexpr_dynamic_alloc_here);
  1735. }
  1736. // We have no information to show for a typeid(T) object.
  1737. }
  1738. enum class CheckEvaluationResultKind {
  1739. ConstantExpression,
  1740. FullyInitialized,
  1741. };
  1742. /// Materialized temporaries that we've already checked to determine if they're
  1743. /// initializsed by a constant expression.
  1744. using CheckedTemporaries =
  1745. llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
  1746. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  1747. EvalInfo &Info, SourceLocation DiagLoc,
  1748. QualType Type, const APValue &Value,
  1749. Expr::ConstExprUsage Usage,
  1750. SourceLocation SubobjectLoc,
  1751. CheckedTemporaries &CheckedTemps);
  1752. /// Check that this reference or pointer core constant expression is a valid
  1753. /// value for an address or reference constant expression. Return true if we
  1754. /// can fold this expression, whether or not it's a constant expression.
  1755. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1756. QualType Type, const LValue &LVal,
  1757. Expr::ConstExprUsage Usage,
  1758. CheckedTemporaries &CheckedTemps) {
  1759. bool IsReferenceType = Type->isReferenceType();
  1760. APValue::LValueBase Base = LVal.getLValueBase();
  1761. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1762. // Check that the object is a global. Note that the fake 'this' object we
  1763. // manufacture when checking potential constant expressions is conservatively
  1764. // assumed to be global here.
  1765. if (!IsGlobalLValue(Base)) {
  1766. if (Info.getLangOpts().CPlusPlus11) {
  1767. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1768. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1769. << IsReferenceType << !Designator.Entries.empty()
  1770. << !!VD << VD;
  1771. NoteLValueLocation(Info, Base);
  1772. } else {
  1773. Info.FFDiag(Loc);
  1774. }
  1775. // Don't allow references to temporaries to escape.
  1776. return false;
  1777. }
  1778. assert((Info.checkingPotentialConstantExpression() ||
  1779. LVal.getLValueCallIndex() == 0) &&
  1780. "have call index for global lvalue");
  1781. if (Base.is<DynamicAllocLValue>()) {
  1782. Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
  1783. << IsReferenceType << !Designator.Entries.empty();
  1784. NoteLValueLocation(Info, Base);
  1785. return false;
  1786. }
  1787. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1788. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1789. // Check if this is a thread-local variable.
  1790. if (Var->getTLSKind())
  1791. // FIXME: Diagnostic!
  1792. return false;
  1793. // A dllimport variable never acts like a constant.
  1794. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1795. // FIXME: Diagnostic!
  1796. return false;
  1797. }
  1798. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1799. // __declspec(dllimport) must be handled very carefully:
  1800. // We must never initialize an expression with the thunk in C++.
  1801. // Doing otherwise would allow the same id-expression to yield
  1802. // different addresses for the same function in different translation
  1803. // units. However, this means that we must dynamically initialize the
  1804. // expression with the contents of the import address table at runtime.
  1805. //
  1806. // The C language has no notion of ODR; furthermore, it has no notion of
  1807. // dynamic initialization. This means that we are permitted to
  1808. // perform initialization with the address of the thunk.
  1809. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1810. FD->hasAttr<DLLImportAttr>())
  1811. // FIXME: Diagnostic!
  1812. return false;
  1813. }
  1814. } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
  1815. Base.dyn_cast<const Expr *>())) {
  1816. if (CheckedTemps.insert(MTE).second) {
  1817. QualType TempType = getType(Base);
  1818. if (TempType.isDestructedType()) {
  1819. Info.FFDiag(MTE->getExprLoc(),
  1820. diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
  1821. << TempType;
  1822. return false;
  1823. }
  1824. APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  1825. assert(V && "evasluation result refers to uninitialised temporary");
  1826. if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1827. Info, MTE->getExprLoc(), TempType, *V,
  1828. Usage, SourceLocation(), CheckedTemps))
  1829. return false;
  1830. }
  1831. }
  1832. // Allow address constant expressions to be past-the-end pointers. This is
  1833. // an extension: the standard requires them to point to an object.
  1834. if (!IsReferenceType)
  1835. return true;
  1836. // A reference constant expression must refer to an object.
  1837. if (!Base) {
  1838. // FIXME: diagnostic
  1839. Info.CCEDiag(Loc);
  1840. return true;
  1841. }
  1842. // Does this refer one past the end of some object?
  1843. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1844. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1845. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1846. << !Designator.Entries.empty() << !!VD << VD;
  1847. NoteLValueLocation(Info, Base);
  1848. }
  1849. return true;
  1850. }
  1851. /// Member pointers are constant expressions unless they point to a
  1852. /// non-virtual dllimport member function.
  1853. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1854. SourceLocation Loc,
  1855. QualType Type,
  1856. const APValue &Value,
  1857. Expr::ConstExprUsage Usage) {
  1858. const ValueDecl *Member = Value.getMemberPointerDecl();
  1859. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1860. if (!FD)
  1861. return true;
  1862. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1863. !FD->hasAttr<DLLImportAttr>();
  1864. }
  1865. /// Check that this core constant expression is of literal type, and if not,
  1866. /// produce an appropriate diagnostic.
  1867. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1868. const LValue *This = nullptr) {
  1869. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1870. return true;
  1871. // C++1y: A constant initializer for an object o [...] may also invoke
  1872. // constexpr constructors for o and its subobjects even if those objects
  1873. // are of non-literal class types.
  1874. //
  1875. // C++11 missed this detail for aggregates, so classes like this:
  1876. // struct foo_t { union { int i; volatile int j; } u; };
  1877. // are not (obviously) initializable like so:
  1878. // __attribute__((__require_constant_initialization__))
  1879. // static const foo_t x = {{0}};
  1880. // because "i" is a subobject with non-literal initialization (due to the
  1881. // volatile member of the union). See:
  1882. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1883. // Therefore, we use the C++1y behavior.
  1884. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1885. return true;
  1886. // Prvalue constant expressions must be of literal types.
  1887. if (Info.getLangOpts().CPlusPlus11)
  1888. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1889. << E->getType();
  1890. else
  1891. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1892. return false;
  1893. }
  1894. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  1895. EvalInfo &Info, SourceLocation DiagLoc,
  1896. QualType Type, const APValue &Value,
  1897. Expr::ConstExprUsage Usage,
  1898. SourceLocation SubobjectLoc,
  1899. CheckedTemporaries &CheckedTemps) {
  1900. if (!Value.hasValue()) {
  1901. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1902. << true << Type;
  1903. if (SubobjectLoc.isValid())
  1904. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1905. return false;
  1906. }
  1907. // We allow _Atomic(T) to be initialized from anything that T can be
  1908. // initialized from.
  1909. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1910. Type = AT->getValueType();
  1911. // Core issue 1454: For a literal constant expression of array or class type,
  1912. // each subobject of its value shall have been initialized by a constant
  1913. // expression.
  1914. if (Value.isArray()) {
  1915. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1916. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1917. if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1918. Value.getArrayInitializedElt(I), Usage,
  1919. SubobjectLoc, CheckedTemps))
  1920. return false;
  1921. }
  1922. if (!Value.hasArrayFiller())
  1923. return true;
  1924. return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  1925. Value.getArrayFiller(), Usage, SubobjectLoc,
  1926. CheckedTemps);
  1927. }
  1928. if (Value.isUnion() && Value.getUnionField()) {
  1929. return CheckEvaluationResult(
  1930. CERK, Info, DiagLoc, Value.getUnionField()->getType(),
  1931. Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
  1932. CheckedTemps);
  1933. }
  1934. if (Value.isStruct()) {
  1935. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1936. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1937. unsigned BaseIndex = 0;
  1938. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1939. if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
  1940. Value.getStructBase(BaseIndex), Usage,
  1941. BS.getBeginLoc(), CheckedTemps))
  1942. return false;
  1943. ++BaseIndex;
  1944. }
  1945. }
  1946. for (const auto *I : RD->fields()) {
  1947. if (I->isUnnamedBitfield())
  1948. continue;
  1949. if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
  1950. Value.getStructField(I->getFieldIndex()),
  1951. Usage, I->getLocation(), CheckedTemps))
  1952. return false;
  1953. }
  1954. }
  1955. if (Value.isLValue() &&
  1956. CERK == CheckEvaluationResultKind::ConstantExpression) {
  1957. LValue LVal;
  1958. LVal.setFrom(Info.Ctx, Value);
  1959. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
  1960. CheckedTemps);
  1961. }
  1962. if (Value.isMemberPointer() &&
  1963. CERK == CheckEvaluationResultKind::ConstantExpression)
  1964. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1965. // Everything else is fine.
  1966. return true;
  1967. }
  1968. /// Check that this core constant expression value is a valid value for a
  1969. /// constant expression. If not, report an appropriate diagnostic. Does not
  1970. /// check that the expression is of literal type.
  1971. static bool
  1972. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1973. const APValue &Value,
  1974. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1975. CheckedTemporaries CheckedTemps;
  1976. return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1977. Info, DiagLoc, Type, Value, Usage,
  1978. SourceLocation(), CheckedTemps);
  1979. }
  1980. /// Check that this evaluated value is fully-initialized and can be loaded by
  1981. /// an lvalue-to-rvalue conversion.
  1982. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
  1983. QualType Type, const APValue &Value) {
  1984. CheckedTemporaries CheckedTemps;
  1985. return CheckEvaluationResult(
  1986. CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
  1987. Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
  1988. }
  1989. /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
  1990. /// "the allocated storage is deallocated within the evaluation".
  1991. static bool CheckMemoryLeaks(EvalInfo &Info) {
  1992. if (!Info.HeapAllocs.empty()) {
  1993. // We can still fold to a constant despite a compile-time memory leak,
  1994. // so long as the heap allocation isn't referenced in the result (we check
  1995. // that in CheckConstantExpression).
  1996. Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
  1997. diag::note_constexpr_memory_leak)
  1998. << unsigned(Info.HeapAllocs.size() - 1);
  1999. }
  2000. return true;
  2001. }
  2002. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  2003. // A null base expression indicates a null pointer. These are always
  2004. // evaluatable, and they are false unless the offset is zero.
  2005. if (!Value.getLValueBase()) {
  2006. Result = !Value.getLValueOffset().isZero();
  2007. return true;
  2008. }
  2009. // We have a non-null base. These are generally known to be true, but if it's
  2010. // a weak declaration it can be null at runtime.
  2011. Result = true;
  2012. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  2013. return !Decl || !Decl->isWeak();
  2014. }
  2015. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  2016. switch (Val.getKind()) {
  2017. case APValue::None:
  2018. case APValue::Indeterminate:
  2019. return false;
  2020. case APValue::Int:
  2021. Result = Val.getInt().getBoolValue();
  2022. return true;
  2023. case APValue::FixedPoint:
  2024. Result = Val.getFixedPoint().getBoolValue();
  2025. return true;
  2026. case APValue::Float:
  2027. Result = !Val.getFloat().isZero();
  2028. return true;
  2029. case APValue::ComplexInt:
  2030. Result = Val.getComplexIntReal().getBoolValue() ||
  2031. Val.getComplexIntImag().getBoolValue();
  2032. return true;
  2033. case APValue::ComplexFloat:
  2034. Result = !Val.getComplexFloatReal().isZero() ||
  2035. !Val.getComplexFloatImag().isZero();
  2036. return true;
  2037. case APValue::LValue:
  2038. return EvalPointerValueAsBool(Val, Result);
  2039. case APValue::MemberPointer:
  2040. Result = Val.getMemberPointerDecl();
  2041. return true;
  2042. case APValue::Vector:
  2043. case APValue::Array:
  2044. case APValue::Struct:
  2045. case APValue::Union:
  2046. case APValue::AddrLabelDiff:
  2047. return false;
  2048. }
  2049. llvm_unreachable("unknown APValue kind");
  2050. }
  2051. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  2052. EvalInfo &Info) {
  2053. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  2054. APValue Val;
  2055. if (!Evaluate(Val, Info, E))
  2056. return false;
  2057. return HandleConversionToBool(Val, Result);
  2058. }
  2059. template<typename T>
  2060. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  2061. const T &SrcValue, QualType DestType) {
  2062. Info.CCEDiag(E, diag::note_constexpr_overflow)
  2063. << SrcValue << DestType;
  2064. return Info.noteUndefinedBehavior();
  2065. }
  2066. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  2067. QualType SrcType, const APFloat &Value,
  2068. QualType DestType, APSInt &Result) {
  2069. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2070. // Determine whether we are converting to unsigned or signed.
  2071. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  2072. Result = APSInt(DestWidth, !DestSigned);
  2073. bool ignored;
  2074. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  2075. & APFloat::opInvalidOp)
  2076. return HandleOverflow(Info, E, Value, DestType);
  2077. return true;
  2078. }
  2079. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  2080. QualType SrcType, QualType DestType,
  2081. APFloat &Result) {
  2082. APFloat Value = Result;
  2083. bool ignored;
  2084. Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  2085. APFloat::rmNearestTiesToEven, &ignored);
  2086. return true;
  2087. }
  2088. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  2089. QualType DestType, QualType SrcType,
  2090. const APSInt &Value) {
  2091. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2092. // Figure out if this is a truncate, extend or noop cast.
  2093. // If the input is signed, do a sign extend, noop, or truncate.
  2094. APSInt Result = Value.extOrTrunc(DestWidth);
  2095. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  2096. if (DestType->isBooleanType())
  2097. Result = Value.getBoolValue();
  2098. return Result;
  2099. }
  2100. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  2101. QualType SrcType, const APSInt &Value,
  2102. QualType DestType, APFloat &Result) {
  2103. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  2104. Result.convertFromAPInt(Value, Value.isSigned(),
  2105. APFloat::rmNearestTiesToEven);
  2106. return true;
  2107. }
  2108. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  2109. APValue &Value, const FieldDecl *FD) {
  2110. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  2111. if (!Value.isInt()) {
  2112. // Trying to store a pointer-cast-to-integer into a bitfield.
  2113. // FIXME: In this case, we should provide the diagnostic for casting
  2114. // a pointer to an integer.
  2115. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  2116. Info.FFDiag(E);
  2117. return false;
  2118. }
  2119. APSInt &Int = Value.getInt();
  2120. unsigned OldBitWidth = Int.getBitWidth();
  2121. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2122. if (NewBitWidth < OldBitWidth)
  2123. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2124. return true;
  2125. }
  2126. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2127. llvm::APInt &Res) {
  2128. APValue SVal;
  2129. if (!Evaluate(SVal, Info, E))
  2130. return false;
  2131. if (SVal.isInt()) {
  2132. Res = SVal.getInt();
  2133. return true;
  2134. }
  2135. if (SVal.isFloat()) {
  2136. Res = SVal.getFloat().bitcastToAPInt();
  2137. return true;
  2138. }
  2139. if (SVal.isVector()) {
  2140. QualType VecTy = E->getType();
  2141. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2142. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2143. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2144. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2145. Res = llvm::APInt::getNullValue(VecSize);
  2146. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2147. APValue &Elt = SVal.getVectorElt(i);
  2148. llvm::APInt EltAsInt;
  2149. if (Elt.isInt()) {
  2150. EltAsInt = Elt.getInt();
  2151. } else if (Elt.isFloat()) {
  2152. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2153. } else {
  2154. // Don't try to handle vectors of anything other than int or float
  2155. // (not sure if it's possible to hit this case).
  2156. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2157. return false;
  2158. }
  2159. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2160. if (BigEndian)
  2161. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2162. else
  2163. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2164. }
  2165. return true;
  2166. }
  2167. // Give up if the input isn't an int, float, or vector. For example, we
  2168. // reject "(v4i16)(intptr_t)&a".
  2169. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2170. return false;
  2171. }
  2172. /// Perform the given integer operation, which is known to need at most BitWidth
  2173. /// bits, and check for overflow in the original type (if that type was not an
  2174. /// unsigned type).
  2175. template<typename Operation>
  2176. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2177. const APSInt &LHS, const APSInt &RHS,
  2178. unsigned BitWidth, Operation Op,
  2179. APSInt &Result) {
  2180. if (LHS.isUnsigned()) {
  2181. Result = Op(LHS, RHS);
  2182. return true;
  2183. }
  2184. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2185. Result = Value.trunc(LHS.getBitWidth());
  2186. if (Result.extend(BitWidth) != Value) {
  2187. if (Info.checkingForUndefinedBehavior())
  2188. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2189. diag::warn_integer_constant_overflow)
  2190. << Result.toString(10) << E->getType();
  2191. else
  2192. return HandleOverflow(Info, E, Value, E->getType());
  2193. }
  2194. return true;
  2195. }
  2196. /// Perform the given binary integer operation.
  2197. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2198. BinaryOperatorKind Opcode, APSInt RHS,
  2199. APSInt &Result) {
  2200. switch (Opcode) {
  2201. default:
  2202. Info.FFDiag(E);
  2203. return false;
  2204. case BO_Mul:
  2205. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2206. std::multiplies<APSInt>(), Result);
  2207. case BO_Add:
  2208. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2209. std::plus<APSInt>(), Result);
  2210. case BO_Sub:
  2211. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2212. std::minus<APSInt>(), Result);
  2213. case BO_And: Result = LHS & RHS; return true;
  2214. case BO_Xor: Result = LHS ^ RHS; return true;
  2215. case BO_Or: Result = LHS | RHS; return true;
  2216. case BO_Div:
  2217. case BO_Rem:
  2218. if (RHS == 0) {
  2219. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2220. return false;
  2221. }
  2222. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2223. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2224. // this operation and gives the two's complement result.
  2225. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2226. LHS.isSigned() && LHS.isMinSignedValue())
  2227. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2228. E->getType());
  2229. return true;
  2230. case BO_Shl: {
  2231. if (Info.getLangOpts().OpenCL)
  2232. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2233. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2234. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2235. RHS.isUnsigned());
  2236. else if (RHS.isSigned() && RHS.isNegative()) {
  2237. // During constant-folding, a negative shift is an opposite shift. Such
  2238. // a shift is not a constant expression.
  2239. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2240. RHS = -RHS;
  2241. goto shift_right;
  2242. }
  2243. shift_left:
  2244. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2245. // the shifted type.
  2246. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2247. if (SA != RHS) {
  2248. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2249. << RHS << E->getType() << LHS.getBitWidth();
  2250. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
  2251. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2252. // operand, and must not overflow the corresponding unsigned type.
  2253. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2254. // E1 x 2^E2 module 2^N.
  2255. if (LHS.isNegative())
  2256. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2257. else if (LHS.countLeadingZeros() < SA)
  2258. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2259. }
  2260. Result = LHS << SA;
  2261. return true;
  2262. }
  2263. case BO_Shr: {
  2264. if (Info.getLangOpts().OpenCL)
  2265. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2266. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2267. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2268. RHS.isUnsigned());
  2269. else if (RHS.isSigned() && RHS.isNegative()) {
  2270. // During constant-folding, a negative shift is an opposite shift. Such a
  2271. // shift is not a constant expression.
  2272. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2273. RHS = -RHS;
  2274. goto shift_left;
  2275. }
  2276. shift_right:
  2277. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2278. // shifted type.
  2279. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2280. if (SA != RHS)
  2281. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2282. << RHS << E->getType() << LHS.getBitWidth();
  2283. Result = LHS >> SA;
  2284. return true;
  2285. }
  2286. case BO_LT: Result = LHS < RHS; return true;
  2287. case BO_GT: Result = LHS > RHS; return true;
  2288. case BO_LE: Result = LHS <= RHS; return true;
  2289. case BO_GE: Result = LHS >= RHS; return true;
  2290. case BO_EQ: Result = LHS == RHS; return true;
  2291. case BO_NE: Result = LHS != RHS; return true;
  2292. case BO_Cmp:
  2293. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2294. }
  2295. }
  2296. /// Perform the given binary floating-point operation, in-place, on LHS.
  2297. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2298. APFloat &LHS, BinaryOperatorKind Opcode,
  2299. const APFloat &RHS) {
  2300. switch (Opcode) {
  2301. default:
  2302. Info.FFDiag(E);
  2303. return false;
  2304. case BO_Mul:
  2305. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2306. break;
  2307. case BO_Add:
  2308. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2309. break;
  2310. case BO_Sub:
  2311. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2312. break;
  2313. case BO_Div:
  2314. // [expr.mul]p4:
  2315. // If the second operand of / or % is zero the behavior is undefined.
  2316. if (RHS.isZero())
  2317. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2318. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2319. break;
  2320. }
  2321. // [expr.pre]p4:
  2322. // If during the evaluation of an expression, the result is not
  2323. // mathematically defined [...], the behavior is undefined.
  2324. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2325. if (LHS.isNaN()) {
  2326. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2327. return Info.noteUndefinedBehavior();
  2328. }
  2329. return true;
  2330. }
  2331. /// Cast an lvalue referring to a base subobject to a derived class, by
  2332. /// truncating the lvalue's path to the given length.
  2333. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2334. const RecordDecl *TruncatedType,
  2335. unsigned TruncatedElements) {
  2336. SubobjectDesignator &D = Result.Designator;
  2337. // Check we actually point to a derived class object.
  2338. if (TruncatedElements == D.Entries.size())
  2339. return true;
  2340. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2341. "not casting to a derived class");
  2342. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2343. return false;
  2344. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2345. const RecordDecl *RD = TruncatedType;
  2346. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2347. if (RD->isInvalidDecl()) return false;
  2348. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2349. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2350. if (isVirtualBaseClass(D.Entries[I]))
  2351. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2352. else
  2353. Result.Offset -= Layout.getBaseClassOffset(Base);
  2354. RD = Base;
  2355. }
  2356. D.Entries.resize(TruncatedElements);
  2357. return true;
  2358. }
  2359. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2360. const CXXRecordDecl *Derived,
  2361. const CXXRecordDecl *Base,
  2362. const ASTRecordLayout *RL = nullptr) {
  2363. if (!RL) {
  2364. if (Derived->isInvalidDecl()) return false;
  2365. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2366. }
  2367. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2368. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2369. return true;
  2370. }
  2371. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2372. const CXXRecordDecl *DerivedDecl,
  2373. const CXXBaseSpecifier *Base) {
  2374. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2375. if (!Base->isVirtual())
  2376. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2377. SubobjectDesignator &D = Obj.Designator;
  2378. if (D.Invalid)
  2379. return false;
  2380. // Extract most-derived object and corresponding type.
  2381. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2382. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2383. return false;
  2384. // Find the virtual base class.
  2385. if (DerivedDecl->isInvalidDecl()) return false;
  2386. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2387. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2388. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2389. return true;
  2390. }
  2391. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2392. QualType Type, LValue &Result) {
  2393. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2394. PathE = E->path_end();
  2395. PathI != PathE; ++PathI) {
  2396. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2397. *PathI))
  2398. return false;
  2399. Type = (*PathI)->getType();
  2400. }
  2401. return true;
  2402. }
  2403. /// Cast an lvalue referring to a derived class to a known base subobject.
  2404. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2405. const CXXRecordDecl *DerivedRD,
  2406. const CXXRecordDecl *BaseRD) {
  2407. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2408. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2409. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2410. llvm_unreachable("Class must be derived from the passed in base class!");
  2411. for (CXXBasePathElement &Elem : Paths.front())
  2412. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2413. return false;
  2414. return true;
  2415. }
  2416. /// Update LVal to refer to the given field, which must be a member of the type
  2417. /// currently described by LVal.
  2418. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2419. const FieldDecl *FD,
  2420. const ASTRecordLayout *RL = nullptr) {
  2421. if (!RL) {
  2422. if (FD->getParent()->isInvalidDecl()) return false;
  2423. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2424. }
  2425. unsigned I = FD->getFieldIndex();
  2426. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2427. LVal.addDecl(Info, E, FD);
  2428. return true;
  2429. }
  2430. /// Update LVal to refer to the given indirect field.
  2431. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2432. LValue &LVal,
  2433. const IndirectFieldDecl *IFD) {
  2434. for (const auto *C : IFD->chain())
  2435. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2436. return false;
  2437. return true;
  2438. }
  2439. /// Get the size of the given type in char units.
  2440. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2441. QualType Type, CharUnits &Size) {
  2442. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2443. // extension.
  2444. if (Type->isVoidType() || Type->isFunctionType()) {
  2445. Size = CharUnits::One();
  2446. return true;
  2447. }
  2448. if (Type->isDependentType()) {
  2449. Info.FFDiag(Loc);
  2450. return false;
  2451. }
  2452. if (!Type->isConstantSizeType()) {
  2453. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2454. // FIXME: Better diagnostic.
  2455. Info.FFDiag(Loc);
  2456. return false;
  2457. }
  2458. Size = Info.Ctx.getTypeSizeInChars(Type);
  2459. return true;
  2460. }
  2461. /// Update a pointer value to model pointer arithmetic.
  2462. /// \param Info - Information about the ongoing evaluation.
  2463. /// \param E - The expression being evaluated, for diagnostic purposes.
  2464. /// \param LVal - The pointer value to be updated.
  2465. /// \param EltTy - The pointee type represented by LVal.
  2466. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2467. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2468. LValue &LVal, QualType EltTy,
  2469. APSInt Adjustment) {
  2470. CharUnits SizeOfPointee;
  2471. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2472. return false;
  2473. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2474. return true;
  2475. }
  2476. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2477. LValue &LVal, QualType EltTy,
  2478. int64_t Adjustment) {
  2479. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2480. APSInt::get(Adjustment));
  2481. }
  2482. /// Update an lvalue to refer to a component of a complex number.
  2483. /// \param Info - Information about the ongoing evaluation.
  2484. /// \param LVal - The lvalue to be updated.
  2485. /// \param EltTy - The complex number's component type.
  2486. /// \param Imag - False for the real component, true for the imaginary.
  2487. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2488. LValue &LVal, QualType EltTy,
  2489. bool Imag) {
  2490. if (Imag) {
  2491. CharUnits SizeOfComponent;
  2492. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2493. return false;
  2494. LVal.Offset += SizeOfComponent;
  2495. }
  2496. LVal.addComplex(Info, E, EltTy, Imag);
  2497. return true;
  2498. }
  2499. /// Try to evaluate the initializer for a variable declaration.
  2500. ///
  2501. /// \param Info Information about the ongoing evaluation.
  2502. /// \param E An expression to be used when printing diagnostics.
  2503. /// \param VD The variable whose initializer should be obtained.
  2504. /// \param Frame The frame in which the variable was created. Must be null
  2505. /// if this variable is not local to the evaluation.
  2506. /// \param Result Filled in with a pointer to the value of the variable.
  2507. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2508. const VarDecl *VD, CallStackFrame *Frame,
  2509. APValue *&Result, const LValue *LVal) {
  2510. // If this is a parameter to an active constexpr function call, perform
  2511. // argument substitution.
  2512. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2513. // Assume arguments of a potential constant expression are unknown
  2514. // constant expressions.
  2515. if (Info.checkingPotentialConstantExpression())
  2516. return false;
  2517. if (!Frame || !Frame->Arguments) {
  2518. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2519. return false;
  2520. }
  2521. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2522. return true;
  2523. }
  2524. // If this is a local variable, dig out its value.
  2525. if (Frame) {
  2526. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2527. : Frame->getCurrentTemporary(VD);
  2528. if (!Result) {
  2529. // Assume variables referenced within a lambda's call operator that were
  2530. // not declared within the call operator are captures and during checking
  2531. // of a potential constant expression, assume they are unknown constant
  2532. // expressions.
  2533. assert(isLambdaCallOperator(Frame->Callee) &&
  2534. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2535. "missing value for local variable");
  2536. if (Info.checkingPotentialConstantExpression())
  2537. return false;
  2538. // FIXME: implement capture evaluation during constant expr evaluation.
  2539. Info.FFDiag(E->getBeginLoc(),
  2540. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2541. << "captures not currently allowed";
  2542. return false;
  2543. }
  2544. return true;
  2545. }
  2546. // Dig out the initializer, and use the declaration which it's attached to.
  2547. const Expr *Init = VD->getAnyInitializer(VD);
  2548. if (!Init || Init->isValueDependent()) {
  2549. // If we're checking a potential constant expression, the variable could be
  2550. // initialized later.
  2551. if (!Info.checkingPotentialConstantExpression())
  2552. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2553. return false;
  2554. }
  2555. // If we're currently evaluating the initializer of this declaration, use that
  2556. // in-flight value.
  2557. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2558. Result = Info.EvaluatingDeclValue;
  2559. return true;
  2560. }
  2561. // Never evaluate the initializer of a weak variable. We can't be sure that
  2562. // this is the definition which will be used.
  2563. if (VD->isWeak()) {
  2564. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2565. return false;
  2566. }
  2567. // Check that we can fold the initializer. In C++, we will have already done
  2568. // this in the cases where it matters for conformance.
  2569. SmallVector<PartialDiagnosticAt, 8> Notes;
  2570. if (!VD->evaluateValue(Notes)) {
  2571. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2572. Notes.size() + 1) << VD;
  2573. Info.Note(VD->getLocation(), diag::note_declared_at);
  2574. Info.addNotes(Notes);
  2575. return false;
  2576. } else if (!VD->checkInitIsICE()) {
  2577. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2578. Notes.size() + 1) << VD;
  2579. Info.Note(VD->getLocation(), diag::note_declared_at);
  2580. Info.addNotes(Notes);
  2581. }
  2582. Result = VD->getEvaluatedValue();
  2583. return true;
  2584. }
  2585. static bool IsConstNonVolatile(QualType T) {
  2586. Qualifiers Quals = T.getQualifiers();
  2587. return Quals.hasConst() && !Quals.hasVolatile();
  2588. }
  2589. /// Get the base index of the given base class within an APValue representing
  2590. /// the given derived class.
  2591. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2592. const CXXRecordDecl *Base) {
  2593. Base = Base->getCanonicalDecl();
  2594. unsigned Index = 0;
  2595. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2596. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2597. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2598. return Index;
  2599. }
  2600. llvm_unreachable("base class missing from derived class's bases list");
  2601. }
  2602. /// Extract the value of a character from a string literal.
  2603. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2604. uint64_t Index) {
  2605. assert(!isa<SourceLocExpr>(Lit) &&
  2606. "SourceLocExpr should have already been converted to a StringLiteral");
  2607. // FIXME: Support MakeStringConstant
  2608. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2609. std::string Str;
  2610. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2611. assert(Index <= Str.size() && "Index too large");
  2612. return APSInt::getUnsigned(Str.c_str()[Index]);
  2613. }
  2614. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2615. Lit = PE->getFunctionName();
  2616. const StringLiteral *S = cast<StringLiteral>(Lit);
  2617. const ConstantArrayType *CAT =
  2618. Info.Ctx.getAsConstantArrayType(S->getType());
  2619. assert(CAT && "string literal isn't an array");
  2620. QualType CharType = CAT->getElementType();
  2621. assert(CharType->isIntegerType() && "unexpected character type");
  2622. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2623. CharType->isUnsignedIntegerType());
  2624. if (Index < S->getLength())
  2625. Value = S->getCodeUnit(Index);
  2626. return Value;
  2627. }
  2628. // Expand a string literal into an array of characters.
  2629. //
  2630. // FIXME: This is inefficient; we should probably introduce something similar
  2631. // to the LLVM ConstantDataArray to make this cheaper.
  2632. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2633. APValue &Result,
  2634. QualType AllocType = QualType()) {
  2635. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  2636. AllocType.isNull() ? S->getType() : AllocType);
  2637. assert(CAT && "string literal isn't an array");
  2638. QualType CharType = CAT->getElementType();
  2639. assert(CharType->isIntegerType() && "unexpected character type");
  2640. unsigned Elts = CAT->getSize().getZExtValue();
  2641. Result = APValue(APValue::UninitArray(),
  2642. std::min(S->getLength(), Elts), Elts);
  2643. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2644. CharType->isUnsignedIntegerType());
  2645. if (Result.hasArrayFiller())
  2646. Result.getArrayFiller() = APValue(Value);
  2647. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2648. Value = S->getCodeUnit(I);
  2649. Result.getArrayInitializedElt(I) = APValue(Value);
  2650. }
  2651. }
  2652. // Expand an array so that it has more than Index filled elements.
  2653. static void expandArray(APValue &Array, unsigned Index) {
  2654. unsigned Size = Array.getArraySize();
  2655. assert(Index < Size);
  2656. // Always at least double the number of elements for which we store a value.
  2657. unsigned OldElts = Array.getArrayInitializedElts();
  2658. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2659. NewElts = std::min(Size, std::max(NewElts, 8u));
  2660. // Copy the data across.
  2661. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2662. for (unsigned I = 0; I != OldElts; ++I)
  2663. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2664. for (unsigned I = OldElts; I != NewElts; ++I)
  2665. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2666. if (NewValue.hasArrayFiller())
  2667. NewValue.getArrayFiller() = Array.getArrayFiller();
  2668. Array.swap(NewValue);
  2669. }
  2670. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2671. /// conversion. If it's of class type, we may assume that the copy operation
  2672. /// is trivial. Note that this is never true for a union type with fields
  2673. /// (because the copy always "reads" the active member) and always true for
  2674. /// a non-class type.
  2675. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2676. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2677. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2678. return true;
  2679. if (RD->isEmpty())
  2680. return false;
  2681. for (auto *Field : RD->fields())
  2682. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2683. return true;
  2684. for (auto &BaseSpec : RD->bases())
  2685. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2686. return true;
  2687. return false;
  2688. }
  2689. /// Diagnose an attempt to read from any unreadable field within the specified
  2690. /// type, which might be a class type.
  2691. static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
  2692. QualType T) {
  2693. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2694. if (!RD)
  2695. return false;
  2696. if (!RD->hasMutableFields())
  2697. return false;
  2698. for (auto *Field : RD->fields()) {
  2699. // If we're actually going to read this field in some way, then it can't
  2700. // be mutable. If we're in a union, then assigning to a mutable field
  2701. // (even an empty one) can change the active member, so that's not OK.
  2702. // FIXME: Add core issue number for the union case.
  2703. if (Field->isMutable() &&
  2704. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2705. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
  2706. Info.Note(Field->getLocation(), diag::note_declared_at);
  2707. return true;
  2708. }
  2709. if (diagnoseMutableFields(Info, E, AK, Field->getType()))
  2710. return true;
  2711. }
  2712. for (auto &BaseSpec : RD->bases())
  2713. if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
  2714. return true;
  2715. // All mutable fields were empty, and thus not actually read.
  2716. return false;
  2717. }
  2718. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2719. APValue::LValueBase Base,
  2720. bool MutableSubobject = false) {
  2721. // A temporary we created.
  2722. if (Base.getCallIndex())
  2723. return true;
  2724. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2725. if (!Evaluating)
  2726. return false;
  2727. auto *BaseD = Base.dyn_cast<const ValueDecl*>();
  2728. switch (Info.IsEvaluatingDecl) {
  2729. case EvalInfo::EvaluatingDeclKind::None:
  2730. return false;
  2731. case EvalInfo::EvaluatingDeclKind::Ctor:
  2732. // The variable whose initializer we're evaluating.
  2733. if (BaseD)
  2734. return declaresSameEntity(Evaluating, BaseD);
  2735. // A temporary lifetime-extended by the variable whose initializer we're
  2736. // evaluating.
  2737. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2738. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2739. return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
  2740. return false;
  2741. case EvalInfo::EvaluatingDeclKind::Dtor:
  2742. // C++2a [expr.const]p6:
  2743. // [during constant destruction] the lifetime of a and its non-mutable
  2744. // subobjects (but not its mutable subobjects) [are] considered to start
  2745. // within e.
  2746. //
  2747. // FIXME: We can meaningfully extend this to cover non-const objects, but
  2748. // we will need special handling: we should be able to access only
  2749. // subobjects of such objects that are themselves declared const.
  2750. if (!BaseD ||
  2751. !(BaseD->getType().isConstQualified() ||
  2752. BaseD->getType()->isReferenceType()) ||
  2753. MutableSubobject)
  2754. return false;
  2755. return declaresSameEntity(Evaluating, BaseD);
  2756. }
  2757. llvm_unreachable("unknown evaluating decl kind");
  2758. }
  2759. namespace {
  2760. /// A handle to a complete object (an object that is not a subobject of
  2761. /// another object).
  2762. struct CompleteObject {
  2763. /// The identity of the object.
  2764. APValue::LValueBase Base;
  2765. /// The value of the complete object.
  2766. APValue *Value;
  2767. /// The type of the complete object.
  2768. QualType Type;
  2769. CompleteObject() : Value(nullptr) {}
  2770. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2771. : Base(Base), Value(Value), Type(Type) {}
  2772. bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
  2773. // In C++14 onwards, it is permitted to read a mutable member whose
  2774. // lifetime began within the evaluation.
  2775. // FIXME: Should we also allow this in C++11?
  2776. if (!Info.getLangOpts().CPlusPlus14)
  2777. return false;
  2778. return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
  2779. }
  2780. explicit operator bool() const { return !Type.isNull(); }
  2781. };
  2782. } // end anonymous namespace
  2783. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2784. bool IsMutable = false) {
  2785. // C++ [basic.type.qualifier]p1:
  2786. // - A const object is an object of type const T or a non-mutable subobject
  2787. // of a const object.
  2788. if (ObjType.isConstQualified() && !IsMutable)
  2789. SubobjType.addConst();
  2790. // - A volatile object is an object of type const T or a subobject of a
  2791. // volatile object.
  2792. if (ObjType.isVolatileQualified())
  2793. SubobjType.addVolatile();
  2794. return SubobjType;
  2795. }
  2796. /// Find the designated sub-object of an rvalue.
  2797. template<typename SubobjectHandler>
  2798. typename SubobjectHandler::result_type
  2799. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2800. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2801. if (Sub.Invalid)
  2802. // A diagnostic will have already been produced.
  2803. return handler.failed();
  2804. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2805. if (Info.getLangOpts().CPlusPlus11)
  2806. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2807. ? diag::note_constexpr_access_past_end
  2808. : diag::note_constexpr_access_unsized_array)
  2809. << handler.AccessKind;
  2810. else
  2811. Info.FFDiag(E);
  2812. return handler.failed();
  2813. }
  2814. APValue *O = Obj.Value;
  2815. QualType ObjType = Obj.Type;
  2816. const FieldDecl *LastField = nullptr;
  2817. const FieldDecl *VolatileField = nullptr;
  2818. // Walk the designator's path to find the subobject.
  2819. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2820. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2821. if ((O->isAbsent() && handler.AccessKind != AK_Construct) ||
  2822. (O->isIndeterminate() && handler.AccessKind != AK_Construct &&
  2823. handler.AccessKind != AK_Assign &&
  2824. handler.AccessKind != AK_ReadObjectRepresentation)) {
  2825. if (!Info.checkingPotentialConstantExpression())
  2826. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2827. << handler.AccessKind << O->isIndeterminate();
  2828. return handler.failed();
  2829. }
  2830. // C++ [class.ctor]p5, C++ [class.dtor]p5:
  2831. // const and volatile semantics are not applied on an object under
  2832. // {con,de}struction.
  2833. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2834. ObjType->isRecordType() &&
  2835. Info.isEvaluatingCtorDtor(
  2836. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2837. Sub.Entries.begin() + I)) !=
  2838. ConstructionPhase::None) {
  2839. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2840. ObjType.removeLocalConst();
  2841. ObjType.removeLocalVolatile();
  2842. }
  2843. // If this is our last pass, check that the final object type is OK.
  2844. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2845. // Accesses to volatile objects are prohibited.
  2846. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2847. if (Info.getLangOpts().CPlusPlus) {
  2848. int DiagKind;
  2849. SourceLocation Loc;
  2850. const NamedDecl *Decl = nullptr;
  2851. if (VolatileField) {
  2852. DiagKind = 2;
  2853. Loc = VolatileField->getLocation();
  2854. Decl = VolatileField;
  2855. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2856. DiagKind = 1;
  2857. Loc = VD->getLocation();
  2858. Decl = VD;
  2859. } else {
  2860. DiagKind = 0;
  2861. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2862. Loc = E->getExprLoc();
  2863. }
  2864. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2865. << handler.AccessKind << DiagKind << Decl;
  2866. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2867. } else {
  2868. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2869. }
  2870. return handler.failed();
  2871. }
  2872. // If we are reading an object of class type, there may still be more
  2873. // things we need to check: if there are any mutable subobjects, we
  2874. // cannot perform this read. (This only happens when performing a trivial
  2875. // copy or assignment.)
  2876. if (ObjType->isRecordType() &&
  2877. !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
  2878. diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
  2879. return handler.failed();
  2880. }
  2881. if (I == N) {
  2882. if (!handler.found(*O, ObjType))
  2883. return false;
  2884. // If we modified a bit-field, truncate it to the right width.
  2885. if (isModification(handler.AccessKind) &&
  2886. LastField && LastField->isBitField() &&
  2887. !truncateBitfieldValue(Info, E, *O, LastField))
  2888. return false;
  2889. return true;
  2890. }
  2891. LastField = nullptr;
  2892. if (ObjType->isArrayType()) {
  2893. // Next subobject is an array element.
  2894. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2895. assert(CAT && "vla in literal type?");
  2896. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2897. if (CAT->getSize().ule(Index)) {
  2898. // Note, it should not be possible to form a pointer with a valid
  2899. // designator which points more than one past the end of the array.
  2900. if (Info.getLangOpts().CPlusPlus11)
  2901. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2902. << handler.AccessKind;
  2903. else
  2904. Info.FFDiag(E);
  2905. return handler.failed();
  2906. }
  2907. ObjType = CAT->getElementType();
  2908. if (O->getArrayInitializedElts() > Index)
  2909. O = &O->getArrayInitializedElt(Index);
  2910. else if (!isRead(handler.AccessKind)) {
  2911. expandArray(*O, Index);
  2912. O = &O->getArrayInitializedElt(Index);
  2913. } else
  2914. O = &O->getArrayFiller();
  2915. } else if (ObjType->isAnyComplexType()) {
  2916. // Next subobject is a complex number.
  2917. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2918. if (Index > 1) {
  2919. if (Info.getLangOpts().CPlusPlus11)
  2920. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2921. << handler.AccessKind;
  2922. else
  2923. Info.FFDiag(E);
  2924. return handler.failed();
  2925. }
  2926. ObjType = getSubobjectType(
  2927. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2928. assert(I == N - 1 && "extracting subobject of scalar?");
  2929. if (O->isComplexInt()) {
  2930. return handler.found(Index ? O->getComplexIntImag()
  2931. : O->getComplexIntReal(), ObjType);
  2932. } else {
  2933. assert(O->isComplexFloat());
  2934. return handler.found(Index ? O->getComplexFloatImag()
  2935. : O->getComplexFloatReal(), ObjType);
  2936. }
  2937. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2938. if (Field->isMutable() &&
  2939. !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
  2940. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
  2941. << handler.AccessKind << Field;
  2942. Info.Note(Field->getLocation(), diag::note_declared_at);
  2943. return handler.failed();
  2944. }
  2945. // Next subobject is a class, struct or union field.
  2946. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2947. if (RD->isUnion()) {
  2948. const FieldDecl *UnionField = O->getUnionField();
  2949. if (!UnionField ||
  2950. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2951. if (I == N - 1 && handler.AccessKind == AK_Construct) {
  2952. // Placement new onto an inactive union member makes it active.
  2953. O->setUnion(Field, APValue());
  2954. } else {
  2955. // FIXME: If O->getUnionValue() is absent, report that there's no
  2956. // active union member rather than reporting the prior active union
  2957. // member. We'll need to fix nullptr_t to not use APValue() as its
  2958. // representation first.
  2959. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2960. << handler.AccessKind << Field << !UnionField << UnionField;
  2961. return handler.failed();
  2962. }
  2963. }
  2964. O = &O->getUnionValue();
  2965. } else
  2966. O = &O->getStructField(Field->getFieldIndex());
  2967. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2968. LastField = Field;
  2969. if (Field->getType().isVolatileQualified())
  2970. VolatileField = Field;
  2971. } else {
  2972. // Next subobject is a base class.
  2973. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2974. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2975. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2976. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2977. }
  2978. }
  2979. }
  2980. namespace {
  2981. struct ExtractSubobjectHandler {
  2982. EvalInfo &Info;
  2983. const Expr *E;
  2984. APValue &Result;
  2985. const AccessKinds AccessKind;
  2986. typedef bool result_type;
  2987. bool failed() { return false; }
  2988. bool found(APValue &Subobj, QualType SubobjType) {
  2989. Result = Subobj;
  2990. if (AccessKind == AK_ReadObjectRepresentation)
  2991. return true;
  2992. return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
  2993. }
  2994. bool found(APSInt &Value, QualType SubobjType) {
  2995. Result = APValue(Value);
  2996. return true;
  2997. }
  2998. bool found(APFloat &Value, QualType SubobjType) {
  2999. Result = APValue(Value);
  3000. return true;
  3001. }
  3002. };
  3003. } // end anonymous namespace
  3004. /// Extract the designated sub-object of an rvalue.
  3005. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  3006. const CompleteObject &Obj,
  3007. const SubobjectDesignator &Sub, APValue &Result,
  3008. AccessKinds AK = AK_Read) {
  3009. assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
  3010. ExtractSubobjectHandler Handler = {Info, E, Result, AK};
  3011. return findSubobject(Info, E, Obj, Sub, Handler);
  3012. }
  3013. namespace {
  3014. struct ModifySubobjectHandler {
  3015. EvalInfo &Info;
  3016. APValue &NewVal;
  3017. const Expr *E;
  3018. typedef bool result_type;
  3019. static const AccessKinds AccessKind = AK_Assign;
  3020. bool checkConst(QualType QT) {
  3021. // Assigning to a const object has undefined behavior.
  3022. if (QT.isConstQualified()) {
  3023. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3024. return false;
  3025. }
  3026. return true;
  3027. }
  3028. bool failed() { return false; }
  3029. bool found(APValue &Subobj, QualType SubobjType) {
  3030. if (!checkConst(SubobjType))
  3031. return false;
  3032. // We've been given ownership of NewVal, so just swap it in.
  3033. Subobj.swap(NewVal);
  3034. return true;
  3035. }
  3036. bool found(APSInt &Value, QualType SubobjType) {
  3037. if (!checkConst(SubobjType))
  3038. return false;
  3039. if (!NewVal.isInt()) {
  3040. // Maybe trying to write a cast pointer value into a complex?
  3041. Info.FFDiag(E);
  3042. return false;
  3043. }
  3044. Value = NewVal.getInt();
  3045. return true;
  3046. }
  3047. bool found(APFloat &Value, QualType SubobjType) {
  3048. if (!checkConst(SubobjType))
  3049. return false;
  3050. Value = NewVal.getFloat();
  3051. return true;
  3052. }
  3053. };
  3054. } // end anonymous namespace
  3055. const AccessKinds ModifySubobjectHandler::AccessKind;
  3056. /// Update the designated sub-object of an rvalue to the given value.
  3057. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  3058. const CompleteObject &Obj,
  3059. const SubobjectDesignator &Sub,
  3060. APValue &NewVal) {
  3061. ModifySubobjectHandler Handler = { Info, NewVal, E };
  3062. return findSubobject(Info, E, Obj, Sub, Handler);
  3063. }
  3064. /// Find the position where two subobject designators diverge, or equivalently
  3065. /// the length of the common initial subsequence.
  3066. static unsigned FindDesignatorMismatch(QualType ObjType,
  3067. const SubobjectDesignator &A,
  3068. const SubobjectDesignator &B,
  3069. bool &WasArrayIndex) {
  3070. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  3071. for (/**/; I != N; ++I) {
  3072. if (!ObjType.isNull() &&
  3073. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  3074. // Next subobject is an array element.
  3075. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  3076. WasArrayIndex = true;
  3077. return I;
  3078. }
  3079. if (ObjType->isAnyComplexType())
  3080. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  3081. else
  3082. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  3083. } else {
  3084. if (A.Entries[I].getAsBaseOrMember() !=
  3085. B.Entries[I].getAsBaseOrMember()) {
  3086. WasArrayIndex = false;
  3087. return I;
  3088. }
  3089. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  3090. // Next subobject is a field.
  3091. ObjType = FD->getType();
  3092. else
  3093. // Next subobject is a base class.
  3094. ObjType = QualType();
  3095. }
  3096. }
  3097. WasArrayIndex = false;
  3098. return I;
  3099. }
  3100. /// Determine whether the given subobject designators refer to elements of the
  3101. /// same array object.
  3102. static bool AreElementsOfSameArray(QualType ObjType,
  3103. const SubobjectDesignator &A,
  3104. const SubobjectDesignator &B) {
  3105. if (A.Entries.size() != B.Entries.size())
  3106. return false;
  3107. bool IsArray = A.MostDerivedIsArrayElement;
  3108. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  3109. // A is a subobject of the array element.
  3110. return false;
  3111. // If A (and B) designates an array element, the last entry will be the array
  3112. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  3113. // of length 1' case, and the entire path must match.
  3114. bool WasArrayIndex;
  3115. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  3116. return CommonLength >= A.Entries.size() - IsArray;
  3117. }
  3118. /// Find the complete object to which an LValue refers.
  3119. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  3120. AccessKinds AK, const LValue &LVal,
  3121. QualType LValType) {
  3122. if (LVal.InvalidBase) {
  3123. Info.FFDiag(E);
  3124. return CompleteObject();
  3125. }
  3126. if (!LVal.Base) {
  3127. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  3128. return CompleteObject();
  3129. }
  3130. CallStackFrame *Frame = nullptr;
  3131. unsigned Depth = 0;
  3132. if (LVal.getLValueCallIndex()) {
  3133. std::tie(Frame, Depth) =
  3134. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  3135. if (!Frame) {
  3136. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  3137. << AK << LVal.Base.is<const ValueDecl*>();
  3138. NoteLValueLocation(Info, LVal.Base);
  3139. return CompleteObject();
  3140. }
  3141. }
  3142. bool IsAccess = isAnyAccess(AK);
  3143. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  3144. // is not a constant expression (even if the object is non-volatile). We also
  3145. // apply this rule to C++98, in order to conform to the expected 'volatile'
  3146. // semantics.
  3147. if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
  3148. if (Info.getLangOpts().CPlusPlus)
  3149. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  3150. << AK << LValType;
  3151. else
  3152. Info.FFDiag(E);
  3153. return CompleteObject();
  3154. }
  3155. // Compute value storage location and type of base object.
  3156. APValue *BaseVal = nullptr;
  3157. QualType BaseType = getType(LVal.Base);
  3158. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  3159. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  3160. // In C++11, constexpr, non-volatile variables initialized with constant
  3161. // expressions are constant expressions too. Inside constexpr functions,
  3162. // parameters are constant expressions even if they're non-const.
  3163. // In C++1y, objects local to a constant expression (those with a Frame) are
  3164. // both readable and writable inside constant expressions.
  3165. // In C, such things can also be folded, although they are not ICEs.
  3166. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3167. if (VD) {
  3168. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3169. VD = VDef;
  3170. }
  3171. if (!VD || VD->isInvalidDecl()) {
  3172. Info.FFDiag(E);
  3173. return CompleteObject();
  3174. }
  3175. // Unless we're looking at a local variable or argument in a constexpr call,
  3176. // the variable we're reading must be const.
  3177. if (!Frame) {
  3178. if (Info.getLangOpts().CPlusPlus14 &&
  3179. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3180. // OK, we can read and modify an object if we're in the process of
  3181. // evaluating its initializer, because its lifetime began in this
  3182. // evaluation.
  3183. } else if (isModification(AK)) {
  3184. // All the remaining cases do not permit modification of the object.
  3185. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3186. return CompleteObject();
  3187. } else if (VD->isConstexpr()) {
  3188. // OK, we can read this variable.
  3189. } else if (BaseType->isIntegralOrEnumerationType()) {
  3190. // In OpenCL if a variable is in constant address space it is a const
  3191. // value.
  3192. if (!(BaseType.isConstQualified() ||
  3193. (Info.getLangOpts().OpenCL &&
  3194. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  3195. if (!IsAccess)
  3196. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3197. if (Info.getLangOpts().CPlusPlus) {
  3198. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3199. Info.Note(VD->getLocation(), diag::note_declared_at);
  3200. } else {
  3201. Info.FFDiag(E);
  3202. }
  3203. return CompleteObject();
  3204. }
  3205. } else if (!IsAccess) {
  3206. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3207. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  3208. // We support folding of const floating-point types, in order to make
  3209. // static const data members of such types (supported as an extension)
  3210. // more useful.
  3211. if (Info.getLangOpts().CPlusPlus11) {
  3212. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3213. Info.Note(VD->getLocation(), diag::note_declared_at);
  3214. } else {
  3215. Info.CCEDiag(E);
  3216. }
  3217. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3218. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3219. // Keep evaluating to see what we can do.
  3220. } else {
  3221. // FIXME: Allow folding of values of any literal type in all languages.
  3222. if (Info.checkingPotentialConstantExpression() &&
  3223. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3224. // The definition of this variable could be constexpr. We can't
  3225. // access it right now, but may be able to in future.
  3226. } else if (Info.getLangOpts().CPlusPlus11) {
  3227. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3228. Info.Note(VD->getLocation(), diag::note_declared_at);
  3229. } else {
  3230. Info.FFDiag(E);
  3231. }
  3232. return CompleteObject();
  3233. }
  3234. }
  3235. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3236. return CompleteObject();
  3237. } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
  3238. Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  3239. if (!Alloc) {
  3240. Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
  3241. return CompleteObject();
  3242. }
  3243. return CompleteObject(LVal.Base, &(*Alloc)->Value,
  3244. LVal.Base.getDynamicAllocType());
  3245. } else {
  3246. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3247. if (!Frame) {
  3248. if (const MaterializeTemporaryExpr *MTE =
  3249. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3250. assert(MTE->getStorageDuration() == SD_Static &&
  3251. "should have a frame for a non-global materialized temporary");
  3252. // Per C++1y [expr.const]p2:
  3253. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3254. // - a [...] glvalue of integral or enumeration type that refers to
  3255. // a non-volatile const object [...]
  3256. // [...]
  3257. // - a [...] glvalue of literal type that refers to a non-volatile
  3258. // object whose lifetime began within the evaluation of e.
  3259. //
  3260. // C++11 misses the 'began within the evaluation of e' check and
  3261. // instead allows all temporaries, including things like:
  3262. // int &&r = 1;
  3263. // int x = ++r;
  3264. // constexpr int k = r;
  3265. // Therefore we use the C++14 rules in C++11 too.
  3266. //
  3267. // Note that temporaries whose lifetimes began while evaluating a
  3268. // variable's constructor are not usable while evaluating the
  3269. // corresponding destructor, not even if they're of const-qualified
  3270. // types.
  3271. if (!(BaseType.isConstQualified() &&
  3272. BaseType->isIntegralOrEnumerationType()) &&
  3273. !lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3274. if (!IsAccess)
  3275. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3276. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3277. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3278. return CompleteObject();
  3279. }
  3280. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3281. assert(BaseVal && "got reference to unevaluated temporary");
  3282. } else {
  3283. if (!IsAccess)
  3284. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3285. APValue Val;
  3286. LVal.moveInto(Val);
  3287. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3288. << AK
  3289. << Val.getAsString(Info.Ctx,
  3290. Info.Ctx.getLValueReferenceType(LValType));
  3291. NoteLValueLocation(Info, LVal.Base);
  3292. return CompleteObject();
  3293. }
  3294. } else {
  3295. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3296. assert(BaseVal && "missing value for temporary");
  3297. }
  3298. }
  3299. // In C++14, we can't safely access any mutable state when we might be
  3300. // evaluating after an unmodeled side effect.
  3301. //
  3302. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3303. // to be read here (but take care with 'mutable' fields).
  3304. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3305. Info.EvalStatus.HasSideEffects) ||
  3306. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3307. return CompleteObject();
  3308. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3309. }
  3310. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3311. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3312. /// glvalue referred to by an entity of reference type.
  3313. ///
  3314. /// \param Info - Information about the ongoing evaluation.
  3315. /// \param Conv - The expression for which we are performing the conversion.
  3316. /// Used for diagnostics.
  3317. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3318. /// case of a non-class type).
  3319. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3320. /// \param RVal - The produced value will be placed here.
  3321. /// \param WantObjectRepresentation - If true, we're looking for the object
  3322. /// representation rather than the value, and in particular,
  3323. /// there is no requirement that the result be fully initialized.
  3324. static bool
  3325. handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
  3326. const LValue &LVal, APValue &RVal,
  3327. bool WantObjectRepresentation = false) {
  3328. if (LVal.Designator.Invalid)
  3329. return false;
  3330. // Check for special cases where there is no existing APValue to look at.
  3331. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3332. AccessKinds AK =
  3333. WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
  3334. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3335. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3336. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3337. // initializer until now for such expressions. Such an expression can't be
  3338. // an ICE in C, so this only matters for fold.
  3339. if (Type.isVolatileQualified()) {
  3340. Info.FFDiag(Conv);
  3341. return false;
  3342. }
  3343. APValue Lit;
  3344. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3345. return false;
  3346. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3347. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
  3348. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3349. // Special-case character extraction so we don't have to construct an
  3350. // APValue for the whole string.
  3351. assert(LVal.Designator.Entries.size() <= 1 &&
  3352. "Can only read characters from string literals");
  3353. if (LVal.Designator.Entries.empty()) {
  3354. // Fail for now for LValue to RValue conversion of an array.
  3355. // (This shouldn't show up in C/C++, but it could be triggered by a
  3356. // weird EvaluateAsRValue call from a tool.)
  3357. Info.FFDiag(Conv);
  3358. return false;
  3359. }
  3360. if (LVal.Designator.isOnePastTheEnd()) {
  3361. if (Info.getLangOpts().CPlusPlus11)
  3362. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
  3363. else
  3364. Info.FFDiag(Conv);
  3365. return false;
  3366. }
  3367. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3368. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3369. return true;
  3370. }
  3371. }
  3372. CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
  3373. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
  3374. }
  3375. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3376. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3377. QualType LValType, APValue &Val) {
  3378. if (LVal.Designator.Invalid)
  3379. return false;
  3380. if (!Info.getLangOpts().CPlusPlus14) {
  3381. Info.FFDiag(E);
  3382. return false;
  3383. }
  3384. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3385. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3386. }
  3387. namespace {
  3388. struct CompoundAssignSubobjectHandler {
  3389. EvalInfo &Info;
  3390. const Expr *E;
  3391. QualType PromotedLHSType;
  3392. BinaryOperatorKind Opcode;
  3393. const APValue &RHS;
  3394. static const AccessKinds AccessKind = AK_Assign;
  3395. typedef bool result_type;
  3396. bool checkConst(QualType QT) {
  3397. // Assigning to a const object has undefined behavior.
  3398. if (QT.isConstQualified()) {
  3399. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3400. return false;
  3401. }
  3402. return true;
  3403. }
  3404. bool failed() { return false; }
  3405. bool found(APValue &Subobj, QualType SubobjType) {
  3406. switch (Subobj.getKind()) {
  3407. case APValue::Int:
  3408. return found(Subobj.getInt(), SubobjType);
  3409. case APValue::Float:
  3410. return found(Subobj.getFloat(), SubobjType);
  3411. case APValue::ComplexInt:
  3412. case APValue::ComplexFloat:
  3413. // FIXME: Implement complex compound assignment.
  3414. Info.FFDiag(E);
  3415. return false;
  3416. case APValue::LValue:
  3417. return foundPointer(Subobj, SubobjType);
  3418. default:
  3419. // FIXME: can this happen?
  3420. Info.FFDiag(E);
  3421. return false;
  3422. }
  3423. }
  3424. bool found(APSInt &Value, QualType SubobjType) {
  3425. if (!checkConst(SubobjType))
  3426. return false;
  3427. if (!SubobjType->isIntegerType()) {
  3428. // We don't support compound assignment on integer-cast-to-pointer
  3429. // values.
  3430. Info.FFDiag(E);
  3431. return false;
  3432. }
  3433. if (RHS.isInt()) {
  3434. APSInt LHS =
  3435. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3436. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3437. return false;
  3438. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3439. return true;
  3440. } else if (RHS.isFloat()) {
  3441. APFloat FValue(0.0);
  3442. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3443. FValue) &&
  3444. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3445. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3446. Value);
  3447. }
  3448. Info.FFDiag(E);
  3449. return false;
  3450. }
  3451. bool found(APFloat &Value, QualType SubobjType) {
  3452. return checkConst(SubobjType) &&
  3453. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3454. Value) &&
  3455. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3456. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3457. }
  3458. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3459. if (!checkConst(SubobjType))
  3460. return false;
  3461. QualType PointeeType;
  3462. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3463. PointeeType = PT->getPointeeType();
  3464. if (PointeeType.isNull() || !RHS.isInt() ||
  3465. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3466. Info.FFDiag(E);
  3467. return false;
  3468. }
  3469. APSInt Offset = RHS.getInt();
  3470. if (Opcode == BO_Sub)
  3471. negateAsSigned(Offset);
  3472. LValue LVal;
  3473. LVal.setFrom(Info.Ctx, Subobj);
  3474. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3475. return false;
  3476. LVal.moveInto(Subobj);
  3477. return true;
  3478. }
  3479. };
  3480. } // end anonymous namespace
  3481. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3482. /// Perform a compound assignment of LVal <op>= RVal.
  3483. static bool handleCompoundAssignment(
  3484. EvalInfo &Info, const Expr *E,
  3485. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3486. BinaryOperatorKind Opcode, const APValue &RVal) {
  3487. if (LVal.Designator.Invalid)
  3488. return false;
  3489. if (!Info.getLangOpts().CPlusPlus14) {
  3490. Info.FFDiag(E);
  3491. return false;
  3492. }
  3493. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3494. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3495. RVal };
  3496. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3497. }
  3498. namespace {
  3499. struct IncDecSubobjectHandler {
  3500. EvalInfo &Info;
  3501. const UnaryOperator *E;
  3502. AccessKinds AccessKind;
  3503. APValue *Old;
  3504. typedef bool result_type;
  3505. bool checkConst(QualType QT) {
  3506. // Assigning to a const object has undefined behavior.
  3507. if (QT.isConstQualified()) {
  3508. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3509. return false;
  3510. }
  3511. return true;
  3512. }
  3513. bool failed() { return false; }
  3514. bool found(APValue &Subobj, QualType SubobjType) {
  3515. // Stash the old value. Also clear Old, so we don't clobber it later
  3516. // if we're post-incrementing a complex.
  3517. if (Old) {
  3518. *Old = Subobj;
  3519. Old = nullptr;
  3520. }
  3521. switch (Subobj.getKind()) {
  3522. case APValue::Int:
  3523. return found(Subobj.getInt(), SubobjType);
  3524. case APValue::Float:
  3525. return found(Subobj.getFloat(), SubobjType);
  3526. case APValue::ComplexInt:
  3527. return found(Subobj.getComplexIntReal(),
  3528. SubobjType->castAs<ComplexType>()->getElementType()
  3529. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3530. case APValue::ComplexFloat:
  3531. return found(Subobj.getComplexFloatReal(),
  3532. SubobjType->castAs<ComplexType>()->getElementType()
  3533. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3534. case APValue::LValue:
  3535. return foundPointer(Subobj, SubobjType);
  3536. default:
  3537. // FIXME: can this happen?
  3538. Info.FFDiag(E);
  3539. return false;
  3540. }
  3541. }
  3542. bool found(APSInt &Value, QualType SubobjType) {
  3543. if (!checkConst(SubobjType))
  3544. return false;
  3545. if (!SubobjType->isIntegerType()) {
  3546. // We don't support increment / decrement on integer-cast-to-pointer
  3547. // values.
  3548. Info.FFDiag(E);
  3549. return false;
  3550. }
  3551. if (Old) *Old = APValue(Value);
  3552. // bool arithmetic promotes to int, and the conversion back to bool
  3553. // doesn't reduce mod 2^n, so special-case it.
  3554. if (SubobjType->isBooleanType()) {
  3555. if (AccessKind == AK_Increment)
  3556. Value = 1;
  3557. else
  3558. Value = !Value;
  3559. return true;
  3560. }
  3561. bool WasNegative = Value.isNegative();
  3562. if (AccessKind == AK_Increment) {
  3563. ++Value;
  3564. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3565. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3566. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3567. }
  3568. } else {
  3569. --Value;
  3570. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3571. unsigned BitWidth = Value.getBitWidth();
  3572. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3573. ActualValue.setBit(BitWidth);
  3574. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3575. }
  3576. }
  3577. return true;
  3578. }
  3579. bool found(APFloat &Value, QualType SubobjType) {
  3580. if (!checkConst(SubobjType))
  3581. return false;
  3582. if (Old) *Old = APValue(Value);
  3583. APFloat One(Value.getSemantics(), 1);
  3584. if (AccessKind == AK_Increment)
  3585. Value.add(One, APFloat::rmNearestTiesToEven);
  3586. else
  3587. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3588. return true;
  3589. }
  3590. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3591. if (!checkConst(SubobjType))
  3592. return false;
  3593. QualType PointeeType;
  3594. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3595. PointeeType = PT->getPointeeType();
  3596. else {
  3597. Info.FFDiag(E);
  3598. return false;
  3599. }
  3600. LValue LVal;
  3601. LVal.setFrom(Info.Ctx, Subobj);
  3602. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3603. AccessKind == AK_Increment ? 1 : -1))
  3604. return false;
  3605. LVal.moveInto(Subobj);
  3606. return true;
  3607. }
  3608. };
  3609. } // end anonymous namespace
  3610. /// Perform an increment or decrement on LVal.
  3611. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3612. QualType LValType, bool IsIncrement, APValue *Old) {
  3613. if (LVal.Designator.Invalid)
  3614. return false;
  3615. if (!Info.getLangOpts().CPlusPlus14) {
  3616. Info.FFDiag(E);
  3617. return false;
  3618. }
  3619. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3620. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3621. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3622. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3623. }
  3624. /// Build an lvalue for the object argument of a member function call.
  3625. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3626. LValue &This) {
  3627. if (Object->getType()->isPointerType() && Object->isRValue())
  3628. return EvaluatePointer(Object, This, Info);
  3629. if (Object->isGLValue())
  3630. return EvaluateLValue(Object, This, Info);
  3631. if (Object->getType()->isLiteralType(Info.Ctx))
  3632. return EvaluateTemporary(Object, This, Info);
  3633. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3634. return false;
  3635. }
  3636. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3637. /// lvalue referring to the result.
  3638. ///
  3639. /// \param Info - Information about the ongoing evaluation.
  3640. /// \param LV - An lvalue referring to the base of the member pointer.
  3641. /// \param RHS - The member pointer expression.
  3642. /// \param IncludeMember - Specifies whether the member itself is included in
  3643. /// the resulting LValue subobject designator. This is not possible when
  3644. /// creating a bound member function.
  3645. /// \return The field or method declaration to which the member pointer refers,
  3646. /// or 0 if evaluation fails.
  3647. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3648. QualType LVType,
  3649. LValue &LV,
  3650. const Expr *RHS,
  3651. bool IncludeMember = true) {
  3652. MemberPtr MemPtr;
  3653. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3654. return nullptr;
  3655. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3656. // member value, the behavior is undefined.
  3657. if (!MemPtr.getDecl()) {
  3658. // FIXME: Specific diagnostic.
  3659. Info.FFDiag(RHS);
  3660. return nullptr;
  3661. }
  3662. if (MemPtr.isDerivedMember()) {
  3663. // This is a member of some derived class. Truncate LV appropriately.
  3664. // The end of the derived-to-base path for the base object must match the
  3665. // derived-to-base path for the member pointer.
  3666. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3667. LV.Designator.Entries.size()) {
  3668. Info.FFDiag(RHS);
  3669. return nullptr;
  3670. }
  3671. unsigned PathLengthToMember =
  3672. LV.Designator.Entries.size() - MemPtr.Path.size();
  3673. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3674. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3675. LV.Designator.Entries[PathLengthToMember + I]);
  3676. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3677. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3678. Info.FFDiag(RHS);
  3679. return nullptr;
  3680. }
  3681. }
  3682. // Truncate the lvalue to the appropriate derived class.
  3683. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3684. PathLengthToMember))
  3685. return nullptr;
  3686. } else if (!MemPtr.Path.empty()) {
  3687. // Extend the LValue path with the member pointer's path.
  3688. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3689. MemPtr.Path.size() + IncludeMember);
  3690. // Walk down to the appropriate base class.
  3691. if (const PointerType *PT = LVType->getAs<PointerType>())
  3692. LVType = PT->getPointeeType();
  3693. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3694. assert(RD && "member pointer access on non-class-type expression");
  3695. // The first class in the path is that of the lvalue.
  3696. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3697. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3698. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3699. return nullptr;
  3700. RD = Base;
  3701. }
  3702. // Finally cast to the class containing the member.
  3703. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3704. MemPtr.getContainingRecord()))
  3705. return nullptr;
  3706. }
  3707. // Add the member. Note that we cannot build bound member functions here.
  3708. if (IncludeMember) {
  3709. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3710. if (!HandleLValueMember(Info, RHS, LV, FD))
  3711. return nullptr;
  3712. } else if (const IndirectFieldDecl *IFD =
  3713. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3714. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3715. return nullptr;
  3716. } else {
  3717. llvm_unreachable("can't construct reference to bound member function");
  3718. }
  3719. }
  3720. return MemPtr.getDecl();
  3721. }
  3722. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3723. const BinaryOperator *BO,
  3724. LValue &LV,
  3725. bool IncludeMember = true) {
  3726. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3727. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3728. if (Info.noteFailure()) {
  3729. MemberPtr MemPtr;
  3730. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3731. }
  3732. return nullptr;
  3733. }
  3734. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3735. BO->getRHS(), IncludeMember);
  3736. }
  3737. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3738. /// the provided lvalue, which currently refers to the base object.
  3739. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3740. LValue &Result) {
  3741. SubobjectDesignator &D = Result.Designator;
  3742. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3743. return false;
  3744. QualType TargetQT = E->getType();
  3745. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3746. TargetQT = PT->getPointeeType();
  3747. // Check this cast lands within the final derived-to-base subobject path.
  3748. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3749. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3750. << D.MostDerivedType << TargetQT;
  3751. return false;
  3752. }
  3753. // Check the type of the final cast. We don't need to check the path,
  3754. // since a cast can only be formed if the path is unique.
  3755. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3756. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3757. const CXXRecordDecl *FinalType;
  3758. if (NewEntriesSize == D.MostDerivedPathLength)
  3759. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3760. else
  3761. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3762. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3763. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3764. << D.MostDerivedType << TargetQT;
  3765. return false;
  3766. }
  3767. // Truncate the lvalue to the appropriate derived class.
  3768. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3769. }
  3770. /// Get the value to use for a default-initialized object of type T.
  3771. static APValue getDefaultInitValue(QualType T) {
  3772. if (auto *RD = T->getAsCXXRecordDecl()) {
  3773. if (RD->isUnion())
  3774. return APValue((const FieldDecl*)nullptr);
  3775. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  3776. std::distance(RD->field_begin(), RD->field_end()));
  3777. unsigned Index = 0;
  3778. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  3779. End = RD->bases_end(); I != End; ++I, ++Index)
  3780. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  3781. for (const auto *I : RD->fields()) {
  3782. if (I->isUnnamedBitfield())
  3783. continue;
  3784. Struct.getStructField(I->getFieldIndex()) =
  3785. getDefaultInitValue(I->getType());
  3786. }
  3787. return Struct;
  3788. }
  3789. if (auto *AT =
  3790. dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
  3791. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  3792. if (Array.hasArrayFiller())
  3793. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  3794. return Array;
  3795. }
  3796. return APValue::IndeterminateValue();
  3797. }
  3798. namespace {
  3799. enum EvalStmtResult {
  3800. /// Evaluation failed.
  3801. ESR_Failed,
  3802. /// Hit a 'return' statement.
  3803. ESR_Returned,
  3804. /// Evaluation succeeded.
  3805. ESR_Succeeded,
  3806. /// Hit a 'continue' statement.
  3807. ESR_Continue,
  3808. /// Hit a 'break' statement.
  3809. ESR_Break,
  3810. /// Still scanning for 'case' or 'default' statement.
  3811. ESR_CaseNotFound
  3812. };
  3813. }
  3814. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3815. // We don't need to evaluate the initializer for a static local.
  3816. if (!VD->hasLocalStorage())
  3817. return true;
  3818. LValue Result;
  3819. APValue &Val =
  3820. Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
  3821. const Expr *InitE = VD->getInit();
  3822. if (!InitE) {
  3823. Val = getDefaultInitValue(VD->getType());
  3824. return true;
  3825. }
  3826. if (InitE->isValueDependent())
  3827. return false;
  3828. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3829. // Wipe out any partially-computed value, to allow tracking that this
  3830. // evaluation failed.
  3831. Val = APValue();
  3832. return false;
  3833. }
  3834. return true;
  3835. }
  3836. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3837. bool OK = true;
  3838. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3839. OK &= EvaluateVarDecl(Info, VD);
  3840. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3841. for (auto *BD : DD->bindings())
  3842. if (auto *VD = BD->getHoldingVar())
  3843. OK &= EvaluateDecl(Info, VD);
  3844. return OK;
  3845. }
  3846. /// Evaluate a condition (either a variable declaration or an expression).
  3847. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3848. const Expr *Cond, bool &Result) {
  3849. FullExpressionRAII Scope(Info);
  3850. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3851. return false;
  3852. if (!EvaluateAsBooleanCondition(Cond, Result, Info))
  3853. return false;
  3854. return Scope.destroy();
  3855. }
  3856. namespace {
  3857. /// A location where the result (returned value) of evaluating a
  3858. /// statement should be stored.
  3859. struct StmtResult {
  3860. /// The APValue that should be filled in with the returned value.
  3861. APValue &Value;
  3862. /// The location containing the result, if any (used to support RVO).
  3863. const LValue *Slot;
  3864. };
  3865. struct TempVersionRAII {
  3866. CallStackFrame &Frame;
  3867. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3868. Frame.pushTempVersion();
  3869. }
  3870. ~TempVersionRAII() {
  3871. Frame.popTempVersion();
  3872. }
  3873. };
  3874. }
  3875. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3876. const Stmt *S,
  3877. const SwitchCase *SC = nullptr);
  3878. /// Evaluate the body of a loop, and translate the result as appropriate.
  3879. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3880. const Stmt *Body,
  3881. const SwitchCase *Case = nullptr) {
  3882. BlockScopeRAII Scope(Info);
  3883. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
  3884. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3885. ESR = ESR_Failed;
  3886. switch (ESR) {
  3887. case ESR_Break:
  3888. return ESR_Succeeded;
  3889. case ESR_Succeeded:
  3890. case ESR_Continue:
  3891. return ESR_Continue;
  3892. case ESR_Failed:
  3893. case ESR_Returned:
  3894. case ESR_CaseNotFound:
  3895. return ESR;
  3896. }
  3897. llvm_unreachable("Invalid EvalStmtResult!");
  3898. }
  3899. /// Evaluate a switch statement.
  3900. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3901. const SwitchStmt *SS) {
  3902. BlockScopeRAII Scope(Info);
  3903. // Evaluate the switch condition.
  3904. APSInt Value;
  3905. {
  3906. if (const Stmt *Init = SS->getInit()) {
  3907. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3908. if (ESR != ESR_Succeeded) {
  3909. if (ESR != ESR_Failed && !Scope.destroy())
  3910. ESR = ESR_Failed;
  3911. return ESR;
  3912. }
  3913. }
  3914. FullExpressionRAII CondScope(Info);
  3915. if (SS->getConditionVariable() &&
  3916. !EvaluateDecl(Info, SS->getConditionVariable()))
  3917. return ESR_Failed;
  3918. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3919. return ESR_Failed;
  3920. if (!CondScope.destroy())
  3921. return ESR_Failed;
  3922. }
  3923. // Find the switch case corresponding to the value of the condition.
  3924. // FIXME: Cache this lookup.
  3925. const SwitchCase *Found = nullptr;
  3926. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3927. SC = SC->getNextSwitchCase()) {
  3928. if (isa<DefaultStmt>(SC)) {
  3929. Found = SC;
  3930. continue;
  3931. }
  3932. const CaseStmt *CS = cast<CaseStmt>(SC);
  3933. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3934. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3935. : LHS;
  3936. if (LHS <= Value && Value <= RHS) {
  3937. Found = SC;
  3938. break;
  3939. }
  3940. }
  3941. if (!Found)
  3942. return Scope.destroy() ? ESR_Failed : ESR_Succeeded;
  3943. // Search the switch body for the switch case and evaluate it from there.
  3944. EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
  3945. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  3946. return ESR_Failed;
  3947. switch (ESR) {
  3948. case ESR_Break:
  3949. return ESR_Succeeded;
  3950. case ESR_Succeeded:
  3951. case ESR_Continue:
  3952. case ESR_Failed:
  3953. case ESR_Returned:
  3954. return ESR;
  3955. case ESR_CaseNotFound:
  3956. // This can only happen if the switch case is nested within a statement
  3957. // expression. We have no intention of supporting that.
  3958. Info.FFDiag(Found->getBeginLoc(),
  3959. diag::note_constexpr_stmt_expr_unsupported);
  3960. return ESR_Failed;
  3961. }
  3962. llvm_unreachable("Invalid EvalStmtResult!");
  3963. }
  3964. // Evaluate a statement.
  3965. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3966. const Stmt *S, const SwitchCase *Case) {
  3967. if (!Info.nextStep(S))
  3968. return ESR_Failed;
  3969. // If we're hunting down a 'case' or 'default' label, recurse through
  3970. // substatements until we hit the label.
  3971. if (Case) {
  3972. switch (S->getStmtClass()) {
  3973. case Stmt::CompoundStmtClass:
  3974. // FIXME: Precompute which substatement of a compound statement we
  3975. // would jump to, and go straight there rather than performing a
  3976. // linear scan each time.
  3977. case Stmt::LabelStmtClass:
  3978. case Stmt::AttributedStmtClass:
  3979. case Stmt::DoStmtClass:
  3980. break;
  3981. case Stmt::CaseStmtClass:
  3982. case Stmt::DefaultStmtClass:
  3983. if (Case == S)
  3984. Case = nullptr;
  3985. break;
  3986. case Stmt::IfStmtClass: {
  3987. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3988. // straight there rather than scanning both sides.
  3989. const IfStmt *IS = cast<IfStmt>(S);
  3990. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3991. // preceded by our switch label.
  3992. BlockScopeRAII Scope(Info);
  3993. // Step into the init statement in case it brings an (uninitialized)
  3994. // variable into scope.
  3995. if (const Stmt *Init = IS->getInit()) {
  3996. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  3997. if (ESR != ESR_CaseNotFound) {
  3998. assert(ESR != ESR_Succeeded);
  3999. return ESR;
  4000. }
  4001. }
  4002. // Condition variable must be initialized if it exists.
  4003. // FIXME: We can skip evaluating the body if there's a condition
  4004. // variable, as there can't be any case labels within it.
  4005. // (The same is true for 'for' statements.)
  4006. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  4007. if (ESR == ESR_Failed)
  4008. return ESR;
  4009. if (ESR != ESR_CaseNotFound)
  4010. return Scope.destroy() ? ESR : ESR_Failed;
  4011. if (!IS->getElse())
  4012. return ESR_CaseNotFound;
  4013. ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
  4014. if (ESR == ESR_Failed)
  4015. return ESR;
  4016. if (ESR != ESR_CaseNotFound)
  4017. return Scope.destroy() ? ESR : ESR_Failed;
  4018. return ESR_CaseNotFound;
  4019. }
  4020. case Stmt::WhileStmtClass: {
  4021. EvalStmtResult ESR =
  4022. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  4023. if (ESR != ESR_Continue)
  4024. return ESR;
  4025. break;
  4026. }
  4027. case Stmt::ForStmtClass: {
  4028. const ForStmt *FS = cast<ForStmt>(S);
  4029. BlockScopeRAII Scope(Info);
  4030. // Step into the init statement in case it brings an (uninitialized)
  4031. // variable into scope.
  4032. if (const Stmt *Init = FS->getInit()) {
  4033. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  4034. if (ESR != ESR_CaseNotFound) {
  4035. assert(ESR != ESR_Succeeded);
  4036. return ESR;
  4037. }
  4038. }
  4039. EvalStmtResult ESR =
  4040. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  4041. if (ESR != ESR_Continue)
  4042. return ESR;
  4043. if (FS->getInc()) {
  4044. FullExpressionRAII IncScope(Info);
  4045. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  4046. return ESR_Failed;
  4047. }
  4048. break;
  4049. }
  4050. case Stmt::DeclStmtClass: {
  4051. // Start the lifetime of any uninitialized variables we encounter. They
  4052. // might be used by the selected branch of the switch.
  4053. const DeclStmt *DS = cast<DeclStmt>(S);
  4054. for (const auto *D : DS->decls()) {
  4055. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4056. if (VD->hasLocalStorage() && !VD->getInit())
  4057. if (!EvaluateVarDecl(Info, VD))
  4058. return ESR_Failed;
  4059. // FIXME: If the variable has initialization that can't be jumped
  4060. // over, bail out of any immediately-surrounding compound-statement
  4061. // too. There can't be any case labels here.
  4062. }
  4063. }
  4064. return ESR_CaseNotFound;
  4065. }
  4066. default:
  4067. return ESR_CaseNotFound;
  4068. }
  4069. }
  4070. switch (S->getStmtClass()) {
  4071. default:
  4072. if (const Expr *E = dyn_cast<Expr>(S)) {
  4073. // Don't bother evaluating beyond an expression-statement which couldn't
  4074. // be evaluated.
  4075. // FIXME: Do we need the FullExpressionRAII object here?
  4076. // VisitExprWithCleanups should create one when necessary.
  4077. FullExpressionRAII Scope(Info);
  4078. if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
  4079. return ESR_Failed;
  4080. return ESR_Succeeded;
  4081. }
  4082. Info.FFDiag(S->getBeginLoc());
  4083. return ESR_Failed;
  4084. case Stmt::NullStmtClass:
  4085. return ESR_Succeeded;
  4086. case Stmt::DeclStmtClass: {
  4087. const DeclStmt *DS = cast<DeclStmt>(S);
  4088. for (const auto *D : DS->decls()) {
  4089. // Each declaration initialization is its own full-expression.
  4090. FullExpressionRAII Scope(Info);
  4091. if (!EvaluateDecl(Info, D) && !Info.noteFailure())
  4092. return ESR_Failed;
  4093. if (!Scope.destroy())
  4094. return ESR_Failed;
  4095. }
  4096. return ESR_Succeeded;
  4097. }
  4098. case Stmt::ReturnStmtClass: {
  4099. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  4100. FullExpressionRAII Scope(Info);
  4101. if (RetExpr &&
  4102. !(Result.Slot
  4103. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  4104. : Evaluate(Result.Value, Info, RetExpr)))
  4105. return ESR_Failed;
  4106. return Scope.destroy() ? ESR_Returned : ESR_Failed;
  4107. }
  4108. case Stmt::CompoundStmtClass: {
  4109. BlockScopeRAII Scope(Info);
  4110. const CompoundStmt *CS = cast<CompoundStmt>(S);
  4111. for (const auto *BI : CS->body()) {
  4112. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  4113. if (ESR == ESR_Succeeded)
  4114. Case = nullptr;
  4115. else if (ESR != ESR_CaseNotFound) {
  4116. if (ESR != ESR_Failed && !Scope.destroy())
  4117. return ESR_Failed;
  4118. return ESR;
  4119. }
  4120. }
  4121. if (Case)
  4122. return ESR_CaseNotFound;
  4123. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4124. }
  4125. case Stmt::IfStmtClass: {
  4126. const IfStmt *IS = cast<IfStmt>(S);
  4127. // Evaluate the condition, as either a var decl or as an expression.
  4128. BlockScopeRAII Scope(Info);
  4129. if (const Stmt *Init = IS->getInit()) {
  4130. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4131. if (ESR != ESR_Succeeded) {
  4132. if (ESR != ESR_Failed && !Scope.destroy())
  4133. return ESR_Failed;
  4134. return ESR;
  4135. }
  4136. }
  4137. bool Cond;
  4138. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  4139. return ESR_Failed;
  4140. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  4141. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  4142. if (ESR != ESR_Succeeded) {
  4143. if (ESR != ESR_Failed && !Scope.destroy())
  4144. return ESR_Failed;
  4145. return ESR;
  4146. }
  4147. }
  4148. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4149. }
  4150. case Stmt::WhileStmtClass: {
  4151. const WhileStmt *WS = cast<WhileStmt>(S);
  4152. while (true) {
  4153. BlockScopeRAII Scope(Info);
  4154. bool Continue;
  4155. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  4156. Continue))
  4157. return ESR_Failed;
  4158. if (!Continue)
  4159. break;
  4160. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  4161. if (ESR != ESR_Continue) {
  4162. if (ESR != ESR_Failed && !Scope.destroy())
  4163. return ESR_Failed;
  4164. return ESR;
  4165. }
  4166. if (!Scope.destroy())
  4167. return ESR_Failed;
  4168. }
  4169. return ESR_Succeeded;
  4170. }
  4171. case Stmt::DoStmtClass: {
  4172. const DoStmt *DS = cast<DoStmt>(S);
  4173. bool Continue;
  4174. do {
  4175. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  4176. if (ESR != ESR_Continue)
  4177. return ESR;
  4178. Case = nullptr;
  4179. FullExpressionRAII CondScope(Info);
  4180. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
  4181. !CondScope.destroy())
  4182. return ESR_Failed;
  4183. } while (Continue);
  4184. return ESR_Succeeded;
  4185. }
  4186. case Stmt::ForStmtClass: {
  4187. const ForStmt *FS = cast<ForStmt>(S);
  4188. BlockScopeRAII ForScope(Info);
  4189. if (FS->getInit()) {
  4190. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4191. if (ESR != ESR_Succeeded) {
  4192. if (ESR != ESR_Failed && !ForScope.destroy())
  4193. return ESR_Failed;
  4194. return ESR;
  4195. }
  4196. }
  4197. while (true) {
  4198. BlockScopeRAII IterScope(Info);
  4199. bool Continue = true;
  4200. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  4201. FS->getCond(), Continue))
  4202. return ESR_Failed;
  4203. if (!Continue)
  4204. break;
  4205. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4206. if (ESR != ESR_Continue) {
  4207. if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
  4208. return ESR_Failed;
  4209. return ESR;
  4210. }
  4211. if (FS->getInc()) {
  4212. FullExpressionRAII IncScope(Info);
  4213. if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
  4214. return ESR_Failed;
  4215. }
  4216. if (!IterScope.destroy())
  4217. return ESR_Failed;
  4218. }
  4219. return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
  4220. }
  4221. case Stmt::CXXForRangeStmtClass: {
  4222. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  4223. BlockScopeRAII Scope(Info);
  4224. // Evaluate the init-statement if present.
  4225. if (FS->getInit()) {
  4226. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4227. if (ESR != ESR_Succeeded) {
  4228. if (ESR != ESR_Failed && !Scope.destroy())
  4229. return ESR_Failed;
  4230. return ESR;
  4231. }
  4232. }
  4233. // Initialize the __range variable.
  4234. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  4235. if (ESR != ESR_Succeeded) {
  4236. if (ESR != ESR_Failed && !Scope.destroy())
  4237. return ESR_Failed;
  4238. return ESR;
  4239. }
  4240. // Create the __begin and __end iterators.
  4241. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  4242. if (ESR != ESR_Succeeded) {
  4243. if (ESR != ESR_Failed && !Scope.destroy())
  4244. return ESR_Failed;
  4245. return ESR;
  4246. }
  4247. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  4248. if (ESR != ESR_Succeeded) {
  4249. if (ESR != ESR_Failed && !Scope.destroy())
  4250. return ESR_Failed;
  4251. return ESR;
  4252. }
  4253. while (true) {
  4254. // Condition: __begin != __end.
  4255. {
  4256. bool Continue = true;
  4257. FullExpressionRAII CondExpr(Info);
  4258. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  4259. return ESR_Failed;
  4260. if (!Continue)
  4261. break;
  4262. }
  4263. // User's variable declaration, initialized by *__begin.
  4264. BlockScopeRAII InnerScope(Info);
  4265. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  4266. if (ESR != ESR_Succeeded) {
  4267. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4268. return ESR_Failed;
  4269. return ESR;
  4270. }
  4271. // Loop body.
  4272. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4273. if (ESR != ESR_Continue) {
  4274. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4275. return ESR_Failed;
  4276. return ESR;
  4277. }
  4278. // Increment: ++__begin
  4279. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  4280. return ESR_Failed;
  4281. if (!InnerScope.destroy())
  4282. return ESR_Failed;
  4283. }
  4284. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4285. }
  4286. case Stmt::SwitchStmtClass:
  4287. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  4288. case Stmt::ContinueStmtClass:
  4289. return ESR_Continue;
  4290. case Stmt::BreakStmtClass:
  4291. return ESR_Break;
  4292. case Stmt::LabelStmtClass:
  4293. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  4294. case Stmt::AttributedStmtClass:
  4295. // As a general principle, C++11 attributes can be ignored without
  4296. // any semantic impact.
  4297. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  4298. Case);
  4299. case Stmt::CaseStmtClass:
  4300. case Stmt::DefaultStmtClass:
  4301. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  4302. case Stmt::CXXTryStmtClass:
  4303. // Evaluate try blocks by evaluating all sub statements.
  4304. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  4305. }
  4306. }
  4307. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  4308. /// default constructor. If so, we'll fold it whether or not it's marked as
  4309. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4310. /// so we need special handling.
  4311. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4312. const CXXConstructorDecl *CD,
  4313. bool IsValueInitialization) {
  4314. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4315. return false;
  4316. // Value-initialization does not call a trivial default constructor, so such a
  4317. // call is a core constant expression whether or not the constructor is
  4318. // constexpr.
  4319. if (!CD->isConstexpr() && !IsValueInitialization) {
  4320. if (Info.getLangOpts().CPlusPlus11) {
  4321. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4322. // we should be much more explicit about why it's not constexpr.
  4323. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4324. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4325. Info.Note(CD->getLocation(), diag::note_declared_at);
  4326. } else {
  4327. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4328. }
  4329. }
  4330. return true;
  4331. }
  4332. /// CheckConstexprFunction - Check that a function can be called in a constant
  4333. /// expression.
  4334. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4335. const FunctionDecl *Declaration,
  4336. const FunctionDecl *Definition,
  4337. const Stmt *Body) {
  4338. // Potential constant expressions can contain calls to declared, but not yet
  4339. // defined, constexpr functions.
  4340. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4341. Declaration->isConstexpr())
  4342. return false;
  4343. // Bail out if the function declaration itself is invalid. We will
  4344. // have produced a relevant diagnostic while parsing it, so just
  4345. // note the problematic sub-expression.
  4346. if (Declaration->isInvalidDecl()) {
  4347. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4348. return false;
  4349. }
  4350. // DR1872: An instantiated virtual constexpr function can't be called in a
  4351. // constant expression (prior to C++20). We can still constant-fold such a
  4352. // call.
  4353. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  4354. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4355. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4356. if (Definition && Definition->isInvalidDecl()) {
  4357. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4358. return false;
  4359. }
  4360. // Can we evaluate this function call?
  4361. if (Definition && Definition->isConstexpr() && Body)
  4362. return true;
  4363. if (Info.getLangOpts().CPlusPlus11) {
  4364. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4365. // If this function is not constexpr because it is an inherited
  4366. // non-constexpr constructor, diagnose that directly.
  4367. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4368. if (CD && CD->isInheritingConstructor()) {
  4369. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4370. if (!Inherited->isConstexpr())
  4371. DiagDecl = CD = Inherited;
  4372. }
  4373. // FIXME: If DiagDecl is an implicitly-declared special member function
  4374. // or an inheriting constructor, we should be much more explicit about why
  4375. // it's not constexpr.
  4376. if (CD && CD->isInheritingConstructor())
  4377. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4378. << CD->getInheritedConstructor().getConstructor()->getParent();
  4379. else
  4380. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4381. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4382. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4383. } else {
  4384. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4385. }
  4386. return false;
  4387. }
  4388. namespace {
  4389. struct CheckDynamicTypeHandler {
  4390. AccessKinds AccessKind;
  4391. typedef bool result_type;
  4392. bool failed() { return false; }
  4393. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4394. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4395. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4396. };
  4397. } // end anonymous namespace
  4398. /// Check that we can access the notional vptr of an object / determine its
  4399. /// dynamic type.
  4400. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4401. AccessKinds AK, bool Polymorphic) {
  4402. if (This.Designator.Invalid)
  4403. return false;
  4404. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4405. if (!Obj)
  4406. return false;
  4407. if (!Obj.Value) {
  4408. // The object is not usable in constant expressions, so we can't inspect
  4409. // its value to see if it's in-lifetime or what the active union members
  4410. // are. We can still check for a one-past-the-end lvalue.
  4411. if (This.Designator.isOnePastTheEnd() ||
  4412. This.Designator.isMostDerivedAnUnsizedArray()) {
  4413. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4414. ? diag::note_constexpr_access_past_end
  4415. : diag::note_constexpr_access_unsized_array)
  4416. << AK;
  4417. return false;
  4418. } else if (Polymorphic) {
  4419. // Conservatively refuse to perform a polymorphic operation if we would
  4420. // not be able to read a notional 'vptr' value.
  4421. APValue Val;
  4422. This.moveInto(Val);
  4423. QualType StarThisType =
  4424. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4425. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4426. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4427. return false;
  4428. }
  4429. return true;
  4430. }
  4431. CheckDynamicTypeHandler Handler{AK};
  4432. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4433. }
  4434. /// Check that the pointee of the 'this' pointer in a member function call is
  4435. /// either within its lifetime or in its period of construction or destruction.
  4436. static bool
  4437. checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4438. const LValue &This,
  4439. const CXXMethodDecl *NamedMember) {
  4440. return checkDynamicType(
  4441. Info, E, This,
  4442. isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
  4443. }
  4444. struct DynamicType {
  4445. /// The dynamic class type of the object.
  4446. const CXXRecordDecl *Type;
  4447. /// The corresponding path length in the lvalue.
  4448. unsigned PathLength;
  4449. };
  4450. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4451. unsigned PathLength) {
  4452. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4453. Designator.Entries.size() && "invalid path length");
  4454. return (PathLength == Designator.MostDerivedPathLength)
  4455. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4456. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4457. }
  4458. /// Determine the dynamic type of an object.
  4459. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4460. LValue &This, AccessKinds AK) {
  4461. // If we don't have an lvalue denoting an object of class type, there is no
  4462. // meaningful dynamic type. (We consider objects of non-class type to have no
  4463. // dynamic type.)
  4464. if (!checkDynamicType(Info, E, This, AK, true))
  4465. return None;
  4466. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4467. // shouldn't happen other than in constant-folding situations, since literal
  4468. // types can't have virtual bases.
  4469. //
  4470. // Note that consumers of DynamicType assume that the type has no virtual
  4471. // bases, and will need modifications if this restriction is relaxed.
  4472. const CXXRecordDecl *Class =
  4473. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4474. if (!Class || Class->getNumVBases()) {
  4475. Info.FFDiag(E);
  4476. return None;
  4477. }
  4478. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4479. // binary search here instead. But the overwhelmingly common case is that
  4480. // we're not in the middle of a constructor, so it probably doesn't matter
  4481. // in practice.
  4482. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4483. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4484. PathLength <= Path.size(); ++PathLength) {
  4485. switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
  4486. Path.slice(0, PathLength))) {
  4487. case ConstructionPhase::Bases:
  4488. case ConstructionPhase::DestroyingBases:
  4489. // We're constructing or destroying a base class. This is not the dynamic
  4490. // type.
  4491. break;
  4492. case ConstructionPhase::None:
  4493. case ConstructionPhase::AfterBases:
  4494. case ConstructionPhase::Destroying:
  4495. // We've finished constructing the base classes and not yet started
  4496. // destroying them again, so this is the dynamic type.
  4497. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4498. PathLength};
  4499. }
  4500. }
  4501. // CWG issue 1517: we're constructing a base class of the object described by
  4502. // 'This', so that object has not yet begun its period of construction and
  4503. // any polymorphic operation on it results in undefined behavior.
  4504. Info.FFDiag(E);
  4505. return None;
  4506. }
  4507. /// Perform virtual dispatch.
  4508. static const CXXMethodDecl *HandleVirtualDispatch(
  4509. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4510. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4511. Optional<DynamicType> DynType = ComputeDynamicType(
  4512. Info, E, This,
  4513. isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
  4514. if (!DynType)
  4515. return nullptr;
  4516. // Find the final overrider. It must be declared in one of the classes on the
  4517. // path from the dynamic type to the static type.
  4518. // FIXME: If we ever allow literal types to have virtual base classes, that
  4519. // won't be true.
  4520. const CXXMethodDecl *Callee = Found;
  4521. unsigned PathLength = DynType->PathLength;
  4522. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4523. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4524. const CXXMethodDecl *Overrider =
  4525. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4526. if (Overrider) {
  4527. Callee = Overrider;
  4528. break;
  4529. }
  4530. }
  4531. // C++2a [class.abstract]p6:
  4532. // the effect of making a virtual call to a pure virtual function [...] is
  4533. // undefined
  4534. if (Callee->isPure()) {
  4535. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4536. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4537. return nullptr;
  4538. }
  4539. // If necessary, walk the rest of the path to determine the sequence of
  4540. // covariant adjustment steps to apply.
  4541. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4542. Found->getReturnType())) {
  4543. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4544. for (unsigned CovariantPathLength = PathLength + 1;
  4545. CovariantPathLength != This.Designator.Entries.size();
  4546. ++CovariantPathLength) {
  4547. const CXXRecordDecl *NextClass =
  4548. getBaseClassType(This.Designator, CovariantPathLength);
  4549. const CXXMethodDecl *Next =
  4550. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4551. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4552. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4553. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4554. }
  4555. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4556. CovariantAdjustmentPath.back()))
  4557. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4558. }
  4559. // Perform 'this' adjustment.
  4560. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4561. return nullptr;
  4562. return Callee;
  4563. }
  4564. /// Perform the adjustment from a value returned by a virtual function to
  4565. /// a value of the statically expected type, which may be a pointer or
  4566. /// reference to a base class of the returned type.
  4567. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4568. APValue &Result,
  4569. ArrayRef<QualType> Path) {
  4570. assert(Result.isLValue() &&
  4571. "unexpected kind of APValue for covariant return");
  4572. if (Result.isNullPointer())
  4573. return true;
  4574. LValue LVal;
  4575. LVal.setFrom(Info.Ctx, Result);
  4576. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4577. for (unsigned I = 1; I != Path.size(); ++I) {
  4578. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4579. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4580. if (OldClass != NewClass &&
  4581. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4582. return false;
  4583. OldClass = NewClass;
  4584. }
  4585. LVal.moveInto(Result);
  4586. return true;
  4587. }
  4588. /// Determine whether \p Base, which is known to be a direct base class of
  4589. /// \p Derived, is a public base class.
  4590. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4591. const CXXRecordDecl *Base) {
  4592. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4593. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4594. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4595. return BaseSpec.getAccessSpecifier() == AS_public;
  4596. }
  4597. llvm_unreachable("Base is not a direct base of Derived");
  4598. }
  4599. /// Apply the given dynamic cast operation on the provided lvalue.
  4600. ///
  4601. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4602. /// to find a suitable target subobject.
  4603. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4604. LValue &Ptr) {
  4605. // We can't do anything with a non-symbolic pointer value.
  4606. SubobjectDesignator &D = Ptr.Designator;
  4607. if (D.Invalid)
  4608. return false;
  4609. // C++ [expr.dynamic.cast]p6:
  4610. // If v is a null pointer value, the result is a null pointer value.
  4611. if (Ptr.isNullPointer() && !E->isGLValue())
  4612. return true;
  4613. // For all the other cases, we need the pointer to point to an object within
  4614. // its lifetime / period of construction / destruction, and we need to know
  4615. // its dynamic type.
  4616. Optional<DynamicType> DynType =
  4617. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4618. if (!DynType)
  4619. return false;
  4620. // C++ [expr.dynamic.cast]p7:
  4621. // If T is "pointer to cv void", then the result is a pointer to the most
  4622. // derived object
  4623. if (E->getType()->isVoidPointerType())
  4624. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4625. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4626. assert(C && "dynamic_cast target is not void pointer nor class");
  4627. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4628. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4629. // C++ [expr.dynamic.cast]p9:
  4630. if (!E->isGLValue()) {
  4631. // The value of a failed cast to pointer type is the null pointer value
  4632. // of the required result type.
  4633. Ptr.setNull(Info.Ctx, E->getType());
  4634. return true;
  4635. }
  4636. // A failed cast to reference type throws [...] std::bad_cast.
  4637. unsigned DiagKind;
  4638. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4639. DynType->Type->isDerivedFrom(C)))
  4640. DiagKind = 0;
  4641. else if (!Paths || Paths->begin() == Paths->end())
  4642. DiagKind = 1;
  4643. else if (Paths->isAmbiguous(CQT))
  4644. DiagKind = 2;
  4645. else {
  4646. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4647. DiagKind = 3;
  4648. }
  4649. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4650. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4651. << Info.Ctx.getRecordType(DynType->Type)
  4652. << E->getType().getUnqualifiedType();
  4653. return false;
  4654. };
  4655. // Runtime check, phase 1:
  4656. // Walk from the base subobject towards the derived object looking for the
  4657. // target type.
  4658. for (int PathLength = Ptr.Designator.Entries.size();
  4659. PathLength >= (int)DynType->PathLength; --PathLength) {
  4660. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4661. if (declaresSameEntity(Class, C))
  4662. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4663. // We can only walk across public inheritance edges.
  4664. if (PathLength > (int)DynType->PathLength &&
  4665. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4666. Class))
  4667. return RuntimeCheckFailed(nullptr);
  4668. }
  4669. // Runtime check, phase 2:
  4670. // Search the dynamic type for an unambiguous public base of type C.
  4671. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4672. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4673. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4674. Paths.front().Access == AS_public) {
  4675. // Downcast to the dynamic type...
  4676. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4677. return false;
  4678. // ... then upcast to the chosen base class subobject.
  4679. for (CXXBasePathElement &Elem : Paths.front())
  4680. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4681. return false;
  4682. return true;
  4683. }
  4684. // Otherwise, the runtime check fails.
  4685. return RuntimeCheckFailed(&Paths);
  4686. }
  4687. namespace {
  4688. struct StartLifetimeOfUnionMemberHandler {
  4689. const FieldDecl *Field;
  4690. static const AccessKinds AccessKind = AK_Assign;
  4691. typedef bool result_type;
  4692. bool failed() { return false; }
  4693. bool found(APValue &Subobj, QualType SubobjType) {
  4694. // We are supposed to perform no initialization but begin the lifetime of
  4695. // the object. We interpret that as meaning to do what default
  4696. // initialization of the object would do if all constructors involved were
  4697. // trivial:
  4698. // * All base, non-variant member, and array element subobjects' lifetimes
  4699. // begin
  4700. // * No variant members' lifetimes begin
  4701. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4702. assert(SubobjType->isUnionType());
  4703. if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
  4704. !Subobj.getUnionValue().hasValue())
  4705. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4706. return true;
  4707. }
  4708. bool found(APSInt &Value, QualType SubobjType) {
  4709. llvm_unreachable("wrong value kind for union object");
  4710. }
  4711. bool found(APFloat &Value, QualType SubobjType) {
  4712. llvm_unreachable("wrong value kind for union object");
  4713. }
  4714. };
  4715. } // end anonymous namespace
  4716. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4717. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4718. /// operator whose left-hand side might involve a union member access. If it
  4719. /// does, implicitly start the lifetime of any accessed union elements per
  4720. /// C++20 [class.union]5.
  4721. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4722. const LValue &LHS) {
  4723. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4724. return false;
  4725. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4726. // C++ [class.union]p5:
  4727. // define the set S(E) of subexpressions of E as follows:
  4728. unsigned PathLength = LHS.Designator.Entries.size();
  4729. for (const Expr *E = LHSExpr; E != nullptr;) {
  4730. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4731. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4732. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4733. // Note that we can't implicitly start the lifetime of a reference,
  4734. // so we don't need to proceed any further if we reach one.
  4735. if (!FD || FD->getType()->isReferenceType())
  4736. break;
  4737. // ... and also contains A.B if B names a union member
  4738. if (FD->getParent()->isUnion())
  4739. UnionPathLengths.push_back({PathLength - 1, FD});
  4740. E = ME->getBase();
  4741. --PathLength;
  4742. assert(declaresSameEntity(FD,
  4743. LHS.Designator.Entries[PathLength]
  4744. .getAsBaseOrMember().getPointer()));
  4745. // -- If E is of the form A[B] and is interpreted as a built-in array
  4746. // subscripting operator, S(E) is [S(the array operand, if any)].
  4747. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4748. // Step over an ArrayToPointerDecay implicit cast.
  4749. auto *Base = ASE->getBase()->IgnoreImplicit();
  4750. if (!Base->getType()->isArrayType())
  4751. break;
  4752. E = Base;
  4753. --PathLength;
  4754. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4755. // Step over a derived-to-base conversion.
  4756. E = ICE->getSubExpr();
  4757. if (ICE->getCastKind() == CK_NoOp)
  4758. continue;
  4759. if (ICE->getCastKind() != CK_DerivedToBase &&
  4760. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4761. break;
  4762. // Walk path backwards as we walk up from the base to the derived class.
  4763. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4764. --PathLength;
  4765. (void)Elt;
  4766. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4767. LHS.Designator.Entries[PathLength]
  4768. .getAsBaseOrMember().getPointer()));
  4769. }
  4770. // -- Otherwise, S(E) is empty.
  4771. } else {
  4772. break;
  4773. }
  4774. }
  4775. // Common case: no unions' lifetimes are started.
  4776. if (UnionPathLengths.empty())
  4777. return true;
  4778. // if modification of X [would access an inactive union member], an object
  4779. // of the type of X is implicitly created
  4780. CompleteObject Obj =
  4781. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4782. if (!Obj)
  4783. return false;
  4784. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4785. llvm::reverse(UnionPathLengths)) {
  4786. // Form a designator for the union object.
  4787. SubobjectDesignator D = LHS.Designator;
  4788. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4789. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4790. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4791. return false;
  4792. }
  4793. return true;
  4794. }
  4795. /// Determine if a class has any fields that might need to be copied by a
  4796. /// trivial copy or move operation.
  4797. static bool hasFields(const CXXRecordDecl *RD) {
  4798. if (!RD || RD->isEmpty())
  4799. return false;
  4800. for (auto *FD : RD->fields()) {
  4801. if (FD->isUnnamedBitfield())
  4802. continue;
  4803. return true;
  4804. }
  4805. for (auto &Base : RD->bases())
  4806. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4807. return true;
  4808. return false;
  4809. }
  4810. namespace {
  4811. typedef SmallVector<APValue, 8> ArgVector;
  4812. }
  4813. /// EvaluateArgs - Evaluate the arguments to a function call.
  4814. static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
  4815. EvalInfo &Info, const FunctionDecl *Callee) {
  4816. bool Success = true;
  4817. llvm::SmallBitVector ForbiddenNullArgs;
  4818. if (Callee->hasAttr<NonNullAttr>()) {
  4819. ForbiddenNullArgs.resize(Args.size());
  4820. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  4821. if (!Attr->args_size()) {
  4822. ForbiddenNullArgs.set();
  4823. break;
  4824. } else
  4825. for (auto Idx : Attr->args()) {
  4826. unsigned ASTIdx = Idx.getASTIndex();
  4827. if (ASTIdx >= Args.size())
  4828. continue;
  4829. ForbiddenNullArgs[ASTIdx] = 1;
  4830. }
  4831. }
  4832. }
  4833. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4834. I != E; ++I) {
  4835. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4836. // If we're checking for a potential constant expression, evaluate all
  4837. // initializers even if some of them fail.
  4838. if (!Info.noteFailure())
  4839. return false;
  4840. Success = false;
  4841. } else if (!ForbiddenNullArgs.empty() &&
  4842. ForbiddenNullArgs[I - Args.begin()] &&
  4843. ArgValues[I - Args.begin()].isNullPointer()) {
  4844. Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
  4845. if (!Info.noteFailure())
  4846. return false;
  4847. Success = false;
  4848. }
  4849. }
  4850. return Success;
  4851. }
  4852. /// Evaluate a function call.
  4853. static bool HandleFunctionCall(SourceLocation CallLoc,
  4854. const FunctionDecl *Callee, const LValue *This,
  4855. ArrayRef<const Expr*> Args, const Stmt *Body,
  4856. EvalInfo &Info, APValue &Result,
  4857. const LValue *ResultSlot) {
  4858. ArgVector ArgValues(Args.size());
  4859. if (!EvaluateArgs(Args, ArgValues, Info, Callee))
  4860. return false;
  4861. if (!Info.CheckCallLimit(CallLoc))
  4862. return false;
  4863. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4864. // For a trivial copy or move assignment, perform an APValue copy. This is
  4865. // essential for unions, where the operations performed by the assignment
  4866. // operator cannot be represented as statements.
  4867. //
  4868. // Skip this for non-union classes with no fields; in that case, the defaulted
  4869. // copy/move does not actually read the object.
  4870. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4871. if (MD && MD->isDefaulted() &&
  4872. (MD->getParent()->isUnion() ||
  4873. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4874. assert(This &&
  4875. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4876. LValue RHS;
  4877. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4878. APValue RHSValue;
  4879. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
  4880. RHSValue, MD->getParent()->isUnion()))
  4881. return false;
  4882. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4883. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4884. return false;
  4885. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4886. RHSValue))
  4887. return false;
  4888. This->moveInto(Result);
  4889. return true;
  4890. } else if (MD && isLambdaCallOperator(MD)) {
  4891. // We're in a lambda; determine the lambda capture field maps unless we're
  4892. // just constexpr checking a lambda's call operator. constexpr checking is
  4893. // done before the captures have been added to the closure object (unless
  4894. // we're inferring constexpr-ness), so we don't have access to them in this
  4895. // case. But since we don't need the captures to constexpr check, we can
  4896. // just ignore them.
  4897. if (!Info.checkingPotentialConstantExpression())
  4898. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4899. Frame.LambdaThisCaptureField);
  4900. }
  4901. StmtResult Ret = {Result, ResultSlot};
  4902. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4903. if (ESR == ESR_Succeeded) {
  4904. if (Callee->getReturnType()->isVoidType())
  4905. return true;
  4906. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4907. }
  4908. return ESR == ESR_Returned;
  4909. }
  4910. /// Evaluate a constructor call.
  4911. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4912. APValue *ArgValues,
  4913. const CXXConstructorDecl *Definition,
  4914. EvalInfo &Info, APValue &Result) {
  4915. SourceLocation CallLoc = E->getExprLoc();
  4916. if (!Info.CheckCallLimit(CallLoc))
  4917. return false;
  4918. const CXXRecordDecl *RD = Definition->getParent();
  4919. if (RD->getNumVBases()) {
  4920. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4921. return false;
  4922. }
  4923. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4924. Info,
  4925. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4926. RD->getNumBases());
  4927. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4928. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4929. // wasteful.
  4930. APValue RetVal;
  4931. StmtResult Ret = {RetVal, nullptr};
  4932. // If it's a delegating constructor, delegate.
  4933. if (Definition->isDelegatingConstructor()) {
  4934. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4935. {
  4936. FullExpressionRAII InitScope(Info);
  4937. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
  4938. !InitScope.destroy())
  4939. return false;
  4940. }
  4941. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4942. }
  4943. // For a trivial copy or move constructor, perform an APValue copy. This is
  4944. // essential for unions (or classes with anonymous union members), where the
  4945. // operations performed by the constructor cannot be represented by
  4946. // ctor-initializers.
  4947. //
  4948. // Skip this for empty non-union classes; we should not perform an
  4949. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4950. // actually read them.
  4951. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4952. (Definition->getParent()->isUnion() ||
  4953. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4954. LValue RHS;
  4955. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4956. return handleLValueToRValueConversion(
  4957. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4958. RHS, Result, Definition->getParent()->isUnion());
  4959. }
  4960. // Reserve space for the struct members.
  4961. if (!RD->isUnion() && !Result.hasValue())
  4962. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4963. std::distance(RD->field_begin(), RD->field_end()));
  4964. if (RD->isInvalidDecl()) return false;
  4965. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4966. // A scope for temporaries lifetime-extended by reference members.
  4967. BlockScopeRAII LifetimeExtendedScope(Info);
  4968. bool Success = true;
  4969. unsigned BasesSeen = 0;
  4970. #ifndef NDEBUG
  4971. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4972. #endif
  4973. CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
  4974. auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
  4975. // We might be initializing the same field again if this is an indirect
  4976. // field initialization.
  4977. if (FieldIt == RD->field_end() ||
  4978. FieldIt->getFieldIndex() > FD->getFieldIndex()) {
  4979. assert(Indirect && "fields out of order?");
  4980. return;
  4981. }
  4982. // Default-initialize any fields with no explicit initializer.
  4983. for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
  4984. assert(FieldIt != RD->field_end() && "missing field?");
  4985. if (!FieldIt->isUnnamedBitfield())
  4986. Result.getStructField(FieldIt->getFieldIndex()) =
  4987. getDefaultInitValue(FieldIt->getType());
  4988. }
  4989. ++FieldIt;
  4990. };
  4991. for (const auto *I : Definition->inits()) {
  4992. LValue Subobject = This;
  4993. LValue SubobjectParent = This;
  4994. APValue *Value = &Result;
  4995. // Determine the subobject to initialize.
  4996. FieldDecl *FD = nullptr;
  4997. if (I->isBaseInitializer()) {
  4998. QualType BaseType(I->getBaseClass(), 0);
  4999. #ifndef NDEBUG
  5000. // Non-virtual base classes are initialized in the order in the class
  5001. // definition. We have already checked for virtual base classes.
  5002. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  5003. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  5004. "base class initializers not in expected order");
  5005. ++BaseIt;
  5006. #endif
  5007. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  5008. BaseType->getAsCXXRecordDecl(), &Layout))
  5009. return false;
  5010. Value = &Result.getStructBase(BasesSeen++);
  5011. } else if ((FD = I->getMember())) {
  5012. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  5013. return false;
  5014. if (RD->isUnion()) {
  5015. Result = APValue(FD);
  5016. Value = &Result.getUnionValue();
  5017. } else {
  5018. SkipToField(FD, false);
  5019. Value = &Result.getStructField(FD->getFieldIndex());
  5020. }
  5021. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  5022. // Walk the indirect field decl's chain to find the object to initialize,
  5023. // and make sure we've initialized every step along it.
  5024. auto IndirectFieldChain = IFD->chain();
  5025. for (auto *C : IndirectFieldChain) {
  5026. FD = cast<FieldDecl>(C);
  5027. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  5028. // Switch the union field if it differs. This happens if we had
  5029. // preceding zero-initialization, and we're now initializing a union
  5030. // subobject other than the first.
  5031. // FIXME: In this case, the values of the other subobjects are
  5032. // specified, since zero-initialization sets all padding bits to zero.
  5033. if (!Value->hasValue() ||
  5034. (Value->isUnion() && Value->getUnionField() != FD)) {
  5035. if (CD->isUnion())
  5036. *Value = APValue(FD);
  5037. else
  5038. // FIXME: This immediately starts the lifetime of all members of an
  5039. // anonymous struct. It would be preferable to strictly start member
  5040. // lifetime in initialization order.
  5041. *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
  5042. }
  5043. // Store Subobject as its parent before updating it for the last element
  5044. // in the chain.
  5045. if (C == IndirectFieldChain.back())
  5046. SubobjectParent = Subobject;
  5047. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  5048. return false;
  5049. if (CD->isUnion())
  5050. Value = &Value->getUnionValue();
  5051. else {
  5052. if (C == IndirectFieldChain.front() && !RD->isUnion())
  5053. SkipToField(FD, true);
  5054. Value = &Value->getStructField(FD->getFieldIndex());
  5055. }
  5056. }
  5057. } else {
  5058. llvm_unreachable("unknown base initializer kind");
  5059. }
  5060. // Need to override This for implicit field initializers as in this case
  5061. // This refers to innermost anonymous struct/union containing initializer,
  5062. // not to currently constructed class.
  5063. const Expr *Init = I->getInit();
  5064. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  5065. isa<CXXDefaultInitExpr>(Init));
  5066. FullExpressionRAII InitScope(Info);
  5067. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  5068. (FD && FD->isBitField() &&
  5069. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  5070. // If we're checking for a potential constant expression, evaluate all
  5071. // initializers even if some of them fail.
  5072. if (!Info.noteFailure())
  5073. return false;
  5074. Success = false;
  5075. }
  5076. // This is the point at which the dynamic type of the object becomes this
  5077. // class type.
  5078. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  5079. EvalObj.finishedConstructingBases();
  5080. }
  5081. // Default-initialize any remaining fields.
  5082. if (!RD->isUnion()) {
  5083. for (; FieldIt != RD->field_end(); ++FieldIt) {
  5084. if (!FieldIt->isUnnamedBitfield())
  5085. Result.getStructField(FieldIt->getFieldIndex()) =
  5086. getDefaultInitValue(FieldIt->getType());
  5087. }
  5088. }
  5089. return Success &&
  5090. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
  5091. LifetimeExtendedScope.destroy();
  5092. }
  5093. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  5094. ArrayRef<const Expr*> Args,
  5095. const CXXConstructorDecl *Definition,
  5096. EvalInfo &Info, APValue &Result) {
  5097. ArgVector ArgValues(Args.size());
  5098. if (!EvaluateArgs(Args, ArgValues, Info, Definition))
  5099. return false;
  5100. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  5101. Info, Result);
  5102. }
  5103. static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
  5104. const LValue &This, APValue &Value,
  5105. QualType T) {
  5106. // Objects can only be destroyed while they're within their lifetimes.
  5107. // FIXME: We have no representation for whether an object of type nullptr_t
  5108. // is in its lifetime; it usually doesn't matter. Perhaps we should model it
  5109. // as indeterminate instead?
  5110. if (Value.isAbsent() && !T->isNullPtrType()) {
  5111. APValue Printable;
  5112. This.moveInto(Printable);
  5113. Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
  5114. << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
  5115. return false;
  5116. }
  5117. // Invent an expression for location purposes.
  5118. // FIXME: We shouldn't need to do this.
  5119. OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
  5120. // For arrays, destroy elements right-to-left.
  5121. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
  5122. uint64_t Size = CAT->getSize().getZExtValue();
  5123. QualType ElemT = CAT->getElementType();
  5124. LValue ElemLV = This;
  5125. ElemLV.addArray(Info, &LocE, CAT);
  5126. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
  5127. return false;
  5128. // Ensure that we have actual array elements available to destroy; the
  5129. // destructors might mutate the value, so we can't run them on the array
  5130. // filler.
  5131. if (Size && Size > Value.getArrayInitializedElts())
  5132. expandArray(Value, Value.getArraySize() - 1);
  5133. for (; Size != 0; --Size) {
  5134. APValue &Elem = Value.getArrayInitializedElt(Size - 1);
  5135. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
  5136. !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
  5137. return false;
  5138. }
  5139. // End the lifetime of this array now.
  5140. Value = APValue();
  5141. return true;
  5142. }
  5143. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  5144. if (!RD) {
  5145. if (T.isDestructedType()) {
  5146. Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
  5147. return false;
  5148. }
  5149. Value = APValue();
  5150. return true;
  5151. }
  5152. if (RD->getNumVBases()) {
  5153. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5154. return false;
  5155. }
  5156. const CXXDestructorDecl *DD = RD->getDestructor();
  5157. if (!DD && !RD->hasTrivialDestructor()) {
  5158. Info.FFDiag(CallLoc);
  5159. return false;
  5160. }
  5161. if (!DD || DD->isTrivial() ||
  5162. (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
  5163. // A trivial destructor just ends the lifetime of the object. Check for
  5164. // this case before checking for a body, because we might not bother
  5165. // building a body for a trivial destructor. Note that it doesn't matter
  5166. // whether the destructor is constexpr in this case; all trivial
  5167. // destructors are constexpr.
  5168. //
  5169. // If an anonymous union would be destroyed, some enclosing destructor must
  5170. // have been explicitly defined, and the anonymous union destruction should
  5171. // have no effect.
  5172. Value = APValue();
  5173. return true;
  5174. }
  5175. if (!Info.CheckCallLimit(CallLoc))
  5176. return false;
  5177. const FunctionDecl *Definition = nullptr;
  5178. const Stmt *Body = DD->getBody(Definition);
  5179. if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
  5180. return false;
  5181. CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
  5182. // We're now in the period of destruction of this object.
  5183. unsigned BasesLeft = RD->getNumBases();
  5184. EvalInfo::EvaluatingDestructorRAII EvalObj(
  5185. Info,
  5186. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
  5187. if (!EvalObj.DidInsert) {
  5188. // C++2a [class.dtor]p19:
  5189. // the behavior is undefined if the destructor is invoked for an object
  5190. // whose lifetime has ended
  5191. // (Note that formally the lifetime ends when the period of destruction
  5192. // begins, even though certain uses of the object remain valid until the
  5193. // period of destruction ends.)
  5194. Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
  5195. return false;
  5196. }
  5197. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5198. // wasteful.
  5199. APValue RetVal;
  5200. StmtResult Ret = {RetVal, nullptr};
  5201. if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
  5202. return false;
  5203. // A union destructor does not implicitly destroy its members.
  5204. if (RD->isUnion())
  5205. return true;
  5206. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5207. // We don't have a good way to iterate fields in reverse, so collect all the
  5208. // fields first and then walk them backwards.
  5209. SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
  5210. for (const FieldDecl *FD : llvm::reverse(Fields)) {
  5211. if (FD->isUnnamedBitfield())
  5212. continue;
  5213. LValue Subobject = This;
  5214. if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
  5215. return false;
  5216. APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
  5217. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5218. FD->getType()))
  5219. return false;
  5220. }
  5221. if (BasesLeft != 0)
  5222. EvalObj.startedDestroyingBases();
  5223. // Destroy base classes in reverse order.
  5224. for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
  5225. --BasesLeft;
  5226. QualType BaseType = Base.getType();
  5227. LValue Subobject = This;
  5228. if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
  5229. BaseType->getAsCXXRecordDecl(), &Layout))
  5230. return false;
  5231. APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
  5232. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5233. BaseType))
  5234. return false;
  5235. }
  5236. assert(BasesLeft == 0 && "NumBases was wrong?");
  5237. // The period of destruction ends now. The object is gone.
  5238. Value = APValue();
  5239. return true;
  5240. }
  5241. namespace {
  5242. struct DestroyObjectHandler {
  5243. EvalInfo &Info;
  5244. const Expr *E;
  5245. const LValue &This;
  5246. const AccessKinds AccessKind;
  5247. typedef bool result_type;
  5248. bool failed() { return false; }
  5249. bool found(APValue &Subobj, QualType SubobjType) {
  5250. return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
  5251. SubobjType);
  5252. }
  5253. bool found(APSInt &Value, QualType SubobjType) {
  5254. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5255. return false;
  5256. }
  5257. bool found(APFloat &Value, QualType SubobjType) {
  5258. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5259. return false;
  5260. }
  5261. };
  5262. }
  5263. /// Perform a destructor or pseudo-destructor call on the given object, which
  5264. /// might in general not be a complete object.
  5265. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  5266. const LValue &This, QualType ThisType) {
  5267. CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
  5268. DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
  5269. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  5270. }
  5271. /// Destroy and end the lifetime of the given complete object.
  5272. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  5273. APValue::LValueBase LVBase, APValue &Value,
  5274. QualType T) {
  5275. // If we've had an unmodeled side-effect, we can't rely on mutable state
  5276. // (such as the object we're about to destroy) being correct.
  5277. if (Info.EvalStatus.HasSideEffects)
  5278. return false;
  5279. LValue LV;
  5280. LV.set({LVBase});
  5281. return HandleDestructionImpl(Info, Loc, LV, Value, T);
  5282. }
  5283. /// Perform a call to 'perator new' or to `__builtin_operator_new'.
  5284. static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
  5285. LValue &Result) {
  5286. if (Info.checkingPotentialConstantExpression() ||
  5287. Info.SpeculativeEvaluationDepth)
  5288. return false;
  5289. // This is permitted only within a call to std::allocator<T>::allocate.
  5290. auto Caller = Info.getStdAllocatorCaller("allocate");
  5291. if (!Caller) {
  5292. Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
  5293. ? diag::note_constexpr_new_untyped
  5294. : diag::note_constexpr_new);
  5295. return false;
  5296. }
  5297. QualType ElemType = Caller.ElemType;
  5298. if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
  5299. Info.FFDiag(E->getExprLoc(),
  5300. diag::note_constexpr_new_not_complete_object_type)
  5301. << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
  5302. return false;
  5303. }
  5304. APSInt ByteSize;
  5305. if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
  5306. return false;
  5307. bool IsNothrow = false;
  5308. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
  5309. EvaluateIgnoredValue(Info, E->getArg(I));
  5310. IsNothrow |= E->getType()->isNothrowT();
  5311. }
  5312. CharUnits ElemSize;
  5313. if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
  5314. return false;
  5315. APInt Size, Remainder;
  5316. APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
  5317. APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
  5318. if (Remainder != 0) {
  5319. // This likely indicates a bug in the implementation of 'std::allocator'.
  5320. Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
  5321. << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
  5322. return false;
  5323. }
  5324. if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  5325. if (IsNothrow) {
  5326. Result.setNull(Info.Ctx, E->getType());
  5327. return true;
  5328. }
  5329. Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
  5330. return false;
  5331. }
  5332. QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
  5333. ArrayType::Normal, 0);
  5334. APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
  5335. *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
  5336. Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
  5337. return true;
  5338. }
  5339. static bool hasVirtualDestructor(QualType T) {
  5340. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  5341. if (CXXDestructorDecl *DD = RD->getDestructor())
  5342. return DD->isVirtual();
  5343. return false;
  5344. }
  5345. /// Check that the given object is a suitable pointer to a heap allocation that
  5346. /// still exists and is of the right kind for the purpose of a deletion.
  5347. ///
  5348. /// On success, returns the heap allocation to deallocate. On failure, produces
  5349. /// a diagnostic and returns None.
  5350. static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
  5351. const LValue &Pointer,
  5352. DynAlloc::Kind DeallocKind) {
  5353. auto PointerAsString = [&] {
  5354. return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
  5355. };
  5356. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  5357. if (!DA) {
  5358. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  5359. << PointerAsString();
  5360. if (Pointer.Base)
  5361. NoteLValueLocation(Info, Pointer.Base);
  5362. return None;
  5363. }
  5364. Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
  5365. if (!Alloc) {
  5366. Info.FFDiag(E, diag::note_constexpr_double_delete);
  5367. return None;
  5368. }
  5369. QualType AllocType = Pointer.Base.getDynamicAllocType();
  5370. if (DeallocKind != (*Alloc)->getKind()) {
  5371. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  5372. << DeallocKind << (*Alloc)->getKind() << AllocType;
  5373. NoteLValueLocation(Info, Pointer.Base);
  5374. return None;
  5375. }
  5376. bool Subobject = false;
  5377. if (DeallocKind == DynAlloc::New) {
  5378. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  5379. Pointer.Designator.isOnePastTheEnd();
  5380. } else {
  5381. Subobject = Pointer.Designator.Entries.size() != 1 ||
  5382. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  5383. }
  5384. if (Subobject) {
  5385. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  5386. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  5387. return None;
  5388. }
  5389. return Alloc;
  5390. }
  5391. // Perform a call to 'operator delete' or '__builtin_operator_delete'.
  5392. bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
  5393. if (Info.checkingPotentialConstantExpression() ||
  5394. Info.SpeculativeEvaluationDepth)
  5395. return false;
  5396. // This is permitted only within a call to std::allocator<T>::deallocate.
  5397. if (!Info.getStdAllocatorCaller("deallocate")) {
  5398. Info.FFDiag(E->getExprLoc());
  5399. return true;
  5400. }
  5401. LValue Pointer;
  5402. if (!EvaluatePointer(E->getArg(0), Pointer, Info))
  5403. return false;
  5404. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
  5405. EvaluateIgnoredValue(Info, E->getArg(I));
  5406. if (Pointer.Designator.Invalid)
  5407. return false;
  5408. // Deleting a null pointer has no effect.
  5409. if (Pointer.isNullPointer())
  5410. return true;
  5411. if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
  5412. return false;
  5413. Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
  5414. return true;
  5415. }
  5416. //===----------------------------------------------------------------------===//
  5417. // Generic Evaluation
  5418. //===----------------------------------------------------------------------===//
  5419. namespace {
  5420. class BitCastBuffer {
  5421. // FIXME: We're going to need bit-level granularity when we support
  5422. // bit-fields.
  5423. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  5424. // we don't support a host or target where that is the case. Still, we should
  5425. // use a more generic type in case we ever do.
  5426. SmallVector<Optional<unsigned char>, 32> Bytes;
  5427. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  5428. "Need at least 8 bit unsigned char");
  5429. bool TargetIsLittleEndian;
  5430. public:
  5431. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  5432. : Bytes(Width.getQuantity()),
  5433. TargetIsLittleEndian(TargetIsLittleEndian) {}
  5434. LLVM_NODISCARD
  5435. bool readObject(CharUnits Offset, CharUnits Width,
  5436. SmallVectorImpl<unsigned char> &Output) const {
  5437. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  5438. // If a byte of an integer is uninitialized, then the whole integer is
  5439. // uninitalized.
  5440. if (!Bytes[I.getQuantity()])
  5441. return false;
  5442. Output.push_back(*Bytes[I.getQuantity()]);
  5443. }
  5444. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5445. std::reverse(Output.begin(), Output.end());
  5446. return true;
  5447. }
  5448. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  5449. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5450. std::reverse(Input.begin(), Input.end());
  5451. size_t Index = 0;
  5452. for (unsigned char Byte : Input) {
  5453. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  5454. Bytes[Offset.getQuantity() + Index] = Byte;
  5455. ++Index;
  5456. }
  5457. }
  5458. size_t size() { return Bytes.size(); }
  5459. };
  5460. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  5461. /// target would represent the value at runtime.
  5462. class APValueToBufferConverter {
  5463. EvalInfo &Info;
  5464. BitCastBuffer Buffer;
  5465. const CastExpr *BCE;
  5466. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  5467. const CastExpr *BCE)
  5468. : Info(Info),
  5469. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  5470. BCE(BCE) {}
  5471. bool visit(const APValue &Val, QualType Ty) {
  5472. return visit(Val, Ty, CharUnits::fromQuantity(0));
  5473. }
  5474. // Write out Val with type Ty into Buffer starting at Offset.
  5475. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  5476. assert((size_t)Offset.getQuantity() <= Buffer.size());
  5477. // As a special case, nullptr_t has an indeterminate value.
  5478. if (Ty->isNullPtrType())
  5479. return true;
  5480. // Dig through Src to find the byte at SrcOffset.
  5481. switch (Val.getKind()) {
  5482. case APValue::Indeterminate:
  5483. case APValue::None:
  5484. return true;
  5485. case APValue::Int:
  5486. return visitInt(Val.getInt(), Ty, Offset);
  5487. case APValue::Float:
  5488. return visitFloat(Val.getFloat(), Ty, Offset);
  5489. case APValue::Array:
  5490. return visitArray(Val, Ty, Offset);
  5491. case APValue::Struct:
  5492. return visitRecord(Val, Ty, Offset);
  5493. case APValue::ComplexInt:
  5494. case APValue::ComplexFloat:
  5495. case APValue::Vector:
  5496. case APValue::FixedPoint:
  5497. // FIXME: We should support these.
  5498. case APValue::Union:
  5499. case APValue::MemberPointer:
  5500. case APValue::AddrLabelDiff: {
  5501. Info.FFDiag(BCE->getBeginLoc(),
  5502. diag::note_constexpr_bit_cast_unsupported_type)
  5503. << Ty;
  5504. return false;
  5505. }
  5506. case APValue::LValue:
  5507. llvm_unreachable("LValue subobject in bit_cast?");
  5508. }
  5509. llvm_unreachable("Unhandled APValue::ValueKind");
  5510. }
  5511. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  5512. const RecordDecl *RD = Ty->getAsRecordDecl();
  5513. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5514. // Visit the base classes.
  5515. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5516. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5517. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5518. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5519. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  5520. Layout.getBaseClassOffset(BaseDecl) + Offset))
  5521. return false;
  5522. }
  5523. }
  5524. // Visit the fields.
  5525. unsigned FieldIdx = 0;
  5526. for (FieldDecl *FD : RD->fields()) {
  5527. if (FD->isBitField()) {
  5528. Info.FFDiag(BCE->getBeginLoc(),
  5529. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5530. return false;
  5531. }
  5532. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5533. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  5534. "only bit-fields can have sub-char alignment");
  5535. CharUnits FieldOffset =
  5536. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  5537. QualType FieldTy = FD->getType();
  5538. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  5539. return false;
  5540. ++FieldIdx;
  5541. }
  5542. return true;
  5543. }
  5544. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  5545. const auto *CAT =
  5546. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  5547. if (!CAT)
  5548. return false;
  5549. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  5550. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  5551. unsigned ArraySize = Val.getArraySize();
  5552. // First, initialize the initialized elements.
  5553. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  5554. const APValue &SubObj = Val.getArrayInitializedElt(I);
  5555. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  5556. return false;
  5557. }
  5558. // Next, initialize the rest of the array using the filler.
  5559. if (Val.hasArrayFiller()) {
  5560. const APValue &Filler = Val.getArrayFiller();
  5561. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  5562. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  5563. return false;
  5564. }
  5565. }
  5566. return true;
  5567. }
  5568. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  5569. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  5570. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  5571. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  5572. Buffer.writeObject(Offset, Bytes);
  5573. return true;
  5574. }
  5575. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  5576. APSInt AsInt(Val.bitcastToAPInt());
  5577. return visitInt(AsInt, Ty, Offset);
  5578. }
  5579. public:
  5580. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  5581. const CastExpr *BCE) {
  5582. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  5583. APValueToBufferConverter Converter(Info, DstSize, BCE);
  5584. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  5585. return None;
  5586. return Converter.Buffer;
  5587. }
  5588. };
  5589. /// Write an BitCastBuffer into an APValue.
  5590. class BufferToAPValueConverter {
  5591. EvalInfo &Info;
  5592. const BitCastBuffer &Buffer;
  5593. const CastExpr *BCE;
  5594. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  5595. const CastExpr *BCE)
  5596. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  5597. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  5598. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  5599. // Ideally this will be unreachable.
  5600. llvm::NoneType unsupportedType(QualType Ty) {
  5601. Info.FFDiag(BCE->getBeginLoc(),
  5602. diag::note_constexpr_bit_cast_unsupported_type)
  5603. << Ty;
  5604. return None;
  5605. }
  5606. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  5607. const EnumType *EnumSugar = nullptr) {
  5608. if (T->isNullPtrType()) {
  5609. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  5610. return APValue((Expr *)nullptr,
  5611. /*Offset=*/CharUnits::fromQuantity(NullValue),
  5612. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  5613. }
  5614. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  5615. SmallVector<uint8_t, 8> Bytes;
  5616. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  5617. // If this is std::byte or unsigned char, then its okay to store an
  5618. // indeterminate value.
  5619. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  5620. bool IsUChar =
  5621. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  5622. T->isSpecificBuiltinType(BuiltinType::Char_U));
  5623. if (!IsStdByte && !IsUChar) {
  5624. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  5625. Info.FFDiag(BCE->getExprLoc(),
  5626. diag::note_constexpr_bit_cast_indet_dest)
  5627. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  5628. return None;
  5629. }
  5630. return APValue::IndeterminateValue();
  5631. }
  5632. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  5633. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  5634. if (T->isIntegralOrEnumerationType()) {
  5635. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  5636. return APValue(Val);
  5637. }
  5638. if (T->isRealFloatingType()) {
  5639. const llvm::fltSemantics &Semantics =
  5640. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  5641. return APValue(APFloat(Semantics, Val));
  5642. }
  5643. return unsupportedType(QualType(T, 0));
  5644. }
  5645. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  5646. const RecordDecl *RD = RTy->getAsRecordDecl();
  5647. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5648. unsigned NumBases = 0;
  5649. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5650. NumBases = CXXRD->getNumBases();
  5651. APValue ResultVal(APValue::UninitStruct(), NumBases,
  5652. std::distance(RD->field_begin(), RD->field_end()));
  5653. // Visit the base classes.
  5654. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5655. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5656. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5657. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5658. if (BaseDecl->isEmpty() ||
  5659. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  5660. continue;
  5661. Optional<APValue> SubObj = visitType(
  5662. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  5663. if (!SubObj)
  5664. return None;
  5665. ResultVal.getStructBase(I) = *SubObj;
  5666. }
  5667. }
  5668. // Visit the fields.
  5669. unsigned FieldIdx = 0;
  5670. for (FieldDecl *FD : RD->fields()) {
  5671. // FIXME: We don't currently support bit-fields. A lot of the logic for
  5672. // this is in CodeGen, so we need to factor it around.
  5673. if (FD->isBitField()) {
  5674. Info.FFDiag(BCE->getBeginLoc(),
  5675. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5676. return None;
  5677. }
  5678. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5679. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  5680. CharUnits FieldOffset =
  5681. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  5682. Offset;
  5683. QualType FieldTy = FD->getType();
  5684. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  5685. if (!SubObj)
  5686. return None;
  5687. ResultVal.getStructField(FieldIdx) = *SubObj;
  5688. ++FieldIdx;
  5689. }
  5690. return ResultVal;
  5691. }
  5692. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  5693. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  5694. assert(!RepresentationType.isNull() &&
  5695. "enum forward decl should be caught by Sema");
  5696. const auto *AsBuiltin =
  5697. RepresentationType.getCanonicalType()->castAs<BuiltinType>();
  5698. // Recurse into the underlying type. Treat std::byte transparently as
  5699. // unsigned char.
  5700. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  5701. }
  5702. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  5703. size_t Size = Ty->getSize().getLimitedValue();
  5704. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  5705. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  5706. for (size_t I = 0; I != Size; ++I) {
  5707. Optional<APValue> ElementValue =
  5708. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  5709. if (!ElementValue)
  5710. return None;
  5711. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  5712. }
  5713. return ArrayValue;
  5714. }
  5715. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  5716. return unsupportedType(QualType(Ty, 0));
  5717. }
  5718. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  5719. QualType Can = Ty.getCanonicalType();
  5720. switch (Can->getTypeClass()) {
  5721. #define TYPE(Class, Base) \
  5722. case Type::Class: \
  5723. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  5724. #define ABSTRACT_TYPE(Class, Base)
  5725. #define NON_CANONICAL_TYPE(Class, Base) \
  5726. case Type::Class: \
  5727. llvm_unreachable("non-canonical type should be impossible!");
  5728. #define DEPENDENT_TYPE(Class, Base) \
  5729. case Type::Class: \
  5730. llvm_unreachable( \
  5731. "dependent types aren't supported in the constant evaluator!");
  5732. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  5733. case Type::Class: \
  5734. llvm_unreachable("either dependent or not canonical!");
  5735. #include "clang/AST/TypeNodes.inc"
  5736. }
  5737. llvm_unreachable("Unhandled Type::TypeClass");
  5738. }
  5739. public:
  5740. // Pull out a full value of type DstType.
  5741. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  5742. const CastExpr *BCE) {
  5743. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  5744. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  5745. }
  5746. };
  5747. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  5748. QualType Ty, EvalInfo *Info,
  5749. const ASTContext &Ctx,
  5750. bool CheckingDest) {
  5751. Ty = Ty.getCanonicalType();
  5752. auto diag = [&](int Reason) {
  5753. if (Info)
  5754. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  5755. << CheckingDest << (Reason == 4) << Reason;
  5756. return false;
  5757. };
  5758. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  5759. if (Info)
  5760. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  5761. << NoteTy << Construct << Ty;
  5762. return false;
  5763. };
  5764. if (Ty->isUnionType())
  5765. return diag(0);
  5766. if (Ty->isPointerType())
  5767. return diag(1);
  5768. if (Ty->isMemberPointerType())
  5769. return diag(2);
  5770. if (Ty.isVolatileQualified())
  5771. return diag(3);
  5772. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  5773. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  5774. for (CXXBaseSpecifier &BS : CXXRD->bases())
  5775. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  5776. CheckingDest))
  5777. return note(1, BS.getType(), BS.getBeginLoc());
  5778. }
  5779. for (FieldDecl *FD : Record->fields()) {
  5780. if (FD->getType()->isReferenceType())
  5781. return diag(4);
  5782. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5783. CheckingDest))
  5784. return note(0, FD->getType(), FD->getBeginLoc());
  5785. }
  5786. }
  5787. if (Ty->isArrayType() &&
  5788. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5789. Info, Ctx, CheckingDest))
  5790. return false;
  5791. return true;
  5792. }
  5793. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5794. const ASTContext &Ctx,
  5795. const CastExpr *BCE) {
  5796. bool DestOK = checkBitCastConstexprEligibilityType(
  5797. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5798. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5799. BCE->getBeginLoc(),
  5800. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5801. return SourceOK;
  5802. }
  5803. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5804. APValue &SourceValue,
  5805. const CastExpr *BCE) {
  5806. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5807. "no host or target supports non 8-bit chars");
  5808. assert(SourceValue.isLValue() &&
  5809. "LValueToRValueBitcast requires an lvalue operand!");
  5810. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5811. return false;
  5812. LValue SourceLValue;
  5813. APValue SourceRValue;
  5814. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5815. if (!handleLValueToRValueConversion(
  5816. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  5817. SourceRValue, /*WantObjectRepresentation=*/true))
  5818. return false;
  5819. // Read out SourceValue into a char buffer.
  5820. Optional<BitCastBuffer> Buffer =
  5821. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5822. if (!Buffer)
  5823. return false;
  5824. // Write out the buffer into a new APValue.
  5825. Optional<APValue> MaybeDestValue =
  5826. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5827. if (!MaybeDestValue)
  5828. return false;
  5829. DestValue = std::move(*MaybeDestValue);
  5830. return true;
  5831. }
  5832. template <class Derived>
  5833. class ExprEvaluatorBase
  5834. : public ConstStmtVisitor<Derived, bool> {
  5835. private:
  5836. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5837. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5838. return getDerived().Success(V, E);
  5839. }
  5840. bool DerivedZeroInitialization(const Expr *E) {
  5841. return getDerived().ZeroInitialization(E);
  5842. }
  5843. // Check whether a conditional operator with a non-constant condition is a
  5844. // potential constant expression. If neither arm is a potential constant
  5845. // expression, then the conditional operator is not either.
  5846. template<typename ConditionalOperator>
  5847. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5848. assert(Info.checkingPotentialConstantExpression());
  5849. // Speculatively evaluate both arms.
  5850. SmallVector<PartialDiagnosticAt, 8> Diag;
  5851. {
  5852. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5853. StmtVisitorTy::Visit(E->getFalseExpr());
  5854. if (Diag.empty())
  5855. return;
  5856. }
  5857. {
  5858. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5859. Diag.clear();
  5860. StmtVisitorTy::Visit(E->getTrueExpr());
  5861. if (Diag.empty())
  5862. return;
  5863. }
  5864. Error(E, diag::note_constexpr_conditional_never_const);
  5865. }
  5866. template<typename ConditionalOperator>
  5867. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5868. bool BoolResult;
  5869. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5870. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5871. CheckPotentialConstantConditional(E);
  5872. return false;
  5873. }
  5874. if (Info.noteFailure()) {
  5875. StmtVisitorTy::Visit(E->getTrueExpr());
  5876. StmtVisitorTy::Visit(E->getFalseExpr());
  5877. }
  5878. return false;
  5879. }
  5880. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5881. return StmtVisitorTy::Visit(EvalExpr);
  5882. }
  5883. protected:
  5884. EvalInfo &Info;
  5885. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5886. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5887. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5888. return Info.CCEDiag(E, D);
  5889. }
  5890. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5891. public:
  5892. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5893. EvalInfo &getEvalInfo() { return Info; }
  5894. /// Report an evaluation error. This should only be called when an error is
  5895. /// first discovered. When propagating an error, just return false.
  5896. bool Error(const Expr *E, diag::kind D) {
  5897. Info.FFDiag(E, D);
  5898. return false;
  5899. }
  5900. bool Error(const Expr *E) {
  5901. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5902. }
  5903. bool VisitStmt(const Stmt *) {
  5904. llvm_unreachable("Expression evaluator should not be called on stmts");
  5905. }
  5906. bool VisitExpr(const Expr *E) {
  5907. return Error(E);
  5908. }
  5909. bool VisitConstantExpr(const ConstantExpr *E)
  5910. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5911. bool VisitParenExpr(const ParenExpr *E)
  5912. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5913. bool VisitUnaryExtension(const UnaryOperator *E)
  5914. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5915. bool VisitUnaryPlus(const UnaryOperator *E)
  5916. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5917. bool VisitChooseExpr(const ChooseExpr *E)
  5918. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5919. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5920. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5921. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5922. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5923. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5924. TempVersionRAII RAII(*Info.CurrentCall);
  5925. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5926. return StmtVisitorTy::Visit(E->getExpr());
  5927. }
  5928. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5929. TempVersionRAII RAII(*Info.CurrentCall);
  5930. // The initializer may not have been parsed yet, or might be erroneous.
  5931. if (!E->getExpr())
  5932. return Error(E);
  5933. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5934. return StmtVisitorTy::Visit(E->getExpr());
  5935. }
  5936. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  5937. FullExpressionRAII Scope(Info);
  5938. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  5939. }
  5940. // Temporaries are registered when created, so we don't care about
  5941. // CXXBindTemporaryExpr.
  5942. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  5943. return StmtVisitorTy::Visit(E->getSubExpr());
  5944. }
  5945. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5946. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5947. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5948. }
  5949. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5950. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5951. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5952. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5953. }
  5954. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5955. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5956. }
  5957. bool VisitBinaryOperator(const BinaryOperator *E) {
  5958. switch (E->getOpcode()) {
  5959. default:
  5960. return Error(E);
  5961. case BO_Comma:
  5962. VisitIgnoredValue(E->getLHS());
  5963. return StmtVisitorTy::Visit(E->getRHS());
  5964. case BO_PtrMemD:
  5965. case BO_PtrMemI: {
  5966. LValue Obj;
  5967. if (!HandleMemberPointerAccess(Info, E, Obj))
  5968. return false;
  5969. APValue Result;
  5970. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5971. return false;
  5972. return DerivedSuccess(Result, E);
  5973. }
  5974. }
  5975. }
  5976. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5977. // Evaluate and cache the common expression. We treat it as a temporary,
  5978. // even though it's not quite the same thing.
  5979. LValue CommonLV;
  5980. if (!Evaluate(Info.CurrentCall->createTemporary(
  5981. E->getOpaqueValue(),
  5982. getStorageType(Info.Ctx, E->getOpaqueValue()), false,
  5983. CommonLV),
  5984. Info, E->getCommon()))
  5985. return false;
  5986. return HandleConditionalOperator(E);
  5987. }
  5988. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5989. bool IsBcpCall = false;
  5990. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5991. // the result is a constant expression if it can be folded without
  5992. // side-effects. This is an important GNU extension. See GCC PR38377
  5993. // for discussion.
  5994. if (const CallExpr *CallCE =
  5995. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  5996. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  5997. IsBcpCall = true;
  5998. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  5999. // constant expression; we can't check whether it's potentially foldable.
  6000. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  6001. // it would return 'false' in this mode.
  6002. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  6003. return false;
  6004. FoldConstant Fold(Info, IsBcpCall);
  6005. if (!HandleConditionalOperator(E)) {
  6006. Fold.keepDiagnostics();
  6007. return false;
  6008. }
  6009. return true;
  6010. }
  6011. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  6012. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  6013. return DerivedSuccess(*Value, E);
  6014. const Expr *Source = E->getSourceExpr();
  6015. if (!Source)
  6016. return Error(E);
  6017. if (Source == E) { // sanity checking.
  6018. assert(0 && "OpaqueValueExpr recursively refers to itself");
  6019. return Error(E);
  6020. }
  6021. return StmtVisitorTy::Visit(Source);
  6022. }
  6023. bool VisitCallExpr(const CallExpr *E) {
  6024. APValue Result;
  6025. if (!handleCallExpr(E, Result, nullptr))
  6026. return false;
  6027. return DerivedSuccess(Result, E);
  6028. }
  6029. bool handleCallExpr(const CallExpr *E, APValue &Result,
  6030. const LValue *ResultSlot) {
  6031. const Expr *Callee = E->getCallee()->IgnoreParens();
  6032. QualType CalleeType = Callee->getType();
  6033. const FunctionDecl *FD = nullptr;
  6034. LValue *This = nullptr, ThisVal;
  6035. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  6036. bool HasQualifier = false;
  6037. // Extract function decl and 'this' pointer from the callee.
  6038. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  6039. const CXXMethodDecl *Member = nullptr;
  6040. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  6041. // Explicit bound member calls, such as x.f() or p->g();
  6042. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  6043. return false;
  6044. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  6045. if (!Member)
  6046. return Error(Callee);
  6047. This = &ThisVal;
  6048. HasQualifier = ME->hasQualifier();
  6049. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  6050. // Indirect bound member calls ('.*' or '->*').
  6051. const ValueDecl *D =
  6052. HandleMemberPointerAccess(Info, BE, ThisVal, false);
  6053. if (!D)
  6054. return false;
  6055. Member = dyn_cast<CXXMethodDecl>(D);
  6056. if (!Member)
  6057. return Error(Callee);
  6058. This = &ThisVal;
  6059. } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
  6060. if (!Info.getLangOpts().CPlusPlus2a)
  6061. Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
  6062. // FIXME: If pseudo-destructor calls ever start ending the lifetime of
  6063. // their callee, we should start calling HandleDestruction here.
  6064. // For now, we just evaluate the object argument and discard it.
  6065. return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
  6066. } else
  6067. return Error(Callee);
  6068. FD = Member;
  6069. } else if (CalleeType->isFunctionPointerType()) {
  6070. LValue Call;
  6071. if (!EvaluatePointer(Callee, Call, Info))
  6072. return false;
  6073. if (!Call.getLValueOffset().isZero())
  6074. return Error(Callee);
  6075. FD = dyn_cast_or_null<FunctionDecl>(
  6076. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  6077. if (!FD)
  6078. return Error(Callee);
  6079. // Don't call function pointers which have been cast to some other type.
  6080. // Per DR (no number yet), the caller and callee can differ in noexcept.
  6081. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  6082. CalleeType->getPointeeType(), FD->getType())) {
  6083. return Error(E);
  6084. }
  6085. // Overloaded operator calls to member functions are represented as normal
  6086. // calls with '*this' as the first argument.
  6087. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6088. if (MD && !MD->isStatic()) {
  6089. // FIXME: When selecting an implicit conversion for an overloaded
  6090. // operator delete, we sometimes try to evaluate calls to conversion
  6091. // operators without a 'this' parameter!
  6092. if (Args.empty())
  6093. return Error(E);
  6094. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  6095. return false;
  6096. This = &ThisVal;
  6097. Args = Args.slice(1);
  6098. } else if (MD && MD->isLambdaStaticInvoker()) {
  6099. // Map the static invoker for the lambda back to the call operator.
  6100. // Conveniently, we don't have to slice out the 'this' argument (as is
  6101. // being done for the non-static case), since a static member function
  6102. // doesn't have an implicit argument passed in.
  6103. const CXXRecordDecl *ClosureClass = MD->getParent();
  6104. assert(
  6105. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  6106. "Number of captures must be zero for conversion to function-ptr");
  6107. const CXXMethodDecl *LambdaCallOp =
  6108. ClosureClass->getLambdaCallOperator();
  6109. // Set 'FD', the function that will be called below, to the call
  6110. // operator. If the closure object represents a generic lambda, find
  6111. // the corresponding specialization of the call operator.
  6112. if (ClosureClass->isGenericLambda()) {
  6113. assert(MD->isFunctionTemplateSpecialization() &&
  6114. "A generic lambda's static-invoker function must be a "
  6115. "template specialization");
  6116. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  6117. FunctionTemplateDecl *CallOpTemplate =
  6118. LambdaCallOp->getDescribedFunctionTemplate();
  6119. void *InsertPos = nullptr;
  6120. FunctionDecl *CorrespondingCallOpSpecialization =
  6121. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  6122. assert(CorrespondingCallOpSpecialization &&
  6123. "We must always have a function call operator specialization "
  6124. "that corresponds to our static invoker specialization");
  6125. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  6126. } else
  6127. FD = LambdaCallOp;
  6128. } else if (FD->isReplaceableGlobalAllocationFunction()) {
  6129. if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
  6130. FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
  6131. LValue Ptr;
  6132. if (!HandleOperatorNewCall(Info, E, Ptr))
  6133. return false;
  6134. Ptr.moveInto(Result);
  6135. return true;
  6136. } else {
  6137. return HandleOperatorDeleteCall(Info, E);
  6138. }
  6139. }
  6140. } else
  6141. return Error(E);
  6142. SmallVector<QualType, 4> CovariantAdjustmentPath;
  6143. if (This) {
  6144. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  6145. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  6146. // Perform virtual dispatch, if necessary.
  6147. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  6148. CovariantAdjustmentPath);
  6149. if (!FD)
  6150. return false;
  6151. } else {
  6152. // Check that the 'this' pointer points to an object of the right type.
  6153. // FIXME: If this is an assignment operator call, we may need to change
  6154. // the active union member before we check this.
  6155. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
  6156. return false;
  6157. }
  6158. }
  6159. // Destructor calls are different enough that they have their own codepath.
  6160. if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
  6161. assert(This && "no 'this' pointer for destructor call");
  6162. return HandleDestruction(Info, E, *This,
  6163. Info.Ctx.getRecordType(DD->getParent()));
  6164. }
  6165. const FunctionDecl *Definition = nullptr;
  6166. Stmt *Body = FD->getBody(Definition);
  6167. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  6168. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  6169. Result, ResultSlot))
  6170. return false;
  6171. if (!CovariantAdjustmentPath.empty() &&
  6172. !HandleCovariantReturnAdjustment(Info, E, Result,
  6173. CovariantAdjustmentPath))
  6174. return false;
  6175. return true;
  6176. }
  6177. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6178. return StmtVisitorTy::Visit(E->getInitializer());
  6179. }
  6180. bool VisitInitListExpr(const InitListExpr *E) {
  6181. if (E->getNumInits() == 0)
  6182. return DerivedZeroInitialization(E);
  6183. if (E->getNumInits() == 1)
  6184. return StmtVisitorTy::Visit(E->getInit(0));
  6185. return Error(E);
  6186. }
  6187. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  6188. return DerivedZeroInitialization(E);
  6189. }
  6190. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  6191. return DerivedZeroInitialization(E);
  6192. }
  6193. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  6194. return DerivedZeroInitialization(E);
  6195. }
  6196. /// A member expression where the object is a prvalue is itself a prvalue.
  6197. bool VisitMemberExpr(const MemberExpr *E) {
  6198. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  6199. "missing temporary materialization conversion");
  6200. assert(!E->isArrow() && "missing call to bound member function?");
  6201. APValue Val;
  6202. if (!Evaluate(Val, Info, E->getBase()))
  6203. return false;
  6204. QualType BaseTy = E->getBase()->getType();
  6205. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  6206. if (!FD) return Error(E);
  6207. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  6208. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6209. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6210. // Note: there is no lvalue base here. But this case should only ever
  6211. // happen in C or in C++98, where we cannot be evaluating a constexpr
  6212. // constructor, which is the only case the base matters.
  6213. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  6214. SubobjectDesignator Designator(BaseTy);
  6215. Designator.addDeclUnchecked(FD);
  6216. APValue Result;
  6217. return extractSubobject(Info, E, Obj, Designator, Result) &&
  6218. DerivedSuccess(Result, E);
  6219. }
  6220. bool VisitCastExpr(const CastExpr *E) {
  6221. switch (E->getCastKind()) {
  6222. default:
  6223. break;
  6224. case CK_AtomicToNonAtomic: {
  6225. APValue AtomicVal;
  6226. // This does not need to be done in place even for class/array types:
  6227. // atomic-to-non-atomic conversion implies copying the object
  6228. // representation.
  6229. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  6230. return false;
  6231. return DerivedSuccess(AtomicVal, E);
  6232. }
  6233. case CK_NoOp:
  6234. case CK_UserDefinedConversion:
  6235. return StmtVisitorTy::Visit(E->getSubExpr());
  6236. case CK_LValueToRValue: {
  6237. LValue LVal;
  6238. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  6239. return false;
  6240. APValue RVal;
  6241. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6242. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6243. LVal, RVal))
  6244. return false;
  6245. return DerivedSuccess(RVal, E);
  6246. }
  6247. case CK_LValueToRValueBitCast: {
  6248. APValue DestValue, SourceValue;
  6249. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  6250. return false;
  6251. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  6252. return false;
  6253. return DerivedSuccess(DestValue, E);
  6254. }
  6255. }
  6256. return Error(E);
  6257. }
  6258. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  6259. return VisitUnaryPostIncDec(UO);
  6260. }
  6261. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  6262. return VisitUnaryPostIncDec(UO);
  6263. }
  6264. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  6265. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6266. return Error(UO);
  6267. LValue LVal;
  6268. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  6269. return false;
  6270. APValue RVal;
  6271. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  6272. UO->isIncrementOp(), &RVal))
  6273. return false;
  6274. return DerivedSuccess(RVal, UO);
  6275. }
  6276. bool VisitStmtExpr(const StmtExpr *E) {
  6277. // We will have checked the full-expressions inside the statement expression
  6278. // when they were completed, and don't need to check them again now.
  6279. if (Info.checkingForUndefinedBehavior())
  6280. return Error(E);
  6281. const CompoundStmt *CS = E->getSubStmt();
  6282. if (CS->body_empty())
  6283. return true;
  6284. BlockScopeRAII Scope(Info);
  6285. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  6286. BE = CS->body_end();
  6287. /**/; ++BI) {
  6288. if (BI + 1 == BE) {
  6289. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  6290. if (!FinalExpr) {
  6291. Info.FFDiag((*BI)->getBeginLoc(),
  6292. diag::note_constexpr_stmt_expr_unsupported);
  6293. return false;
  6294. }
  6295. return this->Visit(FinalExpr) && Scope.destroy();
  6296. }
  6297. APValue ReturnValue;
  6298. StmtResult Result = { ReturnValue, nullptr };
  6299. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  6300. if (ESR != ESR_Succeeded) {
  6301. // FIXME: If the statement-expression terminated due to 'return',
  6302. // 'break', or 'continue', it would be nice to propagate that to
  6303. // the outer statement evaluation rather than bailing out.
  6304. if (ESR != ESR_Failed)
  6305. Info.FFDiag((*BI)->getBeginLoc(),
  6306. diag::note_constexpr_stmt_expr_unsupported);
  6307. return false;
  6308. }
  6309. }
  6310. llvm_unreachable("Return from function from the loop above.");
  6311. }
  6312. /// Visit a value which is evaluated, but whose value is ignored.
  6313. void VisitIgnoredValue(const Expr *E) {
  6314. EvaluateIgnoredValue(Info, E);
  6315. }
  6316. /// Potentially visit a MemberExpr's base expression.
  6317. void VisitIgnoredBaseExpression(const Expr *E) {
  6318. // While MSVC doesn't evaluate the base expression, it does diagnose the
  6319. // presence of side-effecting behavior.
  6320. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  6321. return;
  6322. VisitIgnoredValue(E);
  6323. }
  6324. };
  6325. } // namespace
  6326. //===----------------------------------------------------------------------===//
  6327. // Common base class for lvalue and temporary evaluation.
  6328. //===----------------------------------------------------------------------===//
  6329. namespace {
  6330. template<class Derived>
  6331. class LValueExprEvaluatorBase
  6332. : public ExprEvaluatorBase<Derived> {
  6333. protected:
  6334. LValue &Result;
  6335. bool InvalidBaseOK;
  6336. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  6337. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  6338. bool Success(APValue::LValueBase B) {
  6339. Result.set(B);
  6340. return true;
  6341. }
  6342. bool evaluatePointer(const Expr *E, LValue &Result) {
  6343. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  6344. }
  6345. public:
  6346. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  6347. : ExprEvaluatorBaseTy(Info), Result(Result),
  6348. InvalidBaseOK(InvalidBaseOK) {}
  6349. bool Success(const APValue &V, const Expr *E) {
  6350. Result.setFrom(this->Info.Ctx, V);
  6351. return true;
  6352. }
  6353. bool VisitMemberExpr(const MemberExpr *E) {
  6354. // Handle non-static data members.
  6355. QualType BaseTy;
  6356. bool EvalOK;
  6357. if (E->isArrow()) {
  6358. EvalOK = evaluatePointer(E->getBase(), Result);
  6359. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  6360. } else if (E->getBase()->isRValue()) {
  6361. assert(E->getBase()->getType()->isRecordType());
  6362. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  6363. BaseTy = E->getBase()->getType();
  6364. } else {
  6365. EvalOK = this->Visit(E->getBase());
  6366. BaseTy = E->getBase()->getType();
  6367. }
  6368. if (!EvalOK) {
  6369. if (!InvalidBaseOK)
  6370. return false;
  6371. Result.setInvalid(E);
  6372. return true;
  6373. }
  6374. const ValueDecl *MD = E->getMemberDecl();
  6375. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  6376. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6377. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6378. (void)BaseTy;
  6379. if (!HandleLValueMember(this->Info, E, Result, FD))
  6380. return false;
  6381. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  6382. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  6383. return false;
  6384. } else
  6385. return this->Error(E);
  6386. if (MD->getType()->isReferenceType()) {
  6387. APValue RefValue;
  6388. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  6389. RefValue))
  6390. return false;
  6391. return Success(RefValue, E);
  6392. }
  6393. return true;
  6394. }
  6395. bool VisitBinaryOperator(const BinaryOperator *E) {
  6396. switch (E->getOpcode()) {
  6397. default:
  6398. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6399. case BO_PtrMemD:
  6400. case BO_PtrMemI:
  6401. return HandleMemberPointerAccess(this->Info, E, Result);
  6402. }
  6403. }
  6404. bool VisitCastExpr(const CastExpr *E) {
  6405. switch (E->getCastKind()) {
  6406. default:
  6407. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6408. case CK_DerivedToBase:
  6409. case CK_UncheckedDerivedToBase:
  6410. if (!this->Visit(E->getSubExpr()))
  6411. return false;
  6412. // Now figure out the necessary offset to add to the base LV to get from
  6413. // the derived class to the base class.
  6414. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  6415. Result);
  6416. }
  6417. }
  6418. };
  6419. }
  6420. //===----------------------------------------------------------------------===//
  6421. // LValue Evaluation
  6422. //
  6423. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  6424. // function designators (in C), decl references to void objects (in C), and
  6425. // temporaries (if building with -Wno-address-of-temporary).
  6426. //
  6427. // LValue evaluation produces values comprising a base expression of one of the
  6428. // following types:
  6429. // - Declarations
  6430. // * VarDecl
  6431. // * FunctionDecl
  6432. // - Literals
  6433. // * CompoundLiteralExpr in C (and in global scope in C++)
  6434. // * StringLiteral
  6435. // * PredefinedExpr
  6436. // * ObjCStringLiteralExpr
  6437. // * ObjCEncodeExpr
  6438. // * AddrLabelExpr
  6439. // * BlockExpr
  6440. // * CallExpr for a MakeStringConstant builtin
  6441. // - typeid(T) expressions, as TypeInfoLValues
  6442. // - Locals and temporaries
  6443. // * MaterializeTemporaryExpr
  6444. // * Any Expr, with a CallIndex indicating the function in which the temporary
  6445. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  6446. // from the AST (FIXME).
  6447. // * A MaterializeTemporaryExpr that has static storage duration, with no
  6448. // CallIndex, for a lifetime-extended temporary.
  6449. // plus an offset in bytes.
  6450. //===----------------------------------------------------------------------===//
  6451. namespace {
  6452. class LValueExprEvaluator
  6453. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  6454. public:
  6455. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  6456. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  6457. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  6458. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  6459. bool VisitDeclRefExpr(const DeclRefExpr *E);
  6460. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  6461. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  6462. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  6463. bool VisitMemberExpr(const MemberExpr *E);
  6464. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  6465. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  6466. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  6467. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  6468. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  6469. bool VisitUnaryDeref(const UnaryOperator *E);
  6470. bool VisitUnaryReal(const UnaryOperator *E);
  6471. bool VisitUnaryImag(const UnaryOperator *E);
  6472. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  6473. return VisitUnaryPreIncDec(UO);
  6474. }
  6475. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  6476. return VisitUnaryPreIncDec(UO);
  6477. }
  6478. bool VisitBinAssign(const BinaryOperator *BO);
  6479. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  6480. bool VisitCastExpr(const CastExpr *E) {
  6481. switch (E->getCastKind()) {
  6482. default:
  6483. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6484. case CK_LValueBitCast:
  6485. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6486. if (!Visit(E->getSubExpr()))
  6487. return false;
  6488. Result.Designator.setInvalid();
  6489. return true;
  6490. case CK_BaseToDerived:
  6491. if (!Visit(E->getSubExpr()))
  6492. return false;
  6493. return HandleBaseToDerivedCast(Info, E, Result);
  6494. case CK_Dynamic:
  6495. if (!Visit(E->getSubExpr()))
  6496. return false;
  6497. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6498. }
  6499. }
  6500. };
  6501. } // end anonymous namespace
  6502. /// Evaluate an expression as an lvalue. This can be legitimately called on
  6503. /// expressions which are not glvalues, in three cases:
  6504. /// * function designators in C, and
  6505. /// * "extern void" objects
  6506. /// * @selector() expressions in Objective-C
  6507. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  6508. bool InvalidBaseOK) {
  6509. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  6510. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  6511. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6512. }
  6513. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  6514. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  6515. return Success(FD);
  6516. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  6517. return VisitVarDecl(E, VD);
  6518. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  6519. return Visit(BD->getBinding());
  6520. return Error(E);
  6521. }
  6522. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  6523. // If we are within a lambda's call operator, check whether the 'VD' referred
  6524. // to within 'E' actually represents a lambda-capture that maps to a
  6525. // data-member/field within the closure object, and if so, evaluate to the
  6526. // field or what the field refers to.
  6527. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  6528. isa<DeclRefExpr>(E) &&
  6529. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  6530. // We don't always have a complete capture-map when checking or inferring if
  6531. // the function call operator meets the requirements of a constexpr function
  6532. // - but we don't need to evaluate the captures to determine constexprness
  6533. // (dcl.constexpr C++17).
  6534. if (Info.checkingPotentialConstantExpression())
  6535. return false;
  6536. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  6537. // Start with 'Result' referring to the complete closure object...
  6538. Result = *Info.CurrentCall->This;
  6539. // ... then update it to refer to the field of the closure object
  6540. // that represents the capture.
  6541. if (!HandleLValueMember(Info, E, Result, FD))
  6542. return false;
  6543. // And if the field is of reference type, update 'Result' to refer to what
  6544. // the field refers to.
  6545. if (FD->getType()->isReferenceType()) {
  6546. APValue RVal;
  6547. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  6548. RVal))
  6549. return false;
  6550. Result.setFrom(Info.Ctx, RVal);
  6551. }
  6552. return true;
  6553. }
  6554. }
  6555. CallStackFrame *Frame = nullptr;
  6556. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  6557. // Only if a local variable was declared in the function currently being
  6558. // evaluated, do we expect to be able to find its value in the current
  6559. // frame. (Otherwise it was likely declared in an enclosing context and
  6560. // could either have a valid evaluatable value (for e.g. a constexpr
  6561. // variable) or be ill-formed (and trigger an appropriate evaluation
  6562. // diagnostic)).
  6563. if (Info.CurrentCall->Callee &&
  6564. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  6565. Frame = Info.CurrentCall;
  6566. }
  6567. }
  6568. if (!VD->getType()->isReferenceType()) {
  6569. if (Frame) {
  6570. Result.set({VD, Frame->Index,
  6571. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  6572. return true;
  6573. }
  6574. return Success(VD);
  6575. }
  6576. APValue *V;
  6577. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  6578. return false;
  6579. if (!V->hasValue()) {
  6580. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  6581. // adjust the diagnostic to say that.
  6582. if (!Info.checkingPotentialConstantExpression())
  6583. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  6584. return false;
  6585. }
  6586. return Success(*V, E);
  6587. }
  6588. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  6589. const MaterializeTemporaryExpr *E) {
  6590. // Walk through the expression to find the materialized temporary itself.
  6591. SmallVector<const Expr *, 2> CommaLHSs;
  6592. SmallVector<SubobjectAdjustment, 2> Adjustments;
  6593. const Expr *Inner = E->GetTemporaryExpr()->
  6594. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  6595. // If we passed any comma operators, evaluate their LHSs.
  6596. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  6597. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  6598. return false;
  6599. // A materialized temporary with static storage duration can appear within the
  6600. // result of a constant expression evaluation, so we need to preserve its
  6601. // value for use outside this evaluation.
  6602. APValue *Value;
  6603. if (E->getStorageDuration() == SD_Static) {
  6604. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  6605. *Value = APValue();
  6606. Result.set(E);
  6607. } else {
  6608. Value = &Info.CurrentCall->createTemporary(
  6609. E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
  6610. }
  6611. QualType Type = Inner->getType();
  6612. // Materialize the temporary itself.
  6613. if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
  6614. *Value = APValue();
  6615. return false;
  6616. }
  6617. // Adjust our lvalue to refer to the desired subobject.
  6618. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  6619. --I;
  6620. switch (Adjustments[I].Kind) {
  6621. case SubobjectAdjustment::DerivedToBaseAdjustment:
  6622. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  6623. Type, Result))
  6624. return false;
  6625. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  6626. break;
  6627. case SubobjectAdjustment::FieldAdjustment:
  6628. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  6629. return false;
  6630. Type = Adjustments[I].Field->getType();
  6631. break;
  6632. case SubobjectAdjustment::MemberPointerAdjustment:
  6633. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  6634. Adjustments[I].Ptr.RHS))
  6635. return false;
  6636. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  6637. break;
  6638. }
  6639. }
  6640. return true;
  6641. }
  6642. bool
  6643. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6644. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  6645. "lvalue compound literal in c++?");
  6646. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  6647. // only see this when folding in C, so there's no standard to follow here.
  6648. return Success(E);
  6649. }
  6650. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  6651. TypeInfoLValue TypeInfo;
  6652. if (!E->isPotentiallyEvaluated()) {
  6653. if (E->isTypeOperand())
  6654. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  6655. else
  6656. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  6657. } else {
  6658. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  6659. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  6660. << E->getExprOperand()->getType()
  6661. << E->getExprOperand()->getSourceRange();
  6662. }
  6663. if (!Visit(E->getExprOperand()))
  6664. return false;
  6665. Optional<DynamicType> DynType =
  6666. ComputeDynamicType(Info, E, Result, AK_TypeId);
  6667. if (!DynType)
  6668. return false;
  6669. TypeInfo =
  6670. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  6671. }
  6672. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  6673. }
  6674. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  6675. return Success(E);
  6676. }
  6677. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  6678. // Handle static data members.
  6679. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  6680. VisitIgnoredBaseExpression(E->getBase());
  6681. return VisitVarDecl(E, VD);
  6682. }
  6683. // Handle static member functions.
  6684. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  6685. if (MD->isStatic()) {
  6686. VisitIgnoredBaseExpression(E->getBase());
  6687. return Success(MD);
  6688. }
  6689. }
  6690. // Handle non-static data members.
  6691. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  6692. }
  6693. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  6694. // FIXME: Deal with vectors as array subscript bases.
  6695. if (E->getBase()->getType()->isVectorType())
  6696. return Error(E);
  6697. bool Success = true;
  6698. if (!evaluatePointer(E->getBase(), Result)) {
  6699. if (!Info.noteFailure())
  6700. return false;
  6701. Success = false;
  6702. }
  6703. APSInt Index;
  6704. if (!EvaluateInteger(E->getIdx(), Index, Info))
  6705. return false;
  6706. return Success &&
  6707. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  6708. }
  6709. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  6710. return evaluatePointer(E->getSubExpr(), Result);
  6711. }
  6712. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6713. if (!Visit(E->getSubExpr()))
  6714. return false;
  6715. // __real is a no-op on scalar lvalues.
  6716. if (E->getSubExpr()->getType()->isAnyComplexType())
  6717. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  6718. return true;
  6719. }
  6720. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6721. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  6722. "lvalue __imag__ on scalar?");
  6723. if (!Visit(E->getSubExpr()))
  6724. return false;
  6725. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  6726. return true;
  6727. }
  6728. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  6729. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6730. return Error(UO);
  6731. if (!this->Visit(UO->getSubExpr()))
  6732. return false;
  6733. return handleIncDec(
  6734. this->Info, UO, Result, UO->getSubExpr()->getType(),
  6735. UO->isIncrementOp(), nullptr);
  6736. }
  6737. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  6738. const CompoundAssignOperator *CAO) {
  6739. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6740. return Error(CAO);
  6741. APValue RHS;
  6742. // The overall lvalue result is the result of evaluating the LHS.
  6743. if (!this->Visit(CAO->getLHS())) {
  6744. if (Info.noteFailure())
  6745. Evaluate(RHS, this->Info, CAO->getRHS());
  6746. return false;
  6747. }
  6748. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  6749. return false;
  6750. return handleCompoundAssignment(
  6751. this->Info, CAO,
  6752. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  6753. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  6754. }
  6755. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  6756. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6757. return Error(E);
  6758. APValue NewVal;
  6759. if (!this->Visit(E->getLHS())) {
  6760. if (Info.noteFailure())
  6761. Evaluate(NewVal, this->Info, E->getRHS());
  6762. return false;
  6763. }
  6764. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  6765. return false;
  6766. if (Info.getLangOpts().CPlusPlus2a &&
  6767. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  6768. return false;
  6769. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  6770. NewVal);
  6771. }
  6772. //===----------------------------------------------------------------------===//
  6773. // Pointer Evaluation
  6774. //===----------------------------------------------------------------------===//
  6775. /// Attempts to compute the number of bytes available at the pointer
  6776. /// returned by a function with the alloc_size attribute. Returns true if we
  6777. /// were successful. Places an unsigned number into `Result`.
  6778. ///
  6779. /// This expects the given CallExpr to be a call to a function with an
  6780. /// alloc_size attribute.
  6781. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6782. const CallExpr *Call,
  6783. llvm::APInt &Result) {
  6784. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  6785. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  6786. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  6787. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  6788. if (Call->getNumArgs() <= SizeArgNo)
  6789. return false;
  6790. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  6791. Expr::EvalResult ExprResult;
  6792. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  6793. return false;
  6794. Into = ExprResult.Val.getInt();
  6795. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  6796. return false;
  6797. Into = Into.zextOrSelf(BitsInSizeT);
  6798. return true;
  6799. };
  6800. APSInt SizeOfElem;
  6801. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  6802. return false;
  6803. if (!AllocSize->getNumElemsParam().isValid()) {
  6804. Result = std::move(SizeOfElem);
  6805. return true;
  6806. }
  6807. APSInt NumberOfElems;
  6808. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  6809. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  6810. return false;
  6811. bool Overflow;
  6812. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  6813. if (Overflow)
  6814. return false;
  6815. Result = std::move(BytesAvailable);
  6816. return true;
  6817. }
  6818. /// Convenience function. LVal's base must be a call to an alloc_size
  6819. /// function.
  6820. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6821. const LValue &LVal,
  6822. llvm::APInt &Result) {
  6823. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6824. "Can't get the size of a non alloc_size function");
  6825. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6826. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6827. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6828. }
  6829. /// Attempts to evaluate the given LValueBase as the result of a call to
  6830. /// a function with the alloc_size attribute. If it was possible to do so, this
  6831. /// function will return true, make Result's Base point to said function call,
  6832. /// and mark Result's Base as invalid.
  6833. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6834. LValue &Result) {
  6835. if (Base.isNull())
  6836. return false;
  6837. // Because we do no form of static analysis, we only support const variables.
  6838. //
  6839. // Additionally, we can't support parameters, nor can we support static
  6840. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6841. // we have no clue what they'll be assigned to).
  6842. const auto *VD =
  6843. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6844. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6845. return false;
  6846. const Expr *Init = VD->getAnyInitializer();
  6847. if (!Init)
  6848. return false;
  6849. const Expr *E = Init->IgnoreParens();
  6850. if (!tryUnwrapAllocSizeCall(E))
  6851. return false;
  6852. // Store E instead of E unwrapped so that the type of the LValue's base is
  6853. // what the user wanted.
  6854. Result.setInvalid(E);
  6855. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6856. Result.addUnsizedArray(Info, E, Pointee);
  6857. return true;
  6858. }
  6859. namespace {
  6860. class PointerExprEvaluator
  6861. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6862. LValue &Result;
  6863. bool InvalidBaseOK;
  6864. bool Success(const Expr *E) {
  6865. Result.set(E);
  6866. return true;
  6867. }
  6868. bool evaluateLValue(const Expr *E, LValue &Result) {
  6869. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6870. }
  6871. bool evaluatePointer(const Expr *E, LValue &Result) {
  6872. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6873. }
  6874. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6875. public:
  6876. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6877. : ExprEvaluatorBaseTy(info), Result(Result),
  6878. InvalidBaseOK(InvalidBaseOK) {}
  6879. bool Success(const APValue &V, const Expr *E) {
  6880. Result.setFrom(Info.Ctx, V);
  6881. return true;
  6882. }
  6883. bool ZeroInitialization(const Expr *E) {
  6884. Result.setNull(Info.Ctx, E->getType());
  6885. return true;
  6886. }
  6887. bool VisitBinaryOperator(const BinaryOperator *E);
  6888. bool VisitCastExpr(const CastExpr* E);
  6889. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6890. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6891. { return Success(E); }
  6892. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6893. if (E->isExpressibleAsConstantInitializer())
  6894. return Success(E);
  6895. if (Info.noteFailure())
  6896. EvaluateIgnoredValue(Info, E->getSubExpr());
  6897. return Error(E);
  6898. }
  6899. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6900. { return Success(E); }
  6901. bool VisitCallExpr(const CallExpr *E);
  6902. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6903. bool VisitBlockExpr(const BlockExpr *E) {
  6904. if (!E->getBlockDecl()->hasCaptures())
  6905. return Success(E);
  6906. return Error(E);
  6907. }
  6908. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6909. // Can't look at 'this' when checking a potential constant expression.
  6910. if (Info.checkingPotentialConstantExpression())
  6911. return false;
  6912. if (!Info.CurrentCall->This) {
  6913. if (Info.getLangOpts().CPlusPlus11)
  6914. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6915. else
  6916. Info.FFDiag(E);
  6917. return false;
  6918. }
  6919. Result = *Info.CurrentCall->This;
  6920. // If we are inside a lambda's call operator, the 'this' expression refers
  6921. // to the enclosing '*this' object (either by value or reference) which is
  6922. // either copied into the closure object's field that represents the '*this'
  6923. // or refers to '*this'.
  6924. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6925. // Update 'Result' to refer to the data member/field of the closure object
  6926. // that represents the '*this' capture.
  6927. if (!HandleLValueMember(Info, E, Result,
  6928. Info.CurrentCall->LambdaThisCaptureField))
  6929. return false;
  6930. // If we captured '*this' by reference, replace the field with its referent.
  6931. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6932. ->isPointerType()) {
  6933. APValue RVal;
  6934. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6935. RVal))
  6936. return false;
  6937. Result.setFrom(Info.Ctx, RVal);
  6938. }
  6939. }
  6940. return true;
  6941. }
  6942. bool VisitCXXNewExpr(const CXXNewExpr *E);
  6943. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6944. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6945. APValue LValResult = E->EvaluateInContext(
  6946. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6947. Result.setFrom(Info.Ctx, LValResult);
  6948. return true;
  6949. }
  6950. // FIXME: Missing: @protocol, @selector
  6951. };
  6952. } // end anonymous namespace
  6953. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6954. bool InvalidBaseOK) {
  6955. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6956. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6957. }
  6958. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6959. if (E->getOpcode() != BO_Add &&
  6960. E->getOpcode() != BO_Sub)
  6961. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6962. const Expr *PExp = E->getLHS();
  6963. const Expr *IExp = E->getRHS();
  6964. if (IExp->getType()->isPointerType())
  6965. std::swap(PExp, IExp);
  6966. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6967. if (!EvalPtrOK && !Info.noteFailure())
  6968. return false;
  6969. llvm::APSInt Offset;
  6970. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6971. return false;
  6972. if (E->getOpcode() == BO_Sub)
  6973. negateAsSigned(Offset);
  6974. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6975. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6976. }
  6977. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6978. return evaluateLValue(E->getSubExpr(), Result);
  6979. }
  6980. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6981. const Expr *SubExpr = E->getSubExpr();
  6982. switch (E->getCastKind()) {
  6983. default:
  6984. break;
  6985. case CK_BitCast:
  6986. case CK_CPointerToObjCPointerCast:
  6987. case CK_BlockPointerToObjCPointerCast:
  6988. case CK_AnyPointerToBlockPointerCast:
  6989. case CK_AddressSpaceConversion:
  6990. if (!Visit(SubExpr))
  6991. return false;
  6992. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  6993. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  6994. // also static_casts, but we disallow them as a resolution to DR1312.
  6995. if (!E->getType()->isVoidPointerType()) {
  6996. if (!Result.InvalidBase && !Result.Designator.Invalid &&
  6997. !Result.IsNullPtr &&
  6998. Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
  6999. E->getType()->getPointeeType()) &&
  7000. Info.getStdAllocatorCaller("allocate")) {
  7001. // Inside a call to std::allocator::allocate and friends, we permit
  7002. // casting from void* back to cv1 T* for a pointer that points to a
  7003. // cv2 T.
  7004. } else {
  7005. Result.Designator.setInvalid();
  7006. if (SubExpr->getType()->isVoidPointerType())
  7007. CCEDiag(E, diag::note_constexpr_invalid_cast)
  7008. << 3 << SubExpr->getType();
  7009. else
  7010. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7011. }
  7012. }
  7013. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  7014. ZeroInitialization(E);
  7015. return true;
  7016. case CK_DerivedToBase:
  7017. case CK_UncheckedDerivedToBase:
  7018. if (!evaluatePointer(E->getSubExpr(), Result))
  7019. return false;
  7020. if (!Result.Base && Result.Offset.isZero())
  7021. return true;
  7022. // Now figure out the necessary offset to add to the base LV to get from
  7023. // the derived class to the base class.
  7024. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  7025. castAs<PointerType>()->getPointeeType(),
  7026. Result);
  7027. case CK_BaseToDerived:
  7028. if (!Visit(E->getSubExpr()))
  7029. return false;
  7030. if (!Result.Base && Result.Offset.isZero())
  7031. return true;
  7032. return HandleBaseToDerivedCast(Info, E, Result);
  7033. case CK_Dynamic:
  7034. if (!Visit(E->getSubExpr()))
  7035. return false;
  7036. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  7037. case CK_NullToPointer:
  7038. VisitIgnoredValue(E->getSubExpr());
  7039. return ZeroInitialization(E);
  7040. case CK_IntegralToPointer: {
  7041. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7042. APValue Value;
  7043. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  7044. break;
  7045. if (Value.isInt()) {
  7046. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  7047. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  7048. Result.Base = (Expr*)nullptr;
  7049. Result.InvalidBase = false;
  7050. Result.Offset = CharUnits::fromQuantity(N);
  7051. Result.Designator.setInvalid();
  7052. Result.IsNullPtr = false;
  7053. return true;
  7054. } else {
  7055. // Cast is of an lvalue, no need to change value.
  7056. Result.setFrom(Info.Ctx, Value);
  7057. return true;
  7058. }
  7059. }
  7060. case CK_ArrayToPointerDecay: {
  7061. if (SubExpr->isGLValue()) {
  7062. if (!evaluateLValue(SubExpr, Result))
  7063. return false;
  7064. } else {
  7065. APValue &Value = Info.CurrentCall->createTemporary(
  7066. SubExpr, SubExpr->getType(), false, Result);
  7067. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  7068. return false;
  7069. }
  7070. // The result is a pointer to the first element of the array.
  7071. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  7072. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  7073. Result.addArray(Info, E, CAT);
  7074. else
  7075. Result.addUnsizedArray(Info, E, AT->getElementType());
  7076. return true;
  7077. }
  7078. case CK_FunctionToPointerDecay:
  7079. return evaluateLValue(SubExpr, Result);
  7080. case CK_LValueToRValue: {
  7081. LValue LVal;
  7082. if (!evaluateLValue(E->getSubExpr(), LVal))
  7083. return false;
  7084. APValue RVal;
  7085. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  7086. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  7087. LVal, RVal))
  7088. return InvalidBaseOK &&
  7089. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  7090. return Success(RVal, E);
  7091. }
  7092. }
  7093. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7094. }
  7095. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  7096. UnaryExprOrTypeTrait ExprKind) {
  7097. // C++ [expr.alignof]p3:
  7098. // When alignof is applied to a reference type, the result is the
  7099. // alignment of the referenced type.
  7100. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  7101. T = Ref->getPointeeType();
  7102. if (T.getQualifiers().hasUnaligned())
  7103. return CharUnits::One();
  7104. const bool AlignOfReturnsPreferred =
  7105. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  7106. // __alignof is defined to return the preferred alignment.
  7107. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  7108. // as well.
  7109. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  7110. return Info.Ctx.toCharUnitsFromBits(
  7111. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  7112. // alignof and _Alignof are defined to return the ABI alignment.
  7113. else if (ExprKind == UETT_AlignOf)
  7114. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  7115. else
  7116. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  7117. }
  7118. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  7119. UnaryExprOrTypeTrait ExprKind) {
  7120. E = E->IgnoreParens();
  7121. // The kinds of expressions that we have special-case logic here for
  7122. // should be kept up to date with the special checks for those
  7123. // expressions in Sema.
  7124. // alignof decl is always accepted, even if it doesn't make sense: we default
  7125. // to 1 in those cases.
  7126. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  7127. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  7128. /*RefAsPointee*/true);
  7129. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  7130. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  7131. /*RefAsPointee*/true);
  7132. return GetAlignOfType(Info, E->getType(), ExprKind);
  7133. }
  7134. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  7135. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  7136. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  7137. return true;
  7138. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  7139. return false;
  7140. Result.setInvalid(E);
  7141. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  7142. Result.addUnsizedArray(Info, E, PointeeTy);
  7143. return true;
  7144. }
  7145. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7146. if (IsStringLiteralCall(E))
  7147. return Success(E);
  7148. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7149. return VisitBuiltinCallExpr(E, BuiltinOp);
  7150. return visitNonBuiltinCallExpr(E);
  7151. }
  7152. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7153. unsigned BuiltinOp) {
  7154. switch (BuiltinOp) {
  7155. case Builtin::BI__builtin_addressof:
  7156. return evaluateLValue(E->getArg(0), Result);
  7157. case Builtin::BI__builtin_assume_aligned: {
  7158. // We need to be very careful here because: if the pointer does not have the
  7159. // asserted alignment, then the behavior is undefined, and undefined
  7160. // behavior is non-constant.
  7161. if (!evaluatePointer(E->getArg(0), Result))
  7162. return false;
  7163. LValue OffsetResult(Result);
  7164. APSInt Alignment;
  7165. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  7166. return false;
  7167. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  7168. if (E->getNumArgs() > 2) {
  7169. APSInt Offset;
  7170. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  7171. return false;
  7172. int64_t AdditionalOffset = -Offset.getZExtValue();
  7173. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  7174. }
  7175. // If there is a base object, then it must have the correct alignment.
  7176. if (OffsetResult.Base) {
  7177. CharUnits BaseAlignment;
  7178. if (const ValueDecl *VD =
  7179. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  7180. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  7181. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  7182. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  7183. } else {
  7184. BaseAlignment = GetAlignOfType(
  7185. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  7186. }
  7187. if (BaseAlignment < Align) {
  7188. Result.Designator.setInvalid();
  7189. // FIXME: Add support to Diagnostic for long / long long.
  7190. CCEDiag(E->getArg(0),
  7191. diag::note_constexpr_baa_insufficient_alignment) << 0
  7192. << (unsigned)BaseAlignment.getQuantity()
  7193. << (unsigned)Align.getQuantity();
  7194. return false;
  7195. }
  7196. }
  7197. // The offset must also have the correct alignment.
  7198. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  7199. Result.Designator.setInvalid();
  7200. (OffsetResult.Base
  7201. ? CCEDiag(E->getArg(0),
  7202. diag::note_constexpr_baa_insufficient_alignment) << 1
  7203. : CCEDiag(E->getArg(0),
  7204. diag::note_constexpr_baa_value_insufficient_alignment))
  7205. << (int)OffsetResult.Offset.getQuantity()
  7206. << (unsigned)Align.getQuantity();
  7207. return false;
  7208. }
  7209. return true;
  7210. }
  7211. case Builtin::BI__builtin_operator_new:
  7212. return HandleOperatorNewCall(Info, E, Result);
  7213. case Builtin::BI__builtin_launder:
  7214. return evaluatePointer(E->getArg(0), Result);
  7215. case Builtin::BIstrchr:
  7216. case Builtin::BIwcschr:
  7217. case Builtin::BImemchr:
  7218. case Builtin::BIwmemchr:
  7219. if (Info.getLangOpts().CPlusPlus11)
  7220. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7221. << /*isConstexpr*/0 << /*isConstructor*/0
  7222. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7223. else
  7224. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7225. LLVM_FALLTHROUGH;
  7226. case Builtin::BI__builtin_strchr:
  7227. case Builtin::BI__builtin_wcschr:
  7228. case Builtin::BI__builtin_memchr:
  7229. case Builtin::BI__builtin_char_memchr:
  7230. case Builtin::BI__builtin_wmemchr: {
  7231. if (!Visit(E->getArg(0)))
  7232. return false;
  7233. APSInt Desired;
  7234. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  7235. return false;
  7236. uint64_t MaxLength = uint64_t(-1);
  7237. if (BuiltinOp != Builtin::BIstrchr &&
  7238. BuiltinOp != Builtin::BIwcschr &&
  7239. BuiltinOp != Builtin::BI__builtin_strchr &&
  7240. BuiltinOp != Builtin::BI__builtin_wcschr) {
  7241. APSInt N;
  7242. if (!EvaluateInteger(E->getArg(2), N, Info))
  7243. return false;
  7244. MaxLength = N.getExtValue();
  7245. }
  7246. // We cannot find the value if there are no candidates to match against.
  7247. if (MaxLength == 0u)
  7248. return ZeroInitialization(E);
  7249. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  7250. Result.Designator.Invalid)
  7251. return false;
  7252. QualType CharTy = Result.Designator.getType(Info.Ctx);
  7253. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  7254. BuiltinOp == Builtin::BI__builtin_memchr;
  7255. assert(IsRawByte ||
  7256. Info.Ctx.hasSameUnqualifiedType(
  7257. CharTy, E->getArg(0)->getType()->getPointeeType()));
  7258. // Pointers to const void may point to objects of incomplete type.
  7259. if (IsRawByte && CharTy->isIncompleteType()) {
  7260. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  7261. return false;
  7262. }
  7263. // Give up on byte-oriented matching against multibyte elements.
  7264. // FIXME: We can compare the bytes in the correct order.
  7265. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  7266. return false;
  7267. // Figure out what value we're actually looking for (after converting to
  7268. // the corresponding unsigned type if necessary).
  7269. uint64_t DesiredVal;
  7270. bool StopAtNull = false;
  7271. switch (BuiltinOp) {
  7272. case Builtin::BIstrchr:
  7273. case Builtin::BI__builtin_strchr:
  7274. // strchr compares directly to the passed integer, and therefore
  7275. // always fails if given an int that is not a char.
  7276. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  7277. E->getArg(1)->getType(),
  7278. Desired),
  7279. Desired))
  7280. return ZeroInitialization(E);
  7281. StopAtNull = true;
  7282. LLVM_FALLTHROUGH;
  7283. case Builtin::BImemchr:
  7284. case Builtin::BI__builtin_memchr:
  7285. case Builtin::BI__builtin_char_memchr:
  7286. // memchr compares by converting both sides to unsigned char. That's also
  7287. // correct for strchr if we get this far (to cope with plain char being
  7288. // unsigned in the strchr case).
  7289. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  7290. break;
  7291. case Builtin::BIwcschr:
  7292. case Builtin::BI__builtin_wcschr:
  7293. StopAtNull = true;
  7294. LLVM_FALLTHROUGH;
  7295. case Builtin::BIwmemchr:
  7296. case Builtin::BI__builtin_wmemchr:
  7297. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  7298. DesiredVal = Desired.getZExtValue();
  7299. break;
  7300. }
  7301. for (; MaxLength; --MaxLength) {
  7302. APValue Char;
  7303. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  7304. !Char.isInt())
  7305. return false;
  7306. if (Char.getInt().getZExtValue() == DesiredVal)
  7307. return true;
  7308. if (StopAtNull && !Char.getInt())
  7309. break;
  7310. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  7311. return false;
  7312. }
  7313. // Not found: return nullptr.
  7314. return ZeroInitialization(E);
  7315. }
  7316. case Builtin::BImemcpy:
  7317. case Builtin::BImemmove:
  7318. case Builtin::BIwmemcpy:
  7319. case Builtin::BIwmemmove:
  7320. if (Info.getLangOpts().CPlusPlus11)
  7321. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7322. << /*isConstexpr*/0 << /*isConstructor*/0
  7323. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7324. else
  7325. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7326. LLVM_FALLTHROUGH;
  7327. case Builtin::BI__builtin_memcpy:
  7328. case Builtin::BI__builtin_memmove:
  7329. case Builtin::BI__builtin_wmemcpy:
  7330. case Builtin::BI__builtin_wmemmove: {
  7331. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  7332. BuiltinOp == Builtin::BIwmemmove ||
  7333. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  7334. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7335. bool Move = BuiltinOp == Builtin::BImemmove ||
  7336. BuiltinOp == Builtin::BIwmemmove ||
  7337. BuiltinOp == Builtin::BI__builtin_memmove ||
  7338. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7339. // The result of mem* is the first argument.
  7340. if (!Visit(E->getArg(0)))
  7341. return false;
  7342. LValue Dest = Result;
  7343. LValue Src;
  7344. if (!EvaluatePointer(E->getArg(1), Src, Info))
  7345. return false;
  7346. APSInt N;
  7347. if (!EvaluateInteger(E->getArg(2), N, Info))
  7348. return false;
  7349. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  7350. // If the size is zero, we treat this as always being a valid no-op.
  7351. // (Even if one of the src and dest pointers is null.)
  7352. if (!N)
  7353. return true;
  7354. // Otherwise, if either of the operands is null, we can't proceed. Don't
  7355. // try to determine the type of the copied objects, because there aren't
  7356. // any.
  7357. if (!Src.Base || !Dest.Base) {
  7358. APValue Val;
  7359. (!Src.Base ? Src : Dest).moveInto(Val);
  7360. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  7361. << Move << WChar << !!Src.Base
  7362. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  7363. return false;
  7364. }
  7365. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  7366. return false;
  7367. // We require that Src and Dest are both pointers to arrays of
  7368. // trivially-copyable type. (For the wide version, the designator will be
  7369. // invalid if the designated object is not a wchar_t.)
  7370. QualType T = Dest.Designator.getType(Info.Ctx);
  7371. QualType SrcT = Src.Designator.getType(Info.Ctx);
  7372. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  7373. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  7374. return false;
  7375. }
  7376. if (T->isIncompleteType()) {
  7377. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  7378. return false;
  7379. }
  7380. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  7381. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  7382. return false;
  7383. }
  7384. // Figure out how many T's we're copying.
  7385. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  7386. if (!WChar) {
  7387. uint64_t Remainder;
  7388. llvm::APInt OrigN = N;
  7389. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  7390. if (Remainder) {
  7391. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7392. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  7393. << (unsigned)TSize;
  7394. return false;
  7395. }
  7396. }
  7397. // Check that the copying will remain within the arrays, just so that we
  7398. // can give a more meaningful diagnostic. This implicitly also checks that
  7399. // N fits into 64 bits.
  7400. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  7401. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  7402. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  7403. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7404. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  7405. << N.toString(10, /*Signed*/false);
  7406. return false;
  7407. }
  7408. uint64_t NElems = N.getZExtValue();
  7409. uint64_t NBytes = NElems * TSize;
  7410. // Check for overlap.
  7411. int Direction = 1;
  7412. if (HasSameBase(Src, Dest)) {
  7413. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  7414. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  7415. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  7416. // Dest is inside the source region.
  7417. if (!Move) {
  7418. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7419. return false;
  7420. }
  7421. // For memmove and friends, copy backwards.
  7422. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  7423. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  7424. return false;
  7425. Direction = -1;
  7426. } else if (!Move && SrcOffset >= DestOffset &&
  7427. SrcOffset - DestOffset < NBytes) {
  7428. // Src is inside the destination region for memcpy: invalid.
  7429. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7430. return false;
  7431. }
  7432. }
  7433. while (true) {
  7434. APValue Val;
  7435. // FIXME: Set WantObjectRepresentation to true if we're copying a
  7436. // char-like type?
  7437. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  7438. !handleAssignment(Info, E, Dest, T, Val))
  7439. return false;
  7440. // Do not iterate past the last element; if we're copying backwards, that
  7441. // might take us off the start of the array.
  7442. if (--NElems == 0)
  7443. return true;
  7444. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  7445. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  7446. return false;
  7447. }
  7448. }
  7449. default:
  7450. break;
  7451. }
  7452. return visitNonBuiltinCallExpr(E);
  7453. }
  7454. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  7455. APValue &Result, const InitListExpr *ILE,
  7456. QualType AllocType);
  7457. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  7458. if (!Info.getLangOpts().CPlusPlus2a)
  7459. Info.CCEDiag(E, diag::note_constexpr_new);
  7460. // We cannot speculatively evaluate a delete expression.
  7461. if (Info.SpeculativeEvaluationDepth)
  7462. return false;
  7463. FunctionDecl *OperatorNew = E->getOperatorNew();
  7464. bool IsNothrow = false;
  7465. bool IsPlacement = false;
  7466. if (OperatorNew->isReservedGlobalPlacementOperator() &&
  7467. Info.CurrentCall->isStdFunction() && !E->isArray()) {
  7468. // FIXME Support array placement new.
  7469. assert(E->getNumPlacementArgs() == 1);
  7470. if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
  7471. return false;
  7472. if (Result.Designator.Invalid)
  7473. return false;
  7474. IsPlacement = true;
  7475. } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  7476. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  7477. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  7478. return false;
  7479. } else if (E->getNumPlacementArgs()) {
  7480. // The only new-placement list we support is of the form (std::nothrow).
  7481. //
  7482. // FIXME: There is no restriction on this, but it's not clear that any
  7483. // other form makes any sense. We get here for cases such as:
  7484. //
  7485. // new (std::align_val_t{N}) X(int)
  7486. //
  7487. // (which should presumably be valid only if N is a multiple of
  7488. // alignof(int), and in any case can't be deallocated unless N is
  7489. // alignof(X) and X has new-extended alignment).
  7490. if (E->getNumPlacementArgs() != 1 ||
  7491. !E->getPlacementArg(0)->getType()->isNothrowT())
  7492. return Error(E, diag::note_constexpr_new_placement);
  7493. LValue Nothrow;
  7494. if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
  7495. return false;
  7496. IsNothrow = true;
  7497. }
  7498. const Expr *Init = E->getInitializer();
  7499. const InitListExpr *ResizedArrayILE = nullptr;
  7500. QualType AllocType = E->getAllocatedType();
  7501. if (Optional<const Expr*> ArraySize = E->getArraySize()) {
  7502. const Expr *Stripped = *ArraySize;
  7503. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  7504. Stripped = ICE->getSubExpr())
  7505. if (ICE->getCastKind() != CK_NoOp &&
  7506. ICE->getCastKind() != CK_IntegralCast)
  7507. break;
  7508. llvm::APSInt ArrayBound;
  7509. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  7510. return false;
  7511. // C++ [expr.new]p9:
  7512. // The expression is erroneous if:
  7513. // -- [...] its value before converting to size_t [or] applying the
  7514. // second standard conversion sequence is less than zero
  7515. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  7516. if (IsNothrow)
  7517. return ZeroInitialization(E);
  7518. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  7519. << ArrayBound << (*ArraySize)->getSourceRange();
  7520. return false;
  7521. }
  7522. // -- its value is such that the size of the allocated object would
  7523. // exceed the implementation-defined limit
  7524. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  7525. ArrayBound) >
  7526. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  7527. if (IsNothrow)
  7528. return ZeroInitialization(E);
  7529. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  7530. << ArrayBound << (*ArraySize)->getSourceRange();
  7531. return false;
  7532. }
  7533. // -- the new-initializer is a braced-init-list and the number of
  7534. // array elements for which initializers are provided [...]
  7535. // exceeds the number of elements to initialize
  7536. if (Init) {
  7537. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  7538. assert(CAT && "unexpected type for array initializer");
  7539. unsigned Bits =
  7540. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  7541. llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
  7542. llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
  7543. if (InitBound.ugt(AllocBound)) {
  7544. if (IsNothrow)
  7545. return ZeroInitialization(E);
  7546. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  7547. << AllocBound.toString(10, /*Signed=*/false)
  7548. << InitBound.toString(10, /*Signed=*/false)
  7549. << (*ArraySize)->getSourceRange();
  7550. return false;
  7551. }
  7552. // If the sizes differ, we must have an initializer list, and we need
  7553. // special handling for this case when we initialize.
  7554. if (InitBound != AllocBound)
  7555. ResizedArrayILE = cast<InitListExpr>(Init);
  7556. }
  7557. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
  7558. ArrayType::Normal, 0);
  7559. } else {
  7560. assert(!AllocType->isArrayType() &&
  7561. "array allocation with non-array new");
  7562. }
  7563. APValue *Val;
  7564. if (IsPlacement) {
  7565. AccessKinds AK = AK_Construct;
  7566. struct FindObjectHandler {
  7567. EvalInfo &Info;
  7568. const Expr *E;
  7569. QualType AllocType;
  7570. const AccessKinds AccessKind;
  7571. APValue *Value;
  7572. typedef bool result_type;
  7573. bool failed() { return false; }
  7574. bool found(APValue &Subobj, QualType SubobjType) {
  7575. // FIXME: Reject the cases where [basic.life]p8 would not permit the
  7576. // old name of the object to be used to name the new object.
  7577. if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
  7578. Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
  7579. SubobjType << AllocType;
  7580. return false;
  7581. }
  7582. Value = &Subobj;
  7583. return true;
  7584. }
  7585. bool found(APSInt &Value, QualType SubobjType) {
  7586. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  7587. return false;
  7588. }
  7589. bool found(APFloat &Value, QualType SubobjType) {
  7590. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  7591. return false;
  7592. }
  7593. } Handler = {Info, E, AllocType, AK, nullptr};
  7594. CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
  7595. if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
  7596. return false;
  7597. Val = Handler.Value;
  7598. // [basic.life]p1:
  7599. // The lifetime of an object o of type T ends when [...] the storage
  7600. // which the object occupies is [...] reused by an object that is not
  7601. // nested within o (6.6.2).
  7602. *Val = APValue();
  7603. } else {
  7604. // Perform the allocation and obtain a pointer to the resulting object.
  7605. Val = Info.createHeapAlloc(E, AllocType, Result);
  7606. if (!Val)
  7607. return false;
  7608. }
  7609. if (ResizedArrayILE) {
  7610. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  7611. AllocType))
  7612. return false;
  7613. } else if (Init) {
  7614. if (!EvaluateInPlace(*Val, Info, Result, Init))
  7615. return false;
  7616. } else {
  7617. *Val = getDefaultInitValue(AllocType);
  7618. }
  7619. // Array new returns a pointer to the first element, not a pointer to the
  7620. // array.
  7621. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  7622. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  7623. return true;
  7624. }
  7625. //===----------------------------------------------------------------------===//
  7626. // Member Pointer Evaluation
  7627. //===----------------------------------------------------------------------===//
  7628. namespace {
  7629. class MemberPointerExprEvaluator
  7630. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  7631. MemberPtr &Result;
  7632. bool Success(const ValueDecl *D) {
  7633. Result = MemberPtr(D);
  7634. return true;
  7635. }
  7636. public:
  7637. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  7638. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7639. bool Success(const APValue &V, const Expr *E) {
  7640. Result.setFrom(V);
  7641. return true;
  7642. }
  7643. bool ZeroInitialization(const Expr *E) {
  7644. return Success((const ValueDecl*)nullptr);
  7645. }
  7646. bool VisitCastExpr(const CastExpr *E);
  7647. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7648. };
  7649. } // end anonymous namespace
  7650. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  7651. EvalInfo &Info) {
  7652. assert(E->isRValue() && E->getType()->isMemberPointerType());
  7653. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  7654. }
  7655. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7656. switch (E->getCastKind()) {
  7657. default:
  7658. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7659. case CK_NullToMemberPointer:
  7660. VisitIgnoredValue(E->getSubExpr());
  7661. return ZeroInitialization(E);
  7662. case CK_BaseToDerivedMemberPointer: {
  7663. if (!Visit(E->getSubExpr()))
  7664. return false;
  7665. if (E->path_empty())
  7666. return true;
  7667. // Base-to-derived member pointer casts store the path in derived-to-base
  7668. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  7669. // the wrong end of the derived->base arc, so stagger the path by one class.
  7670. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  7671. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  7672. PathI != PathE; ++PathI) {
  7673. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7674. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  7675. if (!Result.castToDerived(Derived))
  7676. return Error(E);
  7677. }
  7678. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  7679. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  7680. return Error(E);
  7681. return true;
  7682. }
  7683. case CK_DerivedToBaseMemberPointer:
  7684. if (!Visit(E->getSubExpr()))
  7685. return false;
  7686. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7687. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7688. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7689. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7690. if (!Result.castToBase(Base))
  7691. return Error(E);
  7692. }
  7693. return true;
  7694. }
  7695. }
  7696. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7697. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  7698. // member can be formed.
  7699. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  7700. }
  7701. //===----------------------------------------------------------------------===//
  7702. // Record Evaluation
  7703. //===----------------------------------------------------------------------===//
  7704. namespace {
  7705. class RecordExprEvaluator
  7706. : public ExprEvaluatorBase<RecordExprEvaluator> {
  7707. const LValue &This;
  7708. APValue &Result;
  7709. public:
  7710. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  7711. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  7712. bool Success(const APValue &V, const Expr *E) {
  7713. Result = V;
  7714. return true;
  7715. }
  7716. bool ZeroInitialization(const Expr *E) {
  7717. return ZeroInitialization(E, E->getType());
  7718. }
  7719. bool ZeroInitialization(const Expr *E, QualType T);
  7720. bool VisitCallExpr(const CallExpr *E) {
  7721. return handleCallExpr(E, Result, &This);
  7722. }
  7723. bool VisitCastExpr(const CastExpr *E);
  7724. bool VisitInitListExpr(const InitListExpr *E);
  7725. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7726. return VisitCXXConstructExpr(E, E->getType());
  7727. }
  7728. bool VisitLambdaExpr(const LambdaExpr *E);
  7729. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  7730. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  7731. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  7732. bool VisitBinCmp(const BinaryOperator *E);
  7733. };
  7734. }
  7735. /// Perform zero-initialization on an object of non-union class type.
  7736. /// C++11 [dcl.init]p5:
  7737. /// To zero-initialize an object or reference of type T means:
  7738. /// [...]
  7739. /// -- if T is a (possibly cv-qualified) non-union class type,
  7740. /// each non-static data member and each base-class subobject is
  7741. /// zero-initialized
  7742. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  7743. const RecordDecl *RD,
  7744. const LValue &This, APValue &Result) {
  7745. assert(!RD->isUnion() && "Expected non-union class type");
  7746. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  7747. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  7748. std::distance(RD->field_begin(), RD->field_end()));
  7749. if (RD->isInvalidDecl()) return false;
  7750. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7751. if (CD) {
  7752. unsigned Index = 0;
  7753. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  7754. End = CD->bases_end(); I != End; ++I, ++Index) {
  7755. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  7756. LValue Subobject = This;
  7757. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  7758. return false;
  7759. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  7760. Result.getStructBase(Index)))
  7761. return false;
  7762. }
  7763. }
  7764. for (const auto *I : RD->fields()) {
  7765. // -- if T is a reference type, no initialization is performed.
  7766. if (I->getType()->isReferenceType())
  7767. continue;
  7768. LValue Subobject = This;
  7769. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  7770. return false;
  7771. ImplicitValueInitExpr VIE(I->getType());
  7772. if (!EvaluateInPlace(
  7773. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  7774. return false;
  7775. }
  7776. return true;
  7777. }
  7778. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  7779. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  7780. if (RD->isInvalidDecl()) return false;
  7781. if (RD->isUnion()) {
  7782. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  7783. // object's first non-static named data member is zero-initialized
  7784. RecordDecl::field_iterator I = RD->field_begin();
  7785. if (I == RD->field_end()) {
  7786. Result = APValue((const FieldDecl*)nullptr);
  7787. return true;
  7788. }
  7789. LValue Subobject = This;
  7790. if (!HandleLValueMember(Info, E, Subobject, *I))
  7791. return false;
  7792. Result = APValue(*I);
  7793. ImplicitValueInitExpr VIE(I->getType());
  7794. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  7795. }
  7796. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  7797. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  7798. return false;
  7799. }
  7800. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  7801. }
  7802. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7803. switch (E->getCastKind()) {
  7804. default:
  7805. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7806. case CK_ConstructorConversion:
  7807. return Visit(E->getSubExpr());
  7808. case CK_DerivedToBase:
  7809. case CK_UncheckedDerivedToBase: {
  7810. APValue DerivedObject;
  7811. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  7812. return false;
  7813. if (!DerivedObject.isStruct())
  7814. return Error(E->getSubExpr());
  7815. // Derived-to-base rvalue conversion: just slice off the derived part.
  7816. APValue *Value = &DerivedObject;
  7817. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  7818. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7819. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7820. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  7821. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7822. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  7823. RD = Base;
  7824. }
  7825. Result = *Value;
  7826. return true;
  7827. }
  7828. }
  7829. }
  7830. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7831. if (E->isTransparent())
  7832. return Visit(E->getInit(0));
  7833. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  7834. if (RD->isInvalidDecl()) return false;
  7835. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7836. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  7837. EvalInfo::EvaluatingConstructorRAII EvalObj(
  7838. Info,
  7839. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  7840. CXXRD && CXXRD->getNumBases());
  7841. if (RD->isUnion()) {
  7842. const FieldDecl *Field = E->getInitializedFieldInUnion();
  7843. Result = APValue(Field);
  7844. if (!Field)
  7845. return true;
  7846. // If the initializer list for a union does not contain any elements, the
  7847. // first element of the union is value-initialized.
  7848. // FIXME: The element should be initialized from an initializer list.
  7849. // Is this difference ever observable for initializer lists which
  7850. // we don't build?
  7851. ImplicitValueInitExpr VIE(Field->getType());
  7852. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  7853. LValue Subobject = This;
  7854. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  7855. return false;
  7856. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7857. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7858. isa<CXXDefaultInitExpr>(InitExpr));
  7859. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  7860. }
  7861. if (!Result.hasValue())
  7862. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  7863. std::distance(RD->field_begin(), RD->field_end()));
  7864. unsigned ElementNo = 0;
  7865. bool Success = true;
  7866. // Initialize base classes.
  7867. if (CXXRD && CXXRD->getNumBases()) {
  7868. for (const auto &Base : CXXRD->bases()) {
  7869. assert(ElementNo < E->getNumInits() && "missing init for base class");
  7870. const Expr *Init = E->getInit(ElementNo);
  7871. LValue Subobject = This;
  7872. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  7873. return false;
  7874. APValue &FieldVal = Result.getStructBase(ElementNo);
  7875. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  7876. if (!Info.noteFailure())
  7877. return false;
  7878. Success = false;
  7879. }
  7880. ++ElementNo;
  7881. }
  7882. EvalObj.finishedConstructingBases();
  7883. }
  7884. // Initialize members.
  7885. for (const auto *Field : RD->fields()) {
  7886. // Anonymous bit-fields are not considered members of the class for
  7887. // purposes of aggregate initialization.
  7888. if (Field->isUnnamedBitfield())
  7889. continue;
  7890. LValue Subobject = This;
  7891. bool HaveInit = ElementNo < E->getNumInits();
  7892. // FIXME: Diagnostics here should point to the end of the initializer
  7893. // list, not the start.
  7894. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  7895. Subobject, Field, &Layout))
  7896. return false;
  7897. // Perform an implicit value-initialization for members beyond the end of
  7898. // the initializer list.
  7899. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  7900. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  7901. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7902. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7903. isa<CXXDefaultInitExpr>(Init));
  7904. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7905. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  7906. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  7907. FieldVal, Field))) {
  7908. if (!Info.noteFailure())
  7909. return false;
  7910. Success = false;
  7911. }
  7912. }
  7913. return Success;
  7914. }
  7915. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7916. QualType T) {
  7917. // Note that E's type is not necessarily the type of our class here; we might
  7918. // be initializing an array element instead.
  7919. const CXXConstructorDecl *FD = E->getConstructor();
  7920. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  7921. bool ZeroInit = E->requiresZeroInitialization();
  7922. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  7923. // If we've already performed zero-initialization, we're already done.
  7924. if (Result.hasValue())
  7925. return true;
  7926. if (ZeroInit)
  7927. return ZeroInitialization(E, T);
  7928. Result = getDefaultInitValue(T);
  7929. return true;
  7930. }
  7931. const FunctionDecl *Definition = nullptr;
  7932. auto Body = FD->getBody(Definition);
  7933. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7934. return false;
  7935. // Avoid materializing a temporary for an elidable copy/move constructor.
  7936. if (E->isElidable() && !ZeroInit)
  7937. if (const MaterializeTemporaryExpr *ME
  7938. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  7939. return Visit(ME->GetTemporaryExpr());
  7940. if (ZeroInit && !ZeroInitialization(E, T))
  7941. return false;
  7942. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  7943. return HandleConstructorCall(E, This, Args,
  7944. cast<CXXConstructorDecl>(Definition), Info,
  7945. Result);
  7946. }
  7947. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  7948. const CXXInheritedCtorInitExpr *E) {
  7949. if (!Info.CurrentCall) {
  7950. assert(Info.checkingPotentialConstantExpression());
  7951. return false;
  7952. }
  7953. const CXXConstructorDecl *FD = E->getConstructor();
  7954. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  7955. return false;
  7956. const FunctionDecl *Definition = nullptr;
  7957. auto Body = FD->getBody(Definition);
  7958. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7959. return false;
  7960. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  7961. cast<CXXConstructorDecl>(Definition), Info,
  7962. Result);
  7963. }
  7964. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  7965. const CXXStdInitializerListExpr *E) {
  7966. const ConstantArrayType *ArrayType =
  7967. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  7968. LValue Array;
  7969. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  7970. return false;
  7971. // Get a pointer to the first element of the array.
  7972. Array.addArray(Info, E, ArrayType);
  7973. // FIXME: Perform the checks on the field types in SemaInit.
  7974. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  7975. RecordDecl::field_iterator Field = Record->field_begin();
  7976. if (Field == Record->field_end())
  7977. return Error(E);
  7978. // Start pointer.
  7979. if (!Field->getType()->isPointerType() ||
  7980. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7981. ArrayType->getElementType()))
  7982. return Error(E);
  7983. // FIXME: What if the initializer_list type has base classes, etc?
  7984. Result = APValue(APValue::UninitStruct(), 0, 2);
  7985. Array.moveInto(Result.getStructField(0));
  7986. if (++Field == Record->field_end())
  7987. return Error(E);
  7988. if (Field->getType()->isPointerType() &&
  7989. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7990. ArrayType->getElementType())) {
  7991. // End pointer.
  7992. if (!HandleLValueArrayAdjustment(Info, E, Array,
  7993. ArrayType->getElementType(),
  7994. ArrayType->getSize().getZExtValue()))
  7995. return false;
  7996. Array.moveInto(Result.getStructField(1));
  7997. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  7998. // Length.
  7999. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  8000. else
  8001. return Error(E);
  8002. if (++Field != Record->field_end())
  8003. return Error(E);
  8004. return true;
  8005. }
  8006. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  8007. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  8008. if (ClosureClass->isInvalidDecl())
  8009. return false;
  8010. const size_t NumFields =
  8011. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  8012. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  8013. E->capture_init_end()) &&
  8014. "The number of lambda capture initializers should equal the number of "
  8015. "fields within the closure type");
  8016. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  8017. // Iterate through all the lambda's closure object's fields and initialize
  8018. // them.
  8019. auto *CaptureInitIt = E->capture_init_begin();
  8020. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  8021. bool Success = true;
  8022. for (const auto *Field : ClosureClass->fields()) {
  8023. assert(CaptureInitIt != E->capture_init_end());
  8024. // Get the initializer for this field
  8025. Expr *const CurFieldInit = *CaptureInitIt++;
  8026. // If there is no initializer, either this is a VLA or an error has
  8027. // occurred.
  8028. if (!CurFieldInit)
  8029. return Error(E);
  8030. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  8031. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  8032. if (!Info.keepEvaluatingAfterFailure())
  8033. return false;
  8034. Success = false;
  8035. }
  8036. ++CaptureIt;
  8037. }
  8038. return Success;
  8039. }
  8040. static bool EvaluateRecord(const Expr *E, const LValue &This,
  8041. APValue &Result, EvalInfo &Info) {
  8042. assert(E->isRValue() && E->getType()->isRecordType() &&
  8043. "can't evaluate expression as a record rvalue");
  8044. return RecordExprEvaluator(Info, This, Result).Visit(E);
  8045. }
  8046. //===----------------------------------------------------------------------===//
  8047. // Temporary Evaluation
  8048. //
  8049. // Temporaries are represented in the AST as rvalues, but generally behave like
  8050. // lvalues. The full-object of which the temporary is a subobject is implicitly
  8051. // materialized so that a reference can bind to it.
  8052. //===----------------------------------------------------------------------===//
  8053. namespace {
  8054. class TemporaryExprEvaluator
  8055. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  8056. public:
  8057. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  8058. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  8059. /// Visit an expression which constructs the value of this temporary.
  8060. bool VisitConstructExpr(const Expr *E) {
  8061. APValue &Value =
  8062. Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
  8063. return EvaluateInPlace(Value, Info, Result, E);
  8064. }
  8065. bool VisitCastExpr(const CastExpr *E) {
  8066. switch (E->getCastKind()) {
  8067. default:
  8068. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  8069. case CK_ConstructorConversion:
  8070. return VisitConstructExpr(E->getSubExpr());
  8071. }
  8072. }
  8073. bool VisitInitListExpr(const InitListExpr *E) {
  8074. return VisitConstructExpr(E);
  8075. }
  8076. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8077. return VisitConstructExpr(E);
  8078. }
  8079. bool VisitCallExpr(const CallExpr *E) {
  8080. return VisitConstructExpr(E);
  8081. }
  8082. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  8083. return VisitConstructExpr(E);
  8084. }
  8085. bool VisitLambdaExpr(const LambdaExpr *E) {
  8086. return VisitConstructExpr(E);
  8087. }
  8088. };
  8089. } // end anonymous namespace
  8090. /// Evaluate an expression of record type as a temporary.
  8091. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  8092. assert(E->isRValue() && E->getType()->isRecordType());
  8093. return TemporaryExprEvaluator(Info, Result).Visit(E);
  8094. }
  8095. //===----------------------------------------------------------------------===//
  8096. // Vector Evaluation
  8097. //===----------------------------------------------------------------------===//
  8098. namespace {
  8099. class VectorExprEvaluator
  8100. : public ExprEvaluatorBase<VectorExprEvaluator> {
  8101. APValue &Result;
  8102. public:
  8103. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  8104. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8105. bool Success(ArrayRef<APValue> V, const Expr *E) {
  8106. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  8107. // FIXME: remove this APValue copy.
  8108. Result = APValue(V.data(), V.size());
  8109. return true;
  8110. }
  8111. bool Success(const APValue &V, const Expr *E) {
  8112. assert(V.isVector());
  8113. Result = V;
  8114. return true;
  8115. }
  8116. bool ZeroInitialization(const Expr *E);
  8117. bool VisitUnaryReal(const UnaryOperator *E)
  8118. { return Visit(E->getSubExpr()); }
  8119. bool VisitCastExpr(const CastExpr* E);
  8120. bool VisitInitListExpr(const InitListExpr *E);
  8121. bool VisitUnaryImag(const UnaryOperator *E);
  8122. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  8123. // binary comparisons, binary and/or/xor,
  8124. // shufflevector, ExtVectorElementExpr
  8125. };
  8126. } // end anonymous namespace
  8127. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  8128. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  8129. return VectorExprEvaluator(Info, Result).Visit(E);
  8130. }
  8131. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8132. const VectorType *VTy = E->getType()->castAs<VectorType>();
  8133. unsigned NElts = VTy->getNumElements();
  8134. const Expr *SE = E->getSubExpr();
  8135. QualType SETy = SE->getType();
  8136. switch (E->getCastKind()) {
  8137. case CK_VectorSplat: {
  8138. APValue Val = APValue();
  8139. if (SETy->isIntegerType()) {
  8140. APSInt IntResult;
  8141. if (!EvaluateInteger(SE, IntResult, Info))
  8142. return false;
  8143. Val = APValue(std::move(IntResult));
  8144. } else if (SETy->isRealFloatingType()) {
  8145. APFloat FloatResult(0.0);
  8146. if (!EvaluateFloat(SE, FloatResult, Info))
  8147. return false;
  8148. Val = APValue(std::move(FloatResult));
  8149. } else {
  8150. return Error(E);
  8151. }
  8152. // Splat and create vector APValue.
  8153. SmallVector<APValue, 4> Elts(NElts, Val);
  8154. return Success(Elts, E);
  8155. }
  8156. case CK_BitCast: {
  8157. // Evaluate the operand into an APInt we can extract from.
  8158. llvm::APInt SValInt;
  8159. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  8160. return false;
  8161. // Extract the elements
  8162. QualType EltTy = VTy->getElementType();
  8163. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  8164. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  8165. SmallVector<APValue, 4> Elts;
  8166. if (EltTy->isRealFloatingType()) {
  8167. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  8168. unsigned FloatEltSize = EltSize;
  8169. if (&Sem == &APFloat::x87DoubleExtended())
  8170. FloatEltSize = 80;
  8171. for (unsigned i = 0; i < NElts; i++) {
  8172. llvm::APInt Elt;
  8173. if (BigEndian)
  8174. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  8175. else
  8176. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  8177. Elts.push_back(APValue(APFloat(Sem, Elt)));
  8178. }
  8179. } else if (EltTy->isIntegerType()) {
  8180. for (unsigned i = 0; i < NElts; i++) {
  8181. llvm::APInt Elt;
  8182. if (BigEndian)
  8183. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  8184. else
  8185. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  8186. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  8187. }
  8188. } else {
  8189. return Error(E);
  8190. }
  8191. return Success(Elts, E);
  8192. }
  8193. default:
  8194. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8195. }
  8196. }
  8197. bool
  8198. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  8199. const VectorType *VT = E->getType()->castAs<VectorType>();
  8200. unsigned NumInits = E->getNumInits();
  8201. unsigned NumElements = VT->getNumElements();
  8202. QualType EltTy = VT->getElementType();
  8203. SmallVector<APValue, 4> Elements;
  8204. // The number of initializers can be less than the number of
  8205. // vector elements. For OpenCL, this can be due to nested vector
  8206. // initialization. For GCC compatibility, missing trailing elements
  8207. // should be initialized with zeroes.
  8208. unsigned CountInits = 0, CountElts = 0;
  8209. while (CountElts < NumElements) {
  8210. // Handle nested vector initialization.
  8211. if (CountInits < NumInits
  8212. && E->getInit(CountInits)->getType()->isVectorType()) {
  8213. APValue v;
  8214. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  8215. return Error(E);
  8216. unsigned vlen = v.getVectorLength();
  8217. for (unsigned j = 0; j < vlen; j++)
  8218. Elements.push_back(v.getVectorElt(j));
  8219. CountElts += vlen;
  8220. } else if (EltTy->isIntegerType()) {
  8221. llvm::APSInt sInt(32);
  8222. if (CountInits < NumInits) {
  8223. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  8224. return false;
  8225. } else // trailing integer zero.
  8226. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  8227. Elements.push_back(APValue(sInt));
  8228. CountElts++;
  8229. } else {
  8230. llvm::APFloat f(0.0);
  8231. if (CountInits < NumInits) {
  8232. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  8233. return false;
  8234. } else // trailing float zero.
  8235. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  8236. Elements.push_back(APValue(f));
  8237. CountElts++;
  8238. }
  8239. CountInits++;
  8240. }
  8241. return Success(Elements, E);
  8242. }
  8243. bool
  8244. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  8245. const auto *VT = E->getType()->castAs<VectorType>();
  8246. QualType EltTy = VT->getElementType();
  8247. APValue ZeroElement;
  8248. if (EltTy->isIntegerType())
  8249. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  8250. else
  8251. ZeroElement =
  8252. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  8253. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  8254. return Success(Elements, E);
  8255. }
  8256. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8257. VisitIgnoredValue(E->getSubExpr());
  8258. return ZeroInitialization(E);
  8259. }
  8260. //===----------------------------------------------------------------------===//
  8261. // Array Evaluation
  8262. //===----------------------------------------------------------------------===//
  8263. namespace {
  8264. class ArrayExprEvaluator
  8265. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  8266. const LValue &This;
  8267. APValue &Result;
  8268. public:
  8269. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  8270. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  8271. bool Success(const APValue &V, const Expr *E) {
  8272. assert(V.isArray() && "expected array");
  8273. Result = V;
  8274. return true;
  8275. }
  8276. bool ZeroInitialization(const Expr *E) {
  8277. const ConstantArrayType *CAT =
  8278. Info.Ctx.getAsConstantArrayType(E->getType());
  8279. if (!CAT)
  8280. return Error(E);
  8281. Result = APValue(APValue::UninitArray(), 0,
  8282. CAT->getSize().getZExtValue());
  8283. if (!Result.hasArrayFiller()) return true;
  8284. // Zero-initialize all elements.
  8285. LValue Subobject = This;
  8286. Subobject.addArray(Info, E, CAT);
  8287. ImplicitValueInitExpr VIE(CAT->getElementType());
  8288. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  8289. }
  8290. bool VisitCallExpr(const CallExpr *E) {
  8291. return handleCallExpr(E, Result, &This);
  8292. }
  8293. bool VisitInitListExpr(const InitListExpr *E,
  8294. QualType AllocType = QualType());
  8295. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  8296. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  8297. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  8298. const LValue &Subobject,
  8299. APValue *Value, QualType Type);
  8300. bool VisitStringLiteral(const StringLiteral *E,
  8301. QualType AllocType = QualType()) {
  8302. expandStringLiteral(Info, E, Result, AllocType);
  8303. return true;
  8304. }
  8305. };
  8306. } // end anonymous namespace
  8307. static bool EvaluateArray(const Expr *E, const LValue &This,
  8308. APValue &Result, EvalInfo &Info) {
  8309. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  8310. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  8311. }
  8312. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  8313. APValue &Result, const InitListExpr *ILE,
  8314. QualType AllocType) {
  8315. assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
  8316. "not an array rvalue");
  8317. return ArrayExprEvaluator(Info, This, Result)
  8318. .VisitInitListExpr(ILE, AllocType);
  8319. }
  8320. // Return true iff the given array filler may depend on the element index.
  8321. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  8322. // For now, just whitelist non-class value-initialization and initialization
  8323. // lists comprised of them.
  8324. if (isa<ImplicitValueInitExpr>(FillerExpr))
  8325. return false;
  8326. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  8327. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  8328. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  8329. return true;
  8330. }
  8331. return false;
  8332. }
  8333. return true;
  8334. }
  8335. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  8336. QualType AllocType) {
  8337. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  8338. AllocType.isNull() ? E->getType() : AllocType);
  8339. if (!CAT)
  8340. return Error(E);
  8341. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  8342. // an appropriately-typed string literal enclosed in braces.
  8343. if (E->isStringLiteralInit()) {
  8344. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
  8345. // FIXME: Support ObjCEncodeExpr here once we support it in
  8346. // ArrayExprEvaluator generally.
  8347. if (!SL)
  8348. return Error(E);
  8349. return VisitStringLiteral(SL, AllocType);
  8350. }
  8351. bool Success = true;
  8352. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  8353. "zero-initialized array shouldn't have any initialized elts");
  8354. APValue Filler;
  8355. if (Result.isArray() && Result.hasArrayFiller())
  8356. Filler = Result.getArrayFiller();
  8357. unsigned NumEltsToInit = E->getNumInits();
  8358. unsigned NumElts = CAT->getSize().getZExtValue();
  8359. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  8360. // If the initializer might depend on the array index, run it for each
  8361. // array element.
  8362. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  8363. NumEltsToInit = NumElts;
  8364. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  8365. << NumEltsToInit << ".\n");
  8366. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  8367. // If the array was previously zero-initialized, preserve the
  8368. // zero-initialized values.
  8369. if (Filler.hasValue()) {
  8370. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  8371. Result.getArrayInitializedElt(I) = Filler;
  8372. if (Result.hasArrayFiller())
  8373. Result.getArrayFiller() = Filler;
  8374. }
  8375. LValue Subobject = This;
  8376. Subobject.addArray(Info, E, CAT);
  8377. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  8378. const Expr *Init =
  8379. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  8380. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8381. Info, Subobject, Init) ||
  8382. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  8383. CAT->getElementType(), 1)) {
  8384. if (!Info.noteFailure())
  8385. return false;
  8386. Success = false;
  8387. }
  8388. }
  8389. if (!Result.hasArrayFiller())
  8390. return Success;
  8391. // If we get here, we have a trivial filler, which we can just evaluate
  8392. // once and splat over the rest of the array elements.
  8393. assert(FillerExpr && "no array filler for incomplete init list");
  8394. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  8395. FillerExpr) && Success;
  8396. }
  8397. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  8398. LValue CommonLV;
  8399. if (E->getCommonExpr() &&
  8400. !Evaluate(Info.CurrentCall->createTemporary(
  8401. E->getCommonExpr(),
  8402. getStorageType(Info.Ctx, E->getCommonExpr()), false,
  8403. CommonLV),
  8404. Info, E->getCommonExpr()->getSourceExpr()))
  8405. return false;
  8406. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  8407. uint64_t Elements = CAT->getSize().getZExtValue();
  8408. Result = APValue(APValue::UninitArray(), Elements, Elements);
  8409. LValue Subobject = This;
  8410. Subobject.addArray(Info, E, CAT);
  8411. bool Success = true;
  8412. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  8413. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8414. Info, Subobject, E->getSubExpr()) ||
  8415. !HandleLValueArrayAdjustment(Info, E, Subobject,
  8416. CAT->getElementType(), 1)) {
  8417. if (!Info.noteFailure())
  8418. return false;
  8419. Success = false;
  8420. }
  8421. }
  8422. return Success;
  8423. }
  8424. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8425. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  8426. }
  8427. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8428. const LValue &Subobject,
  8429. APValue *Value,
  8430. QualType Type) {
  8431. bool HadZeroInit = Value->hasValue();
  8432. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  8433. unsigned N = CAT->getSize().getZExtValue();
  8434. // Preserve the array filler if we had prior zero-initialization.
  8435. APValue Filler =
  8436. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  8437. : APValue();
  8438. *Value = APValue(APValue::UninitArray(), N, N);
  8439. if (HadZeroInit)
  8440. for (unsigned I = 0; I != N; ++I)
  8441. Value->getArrayInitializedElt(I) = Filler;
  8442. // Initialize the elements.
  8443. LValue ArrayElt = Subobject;
  8444. ArrayElt.addArray(Info, E, CAT);
  8445. for (unsigned I = 0; I != N; ++I)
  8446. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  8447. CAT->getElementType()) ||
  8448. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  8449. CAT->getElementType(), 1))
  8450. return false;
  8451. return true;
  8452. }
  8453. if (!Type->isRecordType())
  8454. return Error(E);
  8455. return RecordExprEvaluator(Info, Subobject, *Value)
  8456. .VisitCXXConstructExpr(E, Type);
  8457. }
  8458. //===----------------------------------------------------------------------===//
  8459. // Integer Evaluation
  8460. //
  8461. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  8462. // types and back in constant folding. Integer values are thus represented
  8463. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  8464. //===----------------------------------------------------------------------===//
  8465. namespace {
  8466. class IntExprEvaluator
  8467. : public ExprEvaluatorBase<IntExprEvaluator> {
  8468. APValue &Result;
  8469. public:
  8470. IntExprEvaluator(EvalInfo &info, APValue &result)
  8471. : ExprEvaluatorBaseTy(info), Result(result) {}
  8472. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  8473. assert(E->getType()->isIntegralOrEnumerationType() &&
  8474. "Invalid evaluation result.");
  8475. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  8476. "Invalid evaluation result.");
  8477. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8478. "Invalid evaluation result.");
  8479. Result = APValue(SI);
  8480. return true;
  8481. }
  8482. bool Success(const llvm::APSInt &SI, const Expr *E) {
  8483. return Success(SI, E, Result);
  8484. }
  8485. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  8486. assert(E->getType()->isIntegralOrEnumerationType() &&
  8487. "Invalid evaluation result.");
  8488. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8489. "Invalid evaluation result.");
  8490. Result = APValue(APSInt(I));
  8491. Result.getInt().setIsUnsigned(
  8492. E->getType()->isUnsignedIntegerOrEnumerationType());
  8493. return true;
  8494. }
  8495. bool Success(const llvm::APInt &I, const Expr *E) {
  8496. return Success(I, E, Result);
  8497. }
  8498. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8499. assert(E->getType()->isIntegralOrEnumerationType() &&
  8500. "Invalid evaluation result.");
  8501. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  8502. return true;
  8503. }
  8504. bool Success(uint64_t Value, const Expr *E) {
  8505. return Success(Value, E, Result);
  8506. }
  8507. bool Success(CharUnits Size, const Expr *E) {
  8508. return Success(Size.getQuantity(), E);
  8509. }
  8510. bool Success(const APValue &V, const Expr *E) {
  8511. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  8512. Result = V;
  8513. return true;
  8514. }
  8515. return Success(V.getInt(), E);
  8516. }
  8517. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  8518. //===--------------------------------------------------------------------===//
  8519. // Visitor Methods
  8520. //===--------------------------------------------------------------------===//
  8521. bool VisitConstantExpr(const ConstantExpr *E);
  8522. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  8523. return Success(E->getValue(), E);
  8524. }
  8525. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  8526. return Success(E->getValue(), E);
  8527. }
  8528. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  8529. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  8530. if (CheckReferencedDecl(E, E->getDecl()))
  8531. return true;
  8532. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  8533. }
  8534. bool VisitMemberExpr(const MemberExpr *E) {
  8535. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  8536. VisitIgnoredBaseExpression(E->getBase());
  8537. return true;
  8538. }
  8539. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  8540. }
  8541. bool VisitCallExpr(const CallExpr *E);
  8542. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  8543. bool VisitBinaryOperator(const BinaryOperator *E);
  8544. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  8545. bool VisitUnaryOperator(const UnaryOperator *E);
  8546. bool VisitCastExpr(const CastExpr* E);
  8547. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  8548. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  8549. return Success(E->getValue(), E);
  8550. }
  8551. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  8552. return Success(E->getValue(), E);
  8553. }
  8554. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  8555. if (Info.ArrayInitIndex == uint64_t(-1)) {
  8556. // We were asked to evaluate this subexpression independent of the
  8557. // enclosing ArrayInitLoopExpr. We can't do that.
  8558. Info.FFDiag(E);
  8559. return false;
  8560. }
  8561. return Success(Info.ArrayInitIndex, E);
  8562. }
  8563. // Note, GNU defines __null as an integer, not a pointer.
  8564. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  8565. return ZeroInitialization(E);
  8566. }
  8567. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  8568. return Success(E->getValue(), E);
  8569. }
  8570. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  8571. return Success(E->getValue(), E);
  8572. }
  8573. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  8574. return Success(E->getValue(), E);
  8575. }
  8576. bool VisitUnaryReal(const UnaryOperator *E);
  8577. bool VisitUnaryImag(const UnaryOperator *E);
  8578. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  8579. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  8580. bool VisitSourceLocExpr(const SourceLocExpr *E);
  8581. // FIXME: Missing: array subscript of vector, member of vector
  8582. };
  8583. class FixedPointExprEvaluator
  8584. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  8585. APValue &Result;
  8586. public:
  8587. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  8588. : ExprEvaluatorBaseTy(info), Result(result) {}
  8589. bool Success(const llvm::APInt &I, const Expr *E) {
  8590. return Success(
  8591. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8592. }
  8593. bool Success(uint64_t Value, const Expr *E) {
  8594. return Success(
  8595. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8596. }
  8597. bool Success(const APValue &V, const Expr *E) {
  8598. return Success(V.getFixedPoint(), E);
  8599. }
  8600. bool Success(const APFixedPoint &V, const Expr *E) {
  8601. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  8602. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8603. "Invalid evaluation result.");
  8604. Result = APValue(V);
  8605. return true;
  8606. }
  8607. //===--------------------------------------------------------------------===//
  8608. // Visitor Methods
  8609. //===--------------------------------------------------------------------===//
  8610. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  8611. return Success(E->getValue(), E);
  8612. }
  8613. bool VisitCastExpr(const CastExpr *E);
  8614. bool VisitUnaryOperator(const UnaryOperator *E);
  8615. bool VisitBinaryOperator(const BinaryOperator *E);
  8616. };
  8617. } // end anonymous namespace
  8618. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  8619. /// produce either the integer value or a pointer.
  8620. ///
  8621. /// GCC has a heinous extension which folds casts between pointer types and
  8622. /// pointer-sized integral types. We support this by allowing the evaluation of
  8623. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  8624. /// Some simple arithmetic on such values is supported (they are treated much
  8625. /// like char*).
  8626. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  8627. EvalInfo &Info) {
  8628. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  8629. return IntExprEvaluator(Info, Result).Visit(E);
  8630. }
  8631. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  8632. APValue Val;
  8633. if (!EvaluateIntegerOrLValue(E, Val, Info))
  8634. return false;
  8635. if (!Val.isInt()) {
  8636. // FIXME: It would be better to produce the diagnostic for casting
  8637. // a pointer to an integer.
  8638. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8639. return false;
  8640. }
  8641. Result = Val.getInt();
  8642. return true;
  8643. }
  8644. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  8645. APValue Evaluated = E->EvaluateInContext(
  8646. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  8647. return Success(Evaluated, E);
  8648. }
  8649. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  8650. EvalInfo &Info) {
  8651. if (E->getType()->isFixedPointType()) {
  8652. APValue Val;
  8653. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  8654. return false;
  8655. if (!Val.isFixedPoint())
  8656. return false;
  8657. Result = Val.getFixedPoint();
  8658. return true;
  8659. }
  8660. return false;
  8661. }
  8662. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  8663. EvalInfo &Info) {
  8664. if (E->getType()->isIntegerType()) {
  8665. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  8666. APSInt Val;
  8667. if (!EvaluateInteger(E, Val, Info))
  8668. return false;
  8669. Result = APFixedPoint(Val, FXSema);
  8670. return true;
  8671. } else if (E->getType()->isFixedPointType()) {
  8672. return EvaluateFixedPoint(E, Result, Info);
  8673. }
  8674. return false;
  8675. }
  8676. /// Check whether the given declaration can be directly converted to an integral
  8677. /// rvalue. If not, no diagnostic is produced; there are other things we can
  8678. /// try.
  8679. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  8680. // Enums are integer constant exprs.
  8681. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  8682. // Check for signedness/width mismatches between E type and ECD value.
  8683. bool SameSign = (ECD->getInitVal().isSigned()
  8684. == E->getType()->isSignedIntegerOrEnumerationType());
  8685. bool SameWidth = (ECD->getInitVal().getBitWidth()
  8686. == Info.Ctx.getIntWidth(E->getType()));
  8687. if (SameSign && SameWidth)
  8688. return Success(ECD->getInitVal(), E);
  8689. else {
  8690. // Get rid of mismatch (otherwise Success assertions will fail)
  8691. // by computing a new value matching the type of E.
  8692. llvm::APSInt Val = ECD->getInitVal();
  8693. if (!SameSign)
  8694. Val.setIsSigned(!ECD->getInitVal().isSigned());
  8695. if (!SameWidth)
  8696. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  8697. return Success(Val, E);
  8698. }
  8699. }
  8700. return false;
  8701. }
  8702. /// Values returned by __builtin_classify_type, chosen to match the values
  8703. /// produced by GCC's builtin.
  8704. enum class GCCTypeClass {
  8705. None = -1,
  8706. Void = 0,
  8707. Integer = 1,
  8708. // GCC reserves 2 for character types, but instead classifies them as
  8709. // integers.
  8710. Enum = 3,
  8711. Bool = 4,
  8712. Pointer = 5,
  8713. // GCC reserves 6 for references, but appears to never use it (because
  8714. // expressions never have reference type, presumably).
  8715. PointerToDataMember = 7,
  8716. RealFloat = 8,
  8717. Complex = 9,
  8718. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  8719. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8720. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  8721. // uses 12 for that purpose, same as for a class or struct. Maybe it
  8722. // internally implements a pointer to member as a struct? Who knows.
  8723. PointerToMemberFunction = 12, // Not a bug, see above.
  8724. ClassOrStruct = 12,
  8725. Union = 13,
  8726. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  8727. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8728. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  8729. // literals.
  8730. };
  8731. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8732. /// as GCC.
  8733. static GCCTypeClass
  8734. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  8735. assert(!T->isDependentType() && "unexpected dependent type");
  8736. QualType CanTy = T.getCanonicalType();
  8737. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  8738. switch (CanTy->getTypeClass()) {
  8739. #define TYPE(ID, BASE)
  8740. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8741. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  8742. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8743. #include "clang/AST/TypeNodes.inc"
  8744. case Type::Auto:
  8745. case Type::DeducedTemplateSpecialization:
  8746. llvm_unreachable("unexpected non-canonical or dependent type");
  8747. case Type::Builtin:
  8748. switch (BT->getKind()) {
  8749. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  8750. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  8751. case BuiltinType::ID: return GCCTypeClass::Integer;
  8752. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  8753. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  8754. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  8755. case BuiltinType::ID: break;
  8756. #include "clang/AST/BuiltinTypes.def"
  8757. case BuiltinType::Void:
  8758. return GCCTypeClass::Void;
  8759. case BuiltinType::Bool:
  8760. return GCCTypeClass::Bool;
  8761. case BuiltinType::Char_U:
  8762. case BuiltinType::UChar:
  8763. case BuiltinType::WChar_U:
  8764. case BuiltinType::Char8:
  8765. case BuiltinType::Char16:
  8766. case BuiltinType::Char32:
  8767. case BuiltinType::UShort:
  8768. case BuiltinType::UInt:
  8769. case BuiltinType::ULong:
  8770. case BuiltinType::ULongLong:
  8771. case BuiltinType::UInt128:
  8772. return GCCTypeClass::Integer;
  8773. case BuiltinType::UShortAccum:
  8774. case BuiltinType::UAccum:
  8775. case BuiltinType::ULongAccum:
  8776. case BuiltinType::UShortFract:
  8777. case BuiltinType::UFract:
  8778. case BuiltinType::ULongFract:
  8779. case BuiltinType::SatUShortAccum:
  8780. case BuiltinType::SatUAccum:
  8781. case BuiltinType::SatULongAccum:
  8782. case BuiltinType::SatUShortFract:
  8783. case BuiltinType::SatUFract:
  8784. case BuiltinType::SatULongFract:
  8785. return GCCTypeClass::None;
  8786. case BuiltinType::NullPtr:
  8787. case BuiltinType::ObjCId:
  8788. case BuiltinType::ObjCClass:
  8789. case BuiltinType::ObjCSel:
  8790. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  8791. case BuiltinType::Id:
  8792. #include "clang/Basic/OpenCLImageTypes.def"
  8793. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  8794. case BuiltinType::Id:
  8795. #include "clang/Basic/OpenCLExtensionTypes.def"
  8796. case BuiltinType::OCLSampler:
  8797. case BuiltinType::OCLEvent:
  8798. case BuiltinType::OCLClkEvent:
  8799. case BuiltinType::OCLQueue:
  8800. case BuiltinType::OCLReserveID:
  8801. #define SVE_TYPE(Name, Id, SingletonId) \
  8802. case BuiltinType::Id:
  8803. #include "clang/Basic/AArch64SVEACLETypes.def"
  8804. return GCCTypeClass::None;
  8805. case BuiltinType::Dependent:
  8806. llvm_unreachable("unexpected dependent type");
  8807. };
  8808. llvm_unreachable("unexpected placeholder type");
  8809. case Type::Enum:
  8810. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  8811. case Type::Pointer:
  8812. case Type::ConstantArray:
  8813. case Type::VariableArray:
  8814. case Type::IncompleteArray:
  8815. case Type::FunctionNoProto:
  8816. case Type::FunctionProto:
  8817. return GCCTypeClass::Pointer;
  8818. case Type::MemberPointer:
  8819. return CanTy->isMemberDataPointerType()
  8820. ? GCCTypeClass::PointerToDataMember
  8821. : GCCTypeClass::PointerToMemberFunction;
  8822. case Type::Complex:
  8823. return GCCTypeClass::Complex;
  8824. case Type::Record:
  8825. return CanTy->isUnionType() ? GCCTypeClass::Union
  8826. : GCCTypeClass::ClassOrStruct;
  8827. case Type::Atomic:
  8828. // GCC classifies _Atomic T the same as T.
  8829. return EvaluateBuiltinClassifyType(
  8830. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  8831. case Type::BlockPointer:
  8832. case Type::Vector:
  8833. case Type::ExtVector:
  8834. case Type::ObjCObject:
  8835. case Type::ObjCInterface:
  8836. case Type::ObjCObjectPointer:
  8837. case Type::Pipe:
  8838. // GCC classifies vectors as None. We follow its lead and classify all
  8839. // other types that don't fit into the regular classification the same way.
  8840. return GCCTypeClass::None;
  8841. case Type::LValueReference:
  8842. case Type::RValueReference:
  8843. llvm_unreachable("invalid type for expression");
  8844. }
  8845. llvm_unreachable("unexpected type class");
  8846. }
  8847. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8848. /// as GCC.
  8849. static GCCTypeClass
  8850. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  8851. // If no argument was supplied, default to None. This isn't
  8852. // ideal, however it is what gcc does.
  8853. if (E->getNumArgs() == 0)
  8854. return GCCTypeClass::None;
  8855. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  8856. // being an ICE, but still folds it to a constant using the type of the first
  8857. // argument.
  8858. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  8859. }
  8860. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  8861. /// __builtin_constant_p when applied to the given pointer.
  8862. ///
  8863. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  8864. /// or it points to the first character of a string literal.
  8865. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  8866. APValue::LValueBase Base = LV.getLValueBase();
  8867. if (Base.isNull()) {
  8868. // A null base is acceptable.
  8869. return true;
  8870. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  8871. if (!isa<StringLiteral>(E))
  8872. return false;
  8873. return LV.getLValueOffset().isZero();
  8874. } else if (Base.is<TypeInfoLValue>()) {
  8875. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  8876. // evaluate to true.
  8877. return true;
  8878. } else {
  8879. // Any other base is not constant enough for GCC.
  8880. return false;
  8881. }
  8882. }
  8883. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  8884. /// GCC as we can manage.
  8885. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  8886. // This evaluation is not permitted to have side-effects, so evaluate it in
  8887. // a speculative evaluation context.
  8888. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8889. // Constant-folding is always enabled for the operand of __builtin_constant_p
  8890. // (even when the enclosing evaluation context otherwise requires a strict
  8891. // language-specific constant expression).
  8892. FoldConstant Fold(Info, true);
  8893. QualType ArgType = Arg->getType();
  8894. // __builtin_constant_p always has one operand. The rules which gcc follows
  8895. // are not precisely documented, but are as follows:
  8896. //
  8897. // - If the operand is of integral, floating, complex or enumeration type,
  8898. // and can be folded to a known value of that type, it returns 1.
  8899. // - If the operand can be folded to a pointer to the first character
  8900. // of a string literal (or such a pointer cast to an integral type)
  8901. // or to a null pointer or an integer cast to a pointer, it returns 1.
  8902. //
  8903. // Otherwise, it returns 0.
  8904. //
  8905. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  8906. // its support for this did not work prior to GCC 9 and is not yet well
  8907. // understood.
  8908. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  8909. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  8910. ArgType->isNullPtrType()) {
  8911. APValue V;
  8912. if (!::EvaluateAsRValue(Info, Arg, V)) {
  8913. Fold.keepDiagnostics();
  8914. return false;
  8915. }
  8916. // For a pointer (possibly cast to integer), there are special rules.
  8917. if (V.getKind() == APValue::LValue)
  8918. return EvaluateBuiltinConstantPForLValue(V);
  8919. // Otherwise, any constant value is good enough.
  8920. return V.hasValue();
  8921. }
  8922. // Anything else isn't considered to be sufficiently constant.
  8923. return false;
  8924. }
  8925. /// Retrieves the "underlying object type" of the given expression,
  8926. /// as used by __builtin_object_size.
  8927. static QualType getObjectType(APValue::LValueBase B) {
  8928. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  8929. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  8930. return VD->getType();
  8931. } else if (const Expr *E = B.get<const Expr*>()) {
  8932. if (isa<CompoundLiteralExpr>(E))
  8933. return E->getType();
  8934. } else if (B.is<TypeInfoLValue>()) {
  8935. return B.getTypeInfoType();
  8936. } else if (B.is<DynamicAllocLValue>()) {
  8937. return B.getDynamicAllocType();
  8938. }
  8939. return QualType();
  8940. }
  8941. /// A more selective version of E->IgnoreParenCasts for
  8942. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  8943. /// to change the type of E.
  8944. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  8945. ///
  8946. /// Always returns an RValue with a pointer representation.
  8947. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  8948. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  8949. auto *NoParens = E->IgnoreParens();
  8950. auto *Cast = dyn_cast<CastExpr>(NoParens);
  8951. if (Cast == nullptr)
  8952. return NoParens;
  8953. // We only conservatively allow a few kinds of casts, because this code is
  8954. // inherently a simple solution that seeks to support the common case.
  8955. auto CastKind = Cast->getCastKind();
  8956. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  8957. CastKind != CK_AddressSpaceConversion)
  8958. return NoParens;
  8959. auto *SubExpr = Cast->getSubExpr();
  8960. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  8961. return NoParens;
  8962. return ignorePointerCastsAndParens(SubExpr);
  8963. }
  8964. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  8965. /// record layout. e.g.
  8966. /// struct { struct { int a, b; } fst, snd; } obj;
  8967. /// obj.fst // no
  8968. /// obj.snd // yes
  8969. /// obj.fst.a // no
  8970. /// obj.fst.b // no
  8971. /// obj.snd.a // no
  8972. /// obj.snd.b // yes
  8973. ///
  8974. /// Please note: this function is specialized for how __builtin_object_size
  8975. /// views "objects".
  8976. ///
  8977. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  8978. /// correct result, it will always return true.
  8979. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  8980. assert(!LVal.Designator.Invalid);
  8981. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  8982. const RecordDecl *Parent = FD->getParent();
  8983. Invalid = Parent->isInvalidDecl();
  8984. if (Invalid || Parent->isUnion())
  8985. return true;
  8986. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  8987. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  8988. };
  8989. auto &Base = LVal.getLValueBase();
  8990. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  8991. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  8992. bool Invalid;
  8993. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  8994. return Invalid;
  8995. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  8996. for (auto *FD : IFD->chain()) {
  8997. bool Invalid;
  8998. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  8999. return Invalid;
  9000. }
  9001. }
  9002. }
  9003. unsigned I = 0;
  9004. QualType BaseType = getType(Base);
  9005. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  9006. // If we don't know the array bound, conservatively assume we're looking at
  9007. // the final array element.
  9008. ++I;
  9009. if (BaseType->isIncompleteArrayType())
  9010. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  9011. else
  9012. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  9013. }
  9014. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  9015. const auto &Entry = LVal.Designator.Entries[I];
  9016. if (BaseType->isArrayType()) {
  9017. // Because __builtin_object_size treats arrays as objects, we can ignore
  9018. // the index iff this is the last array in the Designator.
  9019. if (I + 1 == E)
  9020. return true;
  9021. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  9022. uint64_t Index = Entry.getAsArrayIndex();
  9023. if (Index + 1 != CAT->getSize())
  9024. return false;
  9025. BaseType = CAT->getElementType();
  9026. } else if (BaseType->isAnyComplexType()) {
  9027. const auto *CT = BaseType->castAs<ComplexType>();
  9028. uint64_t Index = Entry.getAsArrayIndex();
  9029. if (Index != 1)
  9030. return false;
  9031. BaseType = CT->getElementType();
  9032. } else if (auto *FD = getAsField(Entry)) {
  9033. bool Invalid;
  9034. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  9035. return Invalid;
  9036. BaseType = FD->getType();
  9037. } else {
  9038. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  9039. return false;
  9040. }
  9041. }
  9042. return true;
  9043. }
  9044. /// Tests to see if the LValue has a user-specified designator (that isn't
  9045. /// necessarily valid). Note that this always returns 'true' if the LValue has
  9046. /// an unsized array as its first designator entry, because there's currently no
  9047. /// way to tell if the user typed *foo or foo[0].
  9048. static bool refersToCompleteObject(const LValue &LVal) {
  9049. if (LVal.Designator.Invalid)
  9050. return false;
  9051. if (!LVal.Designator.Entries.empty())
  9052. return LVal.Designator.isMostDerivedAnUnsizedArray();
  9053. if (!LVal.InvalidBase)
  9054. return true;
  9055. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  9056. // the LValueBase.
  9057. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  9058. return !E || !isa<MemberExpr>(E);
  9059. }
  9060. /// Attempts to detect a user writing into a piece of memory that's impossible
  9061. /// to figure out the size of by just using types.
  9062. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  9063. const SubobjectDesignator &Designator = LVal.Designator;
  9064. // Notes:
  9065. // - Users can only write off of the end when we have an invalid base. Invalid
  9066. // bases imply we don't know where the memory came from.
  9067. // - We used to be a bit more aggressive here; we'd only be conservative if
  9068. // the array at the end was flexible, or if it had 0 or 1 elements. This
  9069. // broke some common standard library extensions (PR30346), but was
  9070. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  9071. // with some sort of whitelist. OTOH, it seems that GCC is always
  9072. // conservative with the last element in structs (if it's an array), so our
  9073. // current behavior is more compatible than a whitelisting approach would
  9074. // be.
  9075. return LVal.InvalidBase &&
  9076. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  9077. Designator.MostDerivedIsArrayElement &&
  9078. isDesignatorAtObjectEnd(Ctx, LVal);
  9079. }
  9080. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  9081. /// Fails if the conversion would cause loss of precision.
  9082. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  9083. CharUnits &Result) {
  9084. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  9085. if (Int.ugt(CharUnitsMax))
  9086. return false;
  9087. Result = CharUnits::fromQuantity(Int.getZExtValue());
  9088. return true;
  9089. }
  9090. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  9091. /// determine how many bytes exist from the beginning of the object to either
  9092. /// the end of the current subobject, or the end of the object itself, depending
  9093. /// on what the LValue looks like + the value of Type.
  9094. ///
  9095. /// If this returns false, the value of Result is undefined.
  9096. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  9097. unsigned Type, const LValue &LVal,
  9098. CharUnits &EndOffset) {
  9099. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  9100. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  9101. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  9102. return false;
  9103. return HandleSizeof(Info, ExprLoc, Ty, Result);
  9104. };
  9105. // We want to evaluate the size of the entire object. This is a valid fallback
  9106. // for when Type=1 and the designator is invalid, because we're asked for an
  9107. // upper-bound.
  9108. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  9109. // Type=3 wants a lower bound, so we can't fall back to this.
  9110. if (Type == 3 && !DetermineForCompleteObject)
  9111. return false;
  9112. llvm::APInt APEndOffset;
  9113. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  9114. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  9115. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  9116. if (LVal.InvalidBase)
  9117. return false;
  9118. QualType BaseTy = getObjectType(LVal.getLValueBase());
  9119. return CheckedHandleSizeof(BaseTy, EndOffset);
  9120. }
  9121. // We want to evaluate the size of a subobject.
  9122. const SubobjectDesignator &Designator = LVal.Designator;
  9123. // The following is a moderately common idiom in C:
  9124. //
  9125. // struct Foo { int a; char c[1]; };
  9126. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  9127. // strcpy(&F->c[0], Bar);
  9128. //
  9129. // In order to not break too much legacy code, we need to support it.
  9130. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  9131. // If we can resolve this to an alloc_size call, we can hand that back,
  9132. // because we know for certain how many bytes there are to write to.
  9133. llvm::APInt APEndOffset;
  9134. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  9135. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  9136. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  9137. // If we cannot determine the size of the initial allocation, then we can't
  9138. // given an accurate upper-bound. However, we are still able to give
  9139. // conservative lower-bounds for Type=3.
  9140. if (Type == 1)
  9141. return false;
  9142. }
  9143. CharUnits BytesPerElem;
  9144. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  9145. return false;
  9146. // According to the GCC documentation, we want the size of the subobject
  9147. // denoted by the pointer. But that's not quite right -- what we actually
  9148. // want is the size of the immediately-enclosing array, if there is one.
  9149. int64_t ElemsRemaining;
  9150. if (Designator.MostDerivedIsArrayElement &&
  9151. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  9152. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  9153. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  9154. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  9155. } else {
  9156. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  9157. }
  9158. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  9159. return true;
  9160. }
  9161. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  9162. /// returns true and stores the result in @p Size.
  9163. ///
  9164. /// If @p WasError is non-null, this will report whether the failure to evaluate
  9165. /// is to be treated as an Error in IntExprEvaluator.
  9166. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  9167. EvalInfo &Info, uint64_t &Size) {
  9168. // Determine the denoted object.
  9169. LValue LVal;
  9170. {
  9171. // The operand of __builtin_object_size is never evaluated for side-effects.
  9172. // If there are any, but we can determine the pointed-to object anyway, then
  9173. // ignore the side-effects.
  9174. SpeculativeEvaluationRAII SpeculativeEval(Info);
  9175. IgnoreSideEffectsRAII Fold(Info);
  9176. if (E->isGLValue()) {
  9177. // It's possible for us to be given GLValues if we're called via
  9178. // Expr::tryEvaluateObjectSize.
  9179. APValue RVal;
  9180. if (!EvaluateAsRValue(Info, E, RVal))
  9181. return false;
  9182. LVal.setFrom(Info.Ctx, RVal);
  9183. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  9184. /*InvalidBaseOK=*/true))
  9185. return false;
  9186. }
  9187. // If we point to before the start of the object, there are no accessible
  9188. // bytes.
  9189. if (LVal.getLValueOffset().isNegative()) {
  9190. Size = 0;
  9191. return true;
  9192. }
  9193. CharUnits EndOffset;
  9194. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  9195. return false;
  9196. // If we've fallen outside of the end offset, just pretend there's nothing to
  9197. // write to/read from.
  9198. if (EndOffset <= LVal.getLValueOffset())
  9199. Size = 0;
  9200. else
  9201. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  9202. return true;
  9203. }
  9204. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  9205. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  9206. if (E->getResultAPValueKind() != APValue::None)
  9207. return Success(E->getAPValueResult(), E);
  9208. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  9209. }
  9210. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  9211. if (unsigned BuiltinOp = E->getBuiltinCallee())
  9212. return VisitBuiltinCallExpr(E, BuiltinOp);
  9213. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9214. }
  9215. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  9216. unsigned BuiltinOp) {
  9217. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  9218. default:
  9219. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9220. case Builtin::BI__builtin_dynamic_object_size:
  9221. case Builtin::BI__builtin_object_size: {
  9222. // The type was checked when we built the expression.
  9223. unsigned Type =
  9224. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  9225. assert(Type <= 3 && "unexpected type");
  9226. uint64_t Size;
  9227. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  9228. return Success(Size, E);
  9229. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  9230. return Success((Type & 2) ? 0 : -1, E);
  9231. // Expression had no side effects, but we couldn't statically determine the
  9232. // size of the referenced object.
  9233. switch (Info.EvalMode) {
  9234. case EvalInfo::EM_ConstantExpression:
  9235. case EvalInfo::EM_ConstantFold:
  9236. case EvalInfo::EM_IgnoreSideEffects:
  9237. // Leave it to IR generation.
  9238. return Error(E);
  9239. case EvalInfo::EM_ConstantExpressionUnevaluated:
  9240. // Reduce it to a constant now.
  9241. return Success((Type & 2) ? 0 : -1, E);
  9242. }
  9243. llvm_unreachable("unexpected EvalMode");
  9244. }
  9245. case Builtin::BI__builtin_os_log_format_buffer_size: {
  9246. analyze_os_log::OSLogBufferLayout Layout;
  9247. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  9248. return Success(Layout.size().getQuantity(), E);
  9249. }
  9250. case Builtin::BI__builtin_bswap16:
  9251. case Builtin::BI__builtin_bswap32:
  9252. case Builtin::BI__builtin_bswap64: {
  9253. APSInt Val;
  9254. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9255. return false;
  9256. return Success(Val.byteSwap(), E);
  9257. }
  9258. case Builtin::BI__builtin_classify_type:
  9259. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  9260. case Builtin::BI__builtin_clrsb:
  9261. case Builtin::BI__builtin_clrsbl:
  9262. case Builtin::BI__builtin_clrsbll: {
  9263. APSInt Val;
  9264. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9265. return false;
  9266. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  9267. }
  9268. case Builtin::BI__builtin_clz:
  9269. case Builtin::BI__builtin_clzl:
  9270. case Builtin::BI__builtin_clzll:
  9271. case Builtin::BI__builtin_clzs: {
  9272. APSInt Val;
  9273. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9274. return false;
  9275. if (!Val)
  9276. return Error(E);
  9277. return Success(Val.countLeadingZeros(), E);
  9278. }
  9279. case Builtin::BI__builtin_constant_p: {
  9280. const Expr *Arg = E->getArg(0);
  9281. if (EvaluateBuiltinConstantP(Info, Arg))
  9282. return Success(true, E);
  9283. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  9284. // Outside a constant context, eagerly evaluate to false in the presence
  9285. // of side-effects in order to avoid -Wunsequenced false-positives in
  9286. // a branch on __builtin_constant_p(expr).
  9287. return Success(false, E);
  9288. }
  9289. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9290. return false;
  9291. }
  9292. case Builtin::BI__builtin_is_constant_evaluated:
  9293. return Success(Info.InConstantContext, E);
  9294. case Builtin::BI__builtin_ctz:
  9295. case Builtin::BI__builtin_ctzl:
  9296. case Builtin::BI__builtin_ctzll:
  9297. case Builtin::BI__builtin_ctzs: {
  9298. APSInt Val;
  9299. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9300. return false;
  9301. if (!Val)
  9302. return Error(E);
  9303. return Success(Val.countTrailingZeros(), E);
  9304. }
  9305. case Builtin::BI__builtin_eh_return_data_regno: {
  9306. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  9307. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  9308. return Success(Operand, E);
  9309. }
  9310. case Builtin::BI__builtin_expect:
  9311. return Visit(E->getArg(0));
  9312. case Builtin::BI__builtin_ffs:
  9313. case Builtin::BI__builtin_ffsl:
  9314. case Builtin::BI__builtin_ffsll: {
  9315. APSInt Val;
  9316. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9317. return false;
  9318. unsigned N = Val.countTrailingZeros();
  9319. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  9320. }
  9321. case Builtin::BI__builtin_fpclassify: {
  9322. APFloat Val(0.0);
  9323. if (!EvaluateFloat(E->getArg(5), Val, Info))
  9324. return false;
  9325. unsigned Arg;
  9326. switch (Val.getCategory()) {
  9327. case APFloat::fcNaN: Arg = 0; break;
  9328. case APFloat::fcInfinity: Arg = 1; break;
  9329. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  9330. case APFloat::fcZero: Arg = 4; break;
  9331. }
  9332. return Visit(E->getArg(Arg));
  9333. }
  9334. case Builtin::BI__builtin_isinf_sign: {
  9335. APFloat Val(0.0);
  9336. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9337. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  9338. }
  9339. case Builtin::BI__builtin_isinf: {
  9340. APFloat Val(0.0);
  9341. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9342. Success(Val.isInfinity() ? 1 : 0, E);
  9343. }
  9344. case Builtin::BI__builtin_isfinite: {
  9345. APFloat Val(0.0);
  9346. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9347. Success(Val.isFinite() ? 1 : 0, E);
  9348. }
  9349. case Builtin::BI__builtin_isnan: {
  9350. APFloat Val(0.0);
  9351. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9352. Success(Val.isNaN() ? 1 : 0, E);
  9353. }
  9354. case Builtin::BI__builtin_isnormal: {
  9355. APFloat Val(0.0);
  9356. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9357. Success(Val.isNormal() ? 1 : 0, E);
  9358. }
  9359. case Builtin::BI__builtin_parity:
  9360. case Builtin::BI__builtin_parityl:
  9361. case Builtin::BI__builtin_parityll: {
  9362. APSInt Val;
  9363. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9364. return false;
  9365. return Success(Val.countPopulation() % 2, E);
  9366. }
  9367. case Builtin::BI__builtin_popcount:
  9368. case Builtin::BI__builtin_popcountl:
  9369. case Builtin::BI__builtin_popcountll: {
  9370. APSInt Val;
  9371. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9372. return false;
  9373. return Success(Val.countPopulation(), E);
  9374. }
  9375. case Builtin::BIstrlen:
  9376. case Builtin::BIwcslen:
  9377. // A call to strlen is not a constant expression.
  9378. if (Info.getLangOpts().CPlusPlus11)
  9379. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9380. << /*isConstexpr*/0 << /*isConstructor*/0
  9381. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9382. else
  9383. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9384. LLVM_FALLTHROUGH;
  9385. case Builtin::BI__builtin_strlen:
  9386. case Builtin::BI__builtin_wcslen: {
  9387. // As an extension, we support __builtin_strlen() as a constant expression,
  9388. // and support folding strlen() to a constant.
  9389. LValue String;
  9390. if (!EvaluatePointer(E->getArg(0), String, Info))
  9391. return false;
  9392. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  9393. // Fast path: if it's a string literal, search the string value.
  9394. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  9395. String.getLValueBase().dyn_cast<const Expr *>())) {
  9396. // The string literal may have embedded null characters. Find the first
  9397. // one and truncate there.
  9398. StringRef Str = S->getBytes();
  9399. int64_t Off = String.Offset.getQuantity();
  9400. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  9401. S->getCharByteWidth() == 1 &&
  9402. // FIXME: Add fast-path for wchar_t too.
  9403. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  9404. Str = Str.substr(Off);
  9405. StringRef::size_type Pos = Str.find(0);
  9406. if (Pos != StringRef::npos)
  9407. Str = Str.substr(0, Pos);
  9408. return Success(Str.size(), E);
  9409. }
  9410. // Fall through to slow path to issue appropriate diagnostic.
  9411. }
  9412. // Slow path: scan the bytes of the string looking for the terminating 0.
  9413. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  9414. APValue Char;
  9415. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  9416. !Char.isInt())
  9417. return false;
  9418. if (!Char.getInt())
  9419. return Success(Strlen, E);
  9420. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  9421. return false;
  9422. }
  9423. }
  9424. case Builtin::BIstrcmp:
  9425. case Builtin::BIwcscmp:
  9426. case Builtin::BIstrncmp:
  9427. case Builtin::BIwcsncmp:
  9428. case Builtin::BImemcmp:
  9429. case Builtin::BIbcmp:
  9430. case Builtin::BIwmemcmp:
  9431. // A call to strlen is not a constant expression.
  9432. if (Info.getLangOpts().CPlusPlus11)
  9433. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9434. << /*isConstexpr*/0 << /*isConstructor*/0
  9435. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9436. else
  9437. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9438. LLVM_FALLTHROUGH;
  9439. case Builtin::BI__builtin_strcmp:
  9440. case Builtin::BI__builtin_wcscmp:
  9441. case Builtin::BI__builtin_strncmp:
  9442. case Builtin::BI__builtin_wcsncmp:
  9443. case Builtin::BI__builtin_memcmp:
  9444. case Builtin::BI__builtin_bcmp:
  9445. case Builtin::BI__builtin_wmemcmp: {
  9446. LValue String1, String2;
  9447. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  9448. !EvaluatePointer(E->getArg(1), String2, Info))
  9449. return false;
  9450. uint64_t MaxLength = uint64_t(-1);
  9451. if (BuiltinOp != Builtin::BIstrcmp &&
  9452. BuiltinOp != Builtin::BIwcscmp &&
  9453. BuiltinOp != Builtin::BI__builtin_strcmp &&
  9454. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  9455. APSInt N;
  9456. if (!EvaluateInteger(E->getArg(2), N, Info))
  9457. return false;
  9458. MaxLength = N.getExtValue();
  9459. }
  9460. // Empty substrings compare equal by definition.
  9461. if (MaxLength == 0u)
  9462. return Success(0, E);
  9463. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9464. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9465. String1.Designator.Invalid || String2.Designator.Invalid)
  9466. return false;
  9467. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  9468. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  9469. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  9470. BuiltinOp == Builtin::BIbcmp ||
  9471. BuiltinOp == Builtin::BI__builtin_memcmp ||
  9472. BuiltinOp == Builtin::BI__builtin_bcmp;
  9473. assert(IsRawByte ||
  9474. (Info.Ctx.hasSameUnqualifiedType(
  9475. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  9476. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  9477. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  9478. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  9479. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  9480. Char1.isInt() && Char2.isInt();
  9481. };
  9482. const auto &AdvanceElems = [&] {
  9483. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  9484. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  9485. };
  9486. if (IsRawByte) {
  9487. uint64_t BytesRemaining = MaxLength;
  9488. // Pointers to const void may point to objects of incomplete type.
  9489. if (CharTy1->isIncompleteType()) {
  9490. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  9491. return false;
  9492. }
  9493. if (CharTy2->isIncompleteType()) {
  9494. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  9495. return false;
  9496. }
  9497. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  9498. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  9499. // Give up on comparing between elements with disparate widths.
  9500. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  9501. return false;
  9502. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  9503. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  9504. "following loop considers at least one element");
  9505. while (true) {
  9506. APValue Char1, Char2;
  9507. if (!ReadCurElems(Char1, Char2))
  9508. return false;
  9509. // We have compatible in-memory widths, but a possible type and
  9510. // (for `bool`) internal representation mismatch.
  9511. // Assuming two's complement representation, including 0 for `false` and
  9512. // 1 for `true`, we can check an appropriate number of elements for
  9513. // equality even if they are not byte-sized.
  9514. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  9515. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  9516. if (Char1InMem.ne(Char2InMem)) {
  9517. // If the elements are byte-sized, then we can produce a three-way
  9518. // comparison result in a straightforward manner.
  9519. if (BytesPerElement == 1u) {
  9520. // memcmp always compares unsigned chars.
  9521. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  9522. }
  9523. // The result is byte-order sensitive, and we have multibyte elements.
  9524. // FIXME: We can compare the remaining bytes in the correct order.
  9525. return false;
  9526. }
  9527. if (!AdvanceElems())
  9528. return false;
  9529. if (BytesRemaining <= BytesPerElement)
  9530. break;
  9531. BytesRemaining -= BytesPerElement;
  9532. }
  9533. // Enough elements are equal to account for the memcmp limit.
  9534. return Success(0, E);
  9535. }
  9536. bool StopAtNull =
  9537. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  9538. BuiltinOp != Builtin::BIwmemcmp &&
  9539. BuiltinOp != Builtin::BI__builtin_memcmp &&
  9540. BuiltinOp != Builtin::BI__builtin_bcmp &&
  9541. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  9542. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  9543. BuiltinOp == Builtin::BIwcsncmp ||
  9544. BuiltinOp == Builtin::BIwmemcmp ||
  9545. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  9546. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  9547. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  9548. for (; MaxLength; --MaxLength) {
  9549. APValue Char1, Char2;
  9550. if (!ReadCurElems(Char1, Char2))
  9551. return false;
  9552. if (Char1.getInt() != Char2.getInt()) {
  9553. if (IsWide) // wmemcmp compares with wchar_t signedness.
  9554. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  9555. // memcmp always compares unsigned chars.
  9556. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  9557. }
  9558. if (StopAtNull && !Char1.getInt())
  9559. return Success(0, E);
  9560. assert(!(StopAtNull && !Char2.getInt()));
  9561. if (!AdvanceElems())
  9562. return false;
  9563. }
  9564. // We hit the strncmp / memcmp limit.
  9565. return Success(0, E);
  9566. }
  9567. case Builtin::BI__atomic_always_lock_free:
  9568. case Builtin::BI__atomic_is_lock_free:
  9569. case Builtin::BI__c11_atomic_is_lock_free: {
  9570. APSInt SizeVal;
  9571. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  9572. return false;
  9573. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  9574. // of two less than the maximum inline atomic width, we know it is
  9575. // lock-free. If the size isn't a power of two, or greater than the
  9576. // maximum alignment where we promote atomics, we know it is not lock-free
  9577. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  9578. // the answer can only be determined at runtime; for example, 16-byte
  9579. // atomics have lock-free implementations on some, but not all,
  9580. // x86-64 processors.
  9581. // Check power-of-two.
  9582. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  9583. if (Size.isPowerOfTwo()) {
  9584. // Check against inlining width.
  9585. unsigned InlineWidthBits =
  9586. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  9587. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  9588. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  9589. Size == CharUnits::One() ||
  9590. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  9591. Expr::NPC_NeverValueDependent))
  9592. // OK, we will inline appropriately-aligned operations of this size,
  9593. // and _Atomic(T) is appropriately-aligned.
  9594. return Success(1, E);
  9595. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  9596. castAs<PointerType>()->getPointeeType();
  9597. if (!PointeeType->isIncompleteType() &&
  9598. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  9599. // OK, we will inline operations on this object.
  9600. return Success(1, E);
  9601. }
  9602. }
  9603. }
  9604. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  9605. Success(0, E) : Error(E);
  9606. }
  9607. case Builtin::BIomp_is_initial_device:
  9608. // We can decide statically which value the runtime would return if called.
  9609. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  9610. case Builtin::BI__builtin_add_overflow:
  9611. case Builtin::BI__builtin_sub_overflow:
  9612. case Builtin::BI__builtin_mul_overflow:
  9613. case Builtin::BI__builtin_sadd_overflow:
  9614. case Builtin::BI__builtin_uadd_overflow:
  9615. case Builtin::BI__builtin_uaddl_overflow:
  9616. case Builtin::BI__builtin_uaddll_overflow:
  9617. case Builtin::BI__builtin_usub_overflow:
  9618. case Builtin::BI__builtin_usubl_overflow:
  9619. case Builtin::BI__builtin_usubll_overflow:
  9620. case Builtin::BI__builtin_umul_overflow:
  9621. case Builtin::BI__builtin_umull_overflow:
  9622. case Builtin::BI__builtin_umulll_overflow:
  9623. case Builtin::BI__builtin_saddl_overflow:
  9624. case Builtin::BI__builtin_saddll_overflow:
  9625. case Builtin::BI__builtin_ssub_overflow:
  9626. case Builtin::BI__builtin_ssubl_overflow:
  9627. case Builtin::BI__builtin_ssubll_overflow:
  9628. case Builtin::BI__builtin_smul_overflow:
  9629. case Builtin::BI__builtin_smull_overflow:
  9630. case Builtin::BI__builtin_smulll_overflow: {
  9631. LValue ResultLValue;
  9632. APSInt LHS, RHS;
  9633. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  9634. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  9635. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  9636. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  9637. return false;
  9638. APSInt Result;
  9639. bool DidOverflow = false;
  9640. // If the types don't have to match, enlarge all 3 to the largest of them.
  9641. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9642. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9643. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9644. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  9645. ResultType->isSignedIntegerOrEnumerationType();
  9646. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  9647. ResultType->isSignedIntegerOrEnumerationType();
  9648. uint64_t LHSSize = LHS.getBitWidth();
  9649. uint64_t RHSSize = RHS.getBitWidth();
  9650. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  9651. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  9652. // Add an additional bit if the signedness isn't uniformly agreed to. We
  9653. // could do this ONLY if there is a signed and an unsigned that both have
  9654. // MaxBits, but the code to check that is pretty nasty. The issue will be
  9655. // caught in the shrink-to-result later anyway.
  9656. if (IsSigned && !AllSigned)
  9657. ++MaxBits;
  9658. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  9659. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  9660. Result = APSInt(MaxBits, !IsSigned);
  9661. }
  9662. // Find largest int.
  9663. switch (BuiltinOp) {
  9664. default:
  9665. llvm_unreachable("Invalid value for BuiltinOp");
  9666. case Builtin::BI__builtin_add_overflow:
  9667. case Builtin::BI__builtin_sadd_overflow:
  9668. case Builtin::BI__builtin_saddl_overflow:
  9669. case Builtin::BI__builtin_saddll_overflow:
  9670. case Builtin::BI__builtin_uadd_overflow:
  9671. case Builtin::BI__builtin_uaddl_overflow:
  9672. case Builtin::BI__builtin_uaddll_overflow:
  9673. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  9674. : LHS.uadd_ov(RHS, DidOverflow);
  9675. break;
  9676. case Builtin::BI__builtin_sub_overflow:
  9677. case Builtin::BI__builtin_ssub_overflow:
  9678. case Builtin::BI__builtin_ssubl_overflow:
  9679. case Builtin::BI__builtin_ssubll_overflow:
  9680. case Builtin::BI__builtin_usub_overflow:
  9681. case Builtin::BI__builtin_usubl_overflow:
  9682. case Builtin::BI__builtin_usubll_overflow:
  9683. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  9684. : LHS.usub_ov(RHS, DidOverflow);
  9685. break;
  9686. case Builtin::BI__builtin_mul_overflow:
  9687. case Builtin::BI__builtin_smul_overflow:
  9688. case Builtin::BI__builtin_smull_overflow:
  9689. case Builtin::BI__builtin_smulll_overflow:
  9690. case Builtin::BI__builtin_umul_overflow:
  9691. case Builtin::BI__builtin_umull_overflow:
  9692. case Builtin::BI__builtin_umulll_overflow:
  9693. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  9694. : LHS.umul_ov(RHS, DidOverflow);
  9695. break;
  9696. }
  9697. // In the case where multiple sizes are allowed, truncate and see if
  9698. // the values are the same.
  9699. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9700. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9701. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9702. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  9703. // since it will give us the behavior of a TruncOrSelf in the case where
  9704. // its parameter <= its size. We previously set Result to be at least the
  9705. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  9706. // will work exactly like TruncOrSelf.
  9707. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  9708. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  9709. if (!APSInt::isSameValue(Temp, Result))
  9710. DidOverflow = true;
  9711. Result = Temp;
  9712. }
  9713. APValue APV{Result};
  9714. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  9715. return false;
  9716. return Success(DidOverflow, E);
  9717. }
  9718. }
  9719. }
  9720. /// Determine whether this is a pointer past the end of the complete
  9721. /// object referred to by the lvalue.
  9722. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  9723. const LValue &LV) {
  9724. // A null pointer can be viewed as being "past the end" but we don't
  9725. // choose to look at it that way here.
  9726. if (!LV.getLValueBase())
  9727. return false;
  9728. // If the designator is valid and refers to a subobject, we're not pointing
  9729. // past the end.
  9730. if (!LV.getLValueDesignator().Invalid &&
  9731. !LV.getLValueDesignator().isOnePastTheEnd())
  9732. return false;
  9733. // A pointer to an incomplete type might be past-the-end if the type's size is
  9734. // zero. We cannot tell because the type is incomplete.
  9735. QualType Ty = getType(LV.getLValueBase());
  9736. if (Ty->isIncompleteType())
  9737. return true;
  9738. // We're a past-the-end pointer if we point to the byte after the object,
  9739. // no matter what our type or path is.
  9740. auto Size = Ctx.getTypeSizeInChars(Ty);
  9741. return LV.getLValueOffset() == Size;
  9742. }
  9743. namespace {
  9744. /// Data recursive integer evaluator of certain binary operators.
  9745. ///
  9746. /// We use a data recursive algorithm for binary operators so that we are able
  9747. /// to handle extreme cases of chained binary operators without causing stack
  9748. /// overflow.
  9749. class DataRecursiveIntBinOpEvaluator {
  9750. struct EvalResult {
  9751. APValue Val;
  9752. bool Failed;
  9753. EvalResult() : Failed(false) { }
  9754. void swap(EvalResult &RHS) {
  9755. Val.swap(RHS.Val);
  9756. Failed = RHS.Failed;
  9757. RHS.Failed = false;
  9758. }
  9759. };
  9760. struct Job {
  9761. const Expr *E;
  9762. EvalResult LHSResult; // meaningful only for binary operator expression.
  9763. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  9764. Job() = default;
  9765. Job(Job &&) = default;
  9766. void startSpeculativeEval(EvalInfo &Info) {
  9767. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  9768. }
  9769. private:
  9770. SpeculativeEvaluationRAII SpecEvalRAII;
  9771. };
  9772. SmallVector<Job, 16> Queue;
  9773. IntExprEvaluator &IntEval;
  9774. EvalInfo &Info;
  9775. APValue &FinalResult;
  9776. public:
  9777. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  9778. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  9779. /// True if \param E is a binary operator that we are going to handle
  9780. /// data recursively.
  9781. /// We handle binary operators that are comma, logical, or that have operands
  9782. /// with integral or enumeration type.
  9783. static bool shouldEnqueue(const BinaryOperator *E) {
  9784. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  9785. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  9786. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9787. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9788. }
  9789. bool Traverse(const BinaryOperator *E) {
  9790. enqueue(E);
  9791. EvalResult PrevResult;
  9792. while (!Queue.empty())
  9793. process(PrevResult);
  9794. if (PrevResult.Failed) return false;
  9795. FinalResult.swap(PrevResult.Val);
  9796. return true;
  9797. }
  9798. private:
  9799. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9800. return IntEval.Success(Value, E, Result);
  9801. }
  9802. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  9803. return IntEval.Success(Value, E, Result);
  9804. }
  9805. bool Error(const Expr *E) {
  9806. return IntEval.Error(E);
  9807. }
  9808. bool Error(const Expr *E, diag::kind D) {
  9809. return IntEval.Error(E, D);
  9810. }
  9811. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  9812. return Info.CCEDiag(E, D);
  9813. }
  9814. // Returns true if visiting the RHS is necessary, false otherwise.
  9815. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9816. bool &SuppressRHSDiags);
  9817. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9818. const BinaryOperator *E, APValue &Result);
  9819. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  9820. Result.Failed = !Evaluate(Result.Val, Info, E);
  9821. if (Result.Failed)
  9822. Result.Val = APValue();
  9823. }
  9824. void process(EvalResult &Result);
  9825. void enqueue(const Expr *E) {
  9826. E = E->IgnoreParens();
  9827. Queue.resize(Queue.size()+1);
  9828. Queue.back().E = E;
  9829. Queue.back().Kind = Job::AnyExprKind;
  9830. }
  9831. };
  9832. }
  9833. bool DataRecursiveIntBinOpEvaluator::
  9834. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9835. bool &SuppressRHSDiags) {
  9836. if (E->getOpcode() == BO_Comma) {
  9837. // Ignore LHS but note if we could not evaluate it.
  9838. if (LHSResult.Failed)
  9839. return Info.noteSideEffect();
  9840. return true;
  9841. }
  9842. if (E->isLogicalOp()) {
  9843. bool LHSAsBool;
  9844. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  9845. // We were able to evaluate the LHS, see if we can get away with not
  9846. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  9847. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  9848. Success(LHSAsBool, E, LHSResult.Val);
  9849. return false; // Ignore RHS
  9850. }
  9851. } else {
  9852. LHSResult.Failed = true;
  9853. // Since we weren't able to evaluate the left hand side, it
  9854. // might have had side effects.
  9855. if (!Info.noteSideEffect())
  9856. return false;
  9857. // We can't evaluate the LHS; however, sometimes the result
  9858. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9859. // Don't ignore RHS and suppress diagnostics from this arm.
  9860. SuppressRHSDiags = true;
  9861. }
  9862. return true;
  9863. }
  9864. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9865. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9866. if (LHSResult.Failed && !Info.noteFailure())
  9867. return false; // Ignore RHS;
  9868. return true;
  9869. }
  9870. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  9871. bool IsSub) {
  9872. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  9873. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  9874. // offsets.
  9875. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  9876. CharUnits &Offset = LVal.getLValueOffset();
  9877. uint64_t Offset64 = Offset.getQuantity();
  9878. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  9879. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  9880. : Offset64 + Index64);
  9881. }
  9882. bool DataRecursiveIntBinOpEvaluator::
  9883. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9884. const BinaryOperator *E, APValue &Result) {
  9885. if (E->getOpcode() == BO_Comma) {
  9886. if (RHSResult.Failed)
  9887. return false;
  9888. Result = RHSResult.Val;
  9889. return true;
  9890. }
  9891. if (E->isLogicalOp()) {
  9892. bool lhsResult, rhsResult;
  9893. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  9894. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  9895. if (LHSIsOK) {
  9896. if (RHSIsOK) {
  9897. if (E->getOpcode() == BO_LOr)
  9898. return Success(lhsResult || rhsResult, E, Result);
  9899. else
  9900. return Success(lhsResult && rhsResult, E, Result);
  9901. }
  9902. } else {
  9903. if (RHSIsOK) {
  9904. // We can't evaluate the LHS; however, sometimes the result
  9905. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9906. if (rhsResult == (E->getOpcode() == BO_LOr))
  9907. return Success(rhsResult, E, Result);
  9908. }
  9909. }
  9910. return false;
  9911. }
  9912. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9913. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9914. if (LHSResult.Failed || RHSResult.Failed)
  9915. return false;
  9916. const APValue &LHSVal = LHSResult.Val;
  9917. const APValue &RHSVal = RHSResult.Val;
  9918. // Handle cases like (unsigned long)&a + 4.
  9919. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  9920. Result = LHSVal;
  9921. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  9922. return true;
  9923. }
  9924. // Handle cases like 4 + (unsigned long)&a
  9925. if (E->getOpcode() == BO_Add &&
  9926. RHSVal.isLValue() && LHSVal.isInt()) {
  9927. Result = RHSVal;
  9928. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  9929. return true;
  9930. }
  9931. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  9932. // Handle (intptr_t)&&A - (intptr_t)&&B.
  9933. if (!LHSVal.getLValueOffset().isZero() ||
  9934. !RHSVal.getLValueOffset().isZero())
  9935. return false;
  9936. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  9937. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  9938. if (!LHSExpr || !RHSExpr)
  9939. return false;
  9940. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9941. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9942. if (!LHSAddrExpr || !RHSAddrExpr)
  9943. return false;
  9944. // Make sure both labels come from the same function.
  9945. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9946. RHSAddrExpr->getLabel()->getDeclContext())
  9947. return false;
  9948. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  9949. return true;
  9950. }
  9951. // All the remaining cases expect both operands to be an integer
  9952. if (!LHSVal.isInt() || !RHSVal.isInt())
  9953. return Error(E);
  9954. // Set up the width and signedness manually, in case it can't be deduced
  9955. // from the operation we're performing.
  9956. // FIXME: Don't do this in the cases where we can deduce it.
  9957. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  9958. E->getType()->isUnsignedIntegerOrEnumerationType());
  9959. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  9960. RHSVal.getInt(), Value))
  9961. return false;
  9962. return Success(Value, E, Result);
  9963. }
  9964. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  9965. Job &job = Queue.back();
  9966. switch (job.Kind) {
  9967. case Job::AnyExprKind: {
  9968. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  9969. if (shouldEnqueue(Bop)) {
  9970. job.Kind = Job::BinOpKind;
  9971. enqueue(Bop->getLHS());
  9972. return;
  9973. }
  9974. }
  9975. EvaluateExpr(job.E, Result);
  9976. Queue.pop_back();
  9977. return;
  9978. }
  9979. case Job::BinOpKind: {
  9980. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9981. bool SuppressRHSDiags = false;
  9982. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  9983. Queue.pop_back();
  9984. return;
  9985. }
  9986. if (SuppressRHSDiags)
  9987. job.startSpeculativeEval(Info);
  9988. job.LHSResult.swap(Result);
  9989. job.Kind = Job::BinOpVisitedLHSKind;
  9990. enqueue(Bop->getRHS());
  9991. return;
  9992. }
  9993. case Job::BinOpVisitedLHSKind: {
  9994. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9995. EvalResult RHS;
  9996. RHS.swap(Result);
  9997. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  9998. Queue.pop_back();
  9999. return;
  10000. }
  10001. }
  10002. llvm_unreachable("Invalid Job::Kind!");
  10003. }
  10004. namespace {
  10005. /// Used when we determine that we should fail, but can keep evaluating prior to
  10006. /// noting that we had a failure.
  10007. class DelayedNoteFailureRAII {
  10008. EvalInfo &Info;
  10009. bool NoteFailure;
  10010. public:
  10011. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  10012. : Info(Info), NoteFailure(NoteFailure) {}
  10013. ~DelayedNoteFailureRAII() {
  10014. if (NoteFailure) {
  10015. bool ContinueAfterFailure = Info.noteFailure();
  10016. (void)ContinueAfterFailure;
  10017. assert(ContinueAfterFailure &&
  10018. "Shouldn't have kept evaluating on failure.");
  10019. }
  10020. }
  10021. };
  10022. }
  10023. template <class SuccessCB, class AfterCB>
  10024. static bool
  10025. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  10026. SuccessCB &&Success, AfterCB &&DoAfter) {
  10027. assert(E->isComparisonOp() && "expected comparison operator");
  10028. assert((E->getOpcode() == BO_Cmp ||
  10029. E->getType()->isIntegralOrEnumerationType()) &&
  10030. "unsupported binary expression evaluation");
  10031. auto Error = [&](const Expr *E) {
  10032. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10033. return false;
  10034. };
  10035. using CCR = ComparisonCategoryResult;
  10036. bool IsRelational = E->isRelationalOp();
  10037. bool IsEquality = E->isEqualityOp();
  10038. if (E->getOpcode() == BO_Cmp) {
  10039. const ComparisonCategoryInfo &CmpInfo =
  10040. Info.Ctx.CompCategories.getInfoForType(E->getType());
  10041. IsRelational = CmpInfo.isOrdered();
  10042. IsEquality = CmpInfo.isEquality();
  10043. }
  10044. QualType LHSTy = E->getLHS()->getType();
  10045. QualType RHSTy = E->getRHS()->getType();
  10046. if (LHSTy->isIntegralOrEnumerationType() &&
  10047. RHSTy->isIntegralOrEnumerationType()) {
  10048. APSInt LHS, RHS;
  10049. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  10050. if (!LHSOK && !Info.noteFailure())
  10051. return false;
  10052. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  10053. return false;
  10054. if (LHS < RHS)
  10055. return Success(CCR::Less, E);
  10056. if (LHS > RHS)
  10057. return Success(CCR::Greater, E);
  10058. return Success(CCR::Equal, E);
  10059. }
  10060. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  10061. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  10062. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  10063. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  10064. if (!LHSOK && !Info.noteFailure())
  10065. return false;
  10066. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  10067. return false;
  10068. if (LHSFX < RHSFX)
  10069. return Success(CCR::Less, E);
  10070. if (LHSFX > RHSFX)
  10071. return Success(CCR::Greater, E);
  10072. return Success(CCR::Equal, E);
  10073. }
  10074. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  10075. ComplexValue LHS, RHS;
  10076. bool LHSOK;
  10077. if (E->isAssignmentOp()) {
  10078. LValue LV;
  10079. EvaluateLValue(E->getLHS(), LV, Info);
  10080. LHSOK = false;
  10081. } else if (LHSTy->isRealFloatingType()) {
  10082. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  10083. if (LHSOK) {
  10084. LHS.makeComplexFloat();
  10085. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  10086. }
  10087. } else {
  10088. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  10089. }
  10090. if (!LHSOK && !Info.noteFailure())
  10091. return false;
  10092. if (E->getRHS()->getType()->isRealFloatingType()) {
  10093. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  10094. return false;
  10095. RHS.makeComplexFloat();
  10096. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  10097. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10098. return false;
  10099. if (LHS.isComplexFloat()) {
  10100. APFloat::cmpResult CR_r =
  10101. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  10102. APFloat::cmpResult CR_i =
  10103. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  10104. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  10105. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  10106. } else {
  10107. assert(IsEquality && "invalid complex comparison");
  10108. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  10109. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  10110. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  10111. }
  10112. }
  10113. if (LHSTy->isRealFloatingType() &&
  10114. RHSTy->isRealFloatingType()) {
  10115. APFloat RHS(0.0), LHS(0.0);
  10116. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  10117. if (!LHSOK && !Info.noteFailure())
  10118. return false;
  10119. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  10120. return false;
  10121. assert(E->isComparisonOp() && "Invalid binary operator!");
  10122. auto GetCmpRes = [&]() {
  10123. switch (LHS.compare(RHS)) {
  10124. case APFloat::cmpEqual:
  10125. return CCR::Equal;
  10126. case APFloat::cmpLessThan:
  10127. return CCR::Less;
  10128. case APFloat::cmpGreaterThan:
  10129. return CCR::Greater;
  10130. case APFloat::cmpUnordered:
  10131. return CCR::Unordered;
  10132. }
  10133. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  10134. };
  10135. return Success(GetCmpRes(), E);
  10136. }
  10137. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  10138. LValue LHSValue, RHSValue;
  10139. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  10140. if (!LHSOK && !Info.noteFailure())
  10141. return false;
  10142. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10143. return false;
  10144. // Reject differing bases from the normal codepath; we special-case
  10145. // comparisons to null.
  10146. if (!HasSameBase(LHSValue, RHSValue)) {
  10147. // Inequalities and subtractions between unrelated pointers have
  10148. // unspecified or undefined behavior.
  10149. if (!IsEquality)
  10150. return Error(E);
  10151. // A constant address may compare equal to the address of a symbol.
  10152. // The one exception is that address of an object cannot compare equal
  10153. // to a null pointer constant.
  10154. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  10155. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  10156. return Error(E);
  10157. // It's implementation-defined whether distinct literals will have
  10158. // distinct addresses. In clang, the result of such a comparison is
  10159. // unspecified, so it is not a constant expression. However, we do know
  10160. // that the address of a literal will be non-null.
  10161. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  10162. LHSValue.Base && RHSValue.Base)
  10163. return Error(E);
  10164. // We can't tell whether weak symbols will end up pointing to the same
  10165. // object.
  10166. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  10167. return Error(E);
  10168. // We can't compare the address of the start of one object with the
  10169. // past-the-end address of another object, per C++ DR1652.
  10170. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  10171. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  10172. (RHSValue.Base && RHSValue.Offset.isZero() &&
  10173. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  10174. return Error(E);
  10175. // We can't tell whether an object is at the same address as another
  10176. // zero sized object.
  10177. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  10178. (LHSValue.Base && isZeroSized(RHSValue)))
  10179. return Error(E);
  10180. return Success(CCR::Nonequal, E);
  10181. }
  10182. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  10183. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  10184. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  10185. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  10186. // C++11 [expr.rel]p3:
  10187. // Pointers to void (after pointer conversions) can be compared, with a
  10188. // result defined as follows: If both pointers represent the same
  10189. // address or are both the null pointer value, the result is true if the
  10190. // operator is <= or >= and false otherwise; otherwise the result is
  10191. // unspecified.
  10192. // We interpret this as applying to pointers to *cv* void.
  10193. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  10194. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  10195. // C++11 [expr.rel]p2:
  10196. // - If two pointers point to non-static data members of the same object,
  10197. // or to subobjects or array elements fo such members, recursively, the
  10198. // pointer to the later declared member compares greater provided the
  10199. // two members have the same access control and provided their class is
  10200. // not a union.
  10201. // [...]
  10202. // - Otherwise pointer comparisons are unspecified.
  10203. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  10204. bool WasArrayIndex;
  10205. unsigned Mismatch = FindDesignatorMismatch(
  10206. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  10207. // At the point where the designators diverge, the comparison has a
  10208. // specified value if:
  10209. // - we are comparing array indices
  10210. // - we are comparing fields of a union, or fields with the same access
  10211. // Otherwise, the result is unspecified and thus the comparison is not a
  10212. // constant expression.
  10213. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  10214. Mismatch < RHSDesignator.Entries.size()) {
  10215. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  10216. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  10217. if (!LF && !RF)
  10218. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  10219. else if (!LF)
  10220. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  10221. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  10222. << RF->getParent() << RF;
  10223. else if (!RF)
  10224. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  10225. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  10226. << LF->getParent() << LF;
  10227. else if (!LF->getParent()->isUnion() &&
  10228. LF->getAccess() != RF->getAccess())
  10229. Info.CCEDiag(E,
  10230. diag::note_constexpr_pointer_comparison_differing_access)
  10231. << LF << LF->getAccess() << RF << RF->getAccess()
  10232. << LF->getParent();
  10233. }
  10234. }
  10235. // The comparison here must be unsigned, and performed with the same
  10236. // width as the pointer.
  10237. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  10238. uint64_t CompareLHS = LHSOffset.getQuantity();
  10239. uint64_t CompareRHS = RHSOffset.getQuantity();
  10240. assert(PtrSize <= 64 && "Unexpected pointer width");
  10241. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  10242. CompareLHS &= Mask;
  10243. CompareRHS &= Mask;
  10244. // If there is a base and this is a relational operator, we can only
  10245. // compare pointers within the object in question; otherwise, the result
  10246. // depends on where the object is located in memory.
  10247. if (!LHSValue.Base.isNull() && IsRelational) {
  10248. QualType BaseTy = getType(LHSValue.Base);
  10249. if (BaseTy->isIncompleteType())
  10250. return Error(E);
  10251. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  10252. uint64_t OffsetLimit = Size.getQuantity();
  10253. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  10254. return Error(E);
  10255. }
  10256. if (CompareLHS < CompareRHS)
  10257. return Success(CCR::Less, E);
  10258. if (CompareLHS > CompareRHS)
  10259. return Success(CCR::Greater, E);
  10260. return Success(CCR::Equal, E);
  10261. }
  10262. if (LHSTy->isMemberPointerType()) {
  10263. assert(IsEquality && "unexpected member pointer operation");
  10264. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  10265. MemberPtr LHSValue, RHSValue;
  10266. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  10267. if (!LHSOK && !Info.noteFailure())
  10268. return false;
  10269. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10270. return false;
  10271. // C++11 [expr.eq]p2:
  10272. // If both operands are null, they compare equal. Otherwise if only one is
  10273. // null, they compare unequal.
  10274. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  10275. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  10276. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  10277. }
  10278. // Otherwise if either is a pointer to a virtual member function, the
  10279. // result is unspecified.
  10280. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  10281. if (MD->isVirtual())
  10282. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  10283. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  10284. if (MD->isVirtual())
  10285. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  10286. // Otherwise they compare equal if and only if they would refer to the
  10287. // same member of the same most derived object or the same subobject if
  10288. // they were dereferenced with a hypothetical object of the associated
  10289. // class type.
  10290. bool Equal = LHSValue == RHSValue;
  10291. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  10292. }
  10293. if (LHSTy->isNullPtrType()) {
  10294. assert(E->isComparisonOp() && "unexpected nullptr operation");
  10295. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  10296. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  10297. // are compared, the result is true of the operator is <=, >= or ==, and
  10298. // false otherwise.
  10299. return Success(CCR::Equal, E);
  10300. }
  10301. return DoAfter();
  10302. }
  10303. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  10304. if (!CheckLiteralType(Info, E))
  10305. return false;
  10306. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10307. const BinaryOperator *E) {
  10308. // Evaluation succeeded. Lookup the information for the comparison category
  10309. // type and fetch the VarDecl for the result.
  10310. const ComparisonCategoryInfo &CmpInfo =
  10311. Info.Ctx.CompCategories.getInfoForType(E->getType());
  10312. const VarDecl *VD =
  10313. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  10314. // Check and evaluate the result as a constant expression.
  10315. LValue LV;
  10316. LV.set(VD);
  10317. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10318. return false;
  10319. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10320. };
  10321. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10322. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  10323. });
  10324. }
  10325. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10326. // We don't call noteFailure immediately because the assignment happens after
  10327. // we evaluate LHS and RHS.
  10328. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  10329. return Error(E);
  10330. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  10331. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  10332. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  10333. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  10334. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  10335. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  10336. if (E->isComparisonOp()) {
  10337. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  10338. // comparisons and then translating the result.
  10339. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10340. const BinaryOperator *E) {
  10341. using CCR = ComparisonCategoryResult;
  10342. bool IsEqual = ResKind == CCR::Equal,
  10343. IsLess = ResKind == CCR::Less,
  10344. IsGreater = ResKind == CCR::Greater;
  10345. auto Op = E->getOpcode();
  10346. switch (Op) {
  10347. default:
  10348. llvm_unreachable("unsupported binary operator");
  10349. case BO_EQ:
  10350. case BO_NE:
  10351. return Success(IsEqual == (Op == BO_EQ), E);
  10352. case BO_LT: return Success(IsLess, E);
  10353. case BO_GT: return Success(IsGreater, E);
  10354. case BO_LE: return Success(IsEqual || IsLess, E);
  10355. case BO_GE: return Success(IsEqual || IsGreater, E);
  10356. }
  10357. };
  10358. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10359. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10360. });
  10361. }
  10362. QualType LHSTy = E->getLHS()->getType();
  10363. QualType RHSTy = E->getRHS()->getType();
  10364. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  10365. E->getOpcode() == BO_Sub) {
  10366. LValue LHSValue, RHSValue;
  10367. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  10368. if (!LHSOK && !Info.noteFailure())
  10369. return false;
  10370. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10371. return false;
  10372. // Reject differing bases from the normal codepath; we special-case
  10373. // comparisons to null.
  10374. if (!HasSameBase(LHSValue, RHSValue)) {
  10375. // Handle &&A - &&B.
  10376. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  10377. return Error(E);
  10378. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  10379. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  10380. if (!LHSExpr || !RHSExpr)
  10381. return Error(E);
  10382. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  10383. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  10384. if (!LHSAddrExpr || !RHSAddrExpr)
  10385. return Error(E);
  10386. // Make sure both labels come from the same function.
  10387. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  10388. RHSAddrExpr->getLabel()->getDeclContext())
  10389. return Error(E);
  10390. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  10391. }
  10392. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  10393. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  10394. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  10395. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  10396. // C++11 [expr.add]p6:
  10397. // Unless both pointers point to elements of the same array object, or
  10398. // one past the last element of the array object, the behavior is
  10399. // undefined.
  10400. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  10401. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  10402. RHSDesignator))
  10403. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  10404. QualType Type = E->getLHS()->getType();
  10405. QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
  10406. CharUnits ElementSize;
  10407. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  10408. return false;
  10409. // As an extension, a type may have zero size (empty struct or union in
  10410. // C, array of zero length). Pointer subtraction in such cases has
  10411. // undefined behavior, so is not constant.
  10412. if (ElementSize.isZero()) {
  10413. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  10414. << ElementType;
  10415. return false;
  10416. }
  10417. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  10418. // and produce incorrect results when it overflows. Such behavior
  10419. // appears to be non-conforming, but is common, so perhaps we should
  10420. // assume the standard intended for such cases to be undefined behavior
  10421. // and check for them.
  10422. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  10423. // overflow in the final conversion to ptrdiff_t.
  10424. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  10425. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  10426. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  10427. false);
  10428. APSInt TrueResult = (LHS - RHS) / ElemSize;
  10429. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  10430. if (Result.extend(65) != TrueResult &&
  10431. !HandleOverflow(Info, E, TrueResult, E->getType()))
  10432. return false;
  10433. return Success(Result, E);
  10434. }
  10435. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10436. }
  10437. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  10438. /// a result as the expression's type.
  10439. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  10440. const UnaryExprOrTypeTraitExpr *E) {
  10441. switch(E->getKind()) {
  10442. case UETT_PreferredAlignOf:
  10443. case UETT_AlignOf: {
  10444. if (E->isArgumentType())
  10445. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  10446. E);
  10447. else
  10448. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  10449. E);
  10450. }
  10451. case UETT_VecStep: {
  10452. QualType Ty = E->getTypeOfArgument();
  10453. if (Ty->isVectorType()) {
  10454. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  10455. // The vec_step built-in functions that take a 3-component
  10456. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  10457. if (n == 3)
  10458. n = 4;
  10459. return Success(n, E);
  10460. } else
  10461. return Success(1, E);
  10462. }
  10463. case UETT_SizeOf: {
  10464. QualType SrcTy = E->getTypeOfArgument();
  10465. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  10466. // the result is the size of the referenced type."
  10467. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  10468. SrcTy = Ref->getPointeeType();
  10469. CharUnits Sizeof;
  10470. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  10471. return false;
  10472. return Success(Sizeof, E);
  10473. }
  10474. case UETT_OpenMPRequiredSimdAlign:
  10475. assert(E->isArgumentType());
  10476. return Success(
  10477. Info.Ctx.toCharUnitsFromBits(
  10478. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  10479. .getQuantity(),
  10480. E);
  10481. }
  10482. llvm_unreachable("unknown expr/type trait");
  10483. }
  10484. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  10485. CharUnits Result;
  10486. unsigned n = OOE->getNumComponents();
  10487. if (n == 0)
  10488. return Error(OOE);
  10489. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  10490. for (unsigned i = 0; i != n; ++i) {
  10491. OffsetOfNode ON = OOE->getComponent(i);
  10492. switch (ON.getKind()) {
  10493. case OffsetOfNode::Array: {
  10494. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  10495. APSInt IdxResult;
  10496. if (!EvaluateInteger(Idx, IdxResult, Info))
  10497. return false;
  10498. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  10499. if (!AT)
  10500. return Error(OOE);
  10501. CurrentType = AT->getElementType();
  10502. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  10503. Result += IdxResult.getSExtValue() * ElementSize;
  10504. break;
  10505. }
  10506. case OffsetOfNode::Field: {
  10507. FieldDecl *MemberDecl = ON.getField();
  10508. const RecordType *RT = CurrentType->getAs<RecordType>();
  10509. if (!RT)
  10510. return Error(OOE);
  10511. RecordDecl *RD = RT->getDecl();
  10512. if (RD->isInvalidDecl()) return false;
  10513. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10514. unsigned i = MemberDecl->getFieldIndex();
  10515. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  10516. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  10517. CurrentType = MemberDecl->getType().getNonReferenceType();
  10518. break;
  10519. }
  10520. case OffsetOfNode::Identifier:
  10521. llvm_unreachable("dependent __builtin_offsetof");
  10522. case OffsetOfNode::Base: {
  10523. CXXBaseSpecifier *BaseSpec = ON.getBase();
  10524. if (BaseSpec->isVirtual())
  10525. return Error(OOE);
  10526. // Find the layout of the class whose base we are looking into.
  10527. const RecordType *RT = CurrentType->getAs<RecordType>();
  10528. if (!RT)
  10529. return Error(OOE);
  10530. RecordDecl *RD = RT->getDecl();
  10531. if (RD->isInvalidDecl()) return false;
  10532. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10533. // Find the base class itself.
  10534. CurrentType = BaseSpec->getType();
  10535. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  10536. if (!BaseRT)
  10537. return Error(OOE);
  10538. // Add the offset to the base.
  10539. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  10540. break;
  10541. }
  10542. }
  10543. }
  10544. return Success(Result, OOE);
  10545. }
  10546. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10547. switch (E->getOpcode()) {
  10548. default:
  10549. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  10550. // See C99 6.6p3.
  10551. return Error(E);
  10552. case UO_Extension:
  10553. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  10554. // If so, we could clear the diagnostic ID.
  10555. return Visit(E->getSubExpr());
  10556. case UO_Plus:
  10557. // The result is just the value.
  10558. return Visit(E->getSubExpr());
  10559. case UO_Minus: {
  10560. if (!Visit(E->getSubExpr()))
  10561. return false;
  10562. if (!Result.isInt()) return Error(E);
  10563. const APSInt &Value = Result.getInt();
  10564. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  10565. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  10566. E->getType()))
  10567. return false;
  10568. return Success(-Value, E);
  10569. }
  10570. case UO_Not: {
  10571. if (!Visit(E->getSubExpr()))
  10572. return false;
  10573. if (!Result.isInt()) return Error(E);
  10574. return Success(~Result.getInt(), E);
  10575. }
  10576. case UO_LNot: {
  10577. bool bres;
  10578. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10579. return false;
  10580. return Success(!bres, E);
  10581. }
  10582. }
  10583. }
  10584. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  10585. /// result type is integer.
  10586. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10587. const Expr *SubExpr = E->getSubExpr();
  10588. QualType DestType = E->getType();
  10589. QualType SrcType = SubExpr->getType();
  10590. switch (E->getCastKind()) {
  10591. case CK_BaseToDerived:
  10592. case CK_DerivedToBase:
  10593. case CK_UncheckedDerivedToBase:
  10594. case CK_Dynamic:
  10595. case CK_ToUnion:
  10596. case CK_ArrayToPointerDecay:
  10597. case CK_FunctionToPointerDecay:
  10598. case CK_NullToPointer:
  10599. case CK_NullToMemberPointer:
  10600. case CK_BaseToDerivedMemberPointer:
  10601. case CK_DerivedToBaseMemberPointer:
  10602. case CK_ReinterpretMemberPointer:
  10603. case CK_ConstructorConversion:
  10604. case CK_IntegralToPointer:
  10605. case CK_ToVoid:
  10606. case CK_VectorSplat:
  10607. case CK_IntegralToFloating:
  10608. case CK_FloatingCast:
  10609. case CK_CPointerToObjCPointerCast:
  10610. case CK_BlockPointerToObjCPointerCast:
  10611. case CK_AnyPointerToBlockPointerCast:
  10612. case CK_ObjCObjectLValueCast:
  10613. case CK_FloatingRealToComplex:
  10614. case CK_FloatingComplexToReal:
  10615. case CK_FloatingComplexCast:
  10616. case CK_FloatingComplexToIntegralComplex:
  10617. case CK_IntegralRealToComplex:
  10618. case CK_IntegralComplexCast:
  10619. case CK_IntegralComplexToFloatingComplex:
  10620. case CK_BuiltinFnToFnPtr:
  10621. case CK_ZeroToOCLOpaqueType:
  10622. case CK_NonAtomicToAtomic:
  10623. case CK_AddressSpaceConversion:
  10624. case CK_IntToOCLSampler:
  10625. case CK_FixedPointCast:
  10626. case CK_IntegralToFixedPoint:
  10627. llvm_unreachable("invalid cast kind for integral value");
  10628. case CK_BitCast:
  10629. case CK_Dependent:
  10630. case CK_LValueBitCast:
  10631. case CK_ARCProduceObject:
  10632. case CK_ARCConsumeObject:
  10633. case CK_ARCReclaimReturnedObject:
  10634. case CK_ARCExtendBlockObject:
  10635. case CK_CopyAndAutoreleaseBlockObject:
  10636. return Error(E);
  10637. case CK_UserDefinedConversion:
  10638. case CK_LValueToRValue:
  10639. case CK_AtomicToNonAtomic:
  10640. case CK_NoOp:
  10641. case CK_LValueToRValueBitCast:
  10642. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10643. case CK_MemberPointerToBoolean:
  10644. case CK_PointerToBoolean:
  10645. case CK_IntegralToBoolean:
  10646. case CK_FloatingToBoolean:
  10647. case CK_BooleanToSignedIntegral:
  10648. case CK_FloatingComplexToBoolean:
  10649. case CK_IntegralComplexToBoolean: {
  10650. bool BoolResult;
  10651. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  10652. return false;
  10653. uint64_t IntResult = BoolResult;
  10654. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  10655. IntResult = (uint64_t)-1;
  10656. return Success(IntResult, E);
  10657. }
  10658. case CK_FixedPointToIntegral: {
  10659. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  10660. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10661. return false;
  10662. bool Overflowed;
  10663. llvm::APSInt Result = Src.convertToInt(
  10664. Info.Ctx.getIntWidth(DestType),
  10665. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  10666. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10667. return false;
  10668. return Success(Result, E);
  10669. }
  10670. case CK_FixedPointToBoolean: {
  10671. // Unsigned padding does not affect this.
  10672. APValue Val;
  10673. if (!Evaluate(Val, Info, SubExpr))
  10674. return false;
  10675. return Success(Val.getFixedPoint().getBoolValue(), E);
  10676. }
  10677. case CK_IntegralCast: {
  10678. if (!Visit(SubExpr))
  10679. return false;
  10680. if (!Result.isInt()) {
  10681. // Allow casts of address-of-label differences if they are no-ops
  10682. // or narrowing. (The narrowing case isn't actually guaranteed to
  10683. // be constant-evaluatable except in some narrow cases which are hard
  10684. // to detect here. We let it through on the assumption the user knows
  10685. // what they are doing.)
  10686. if (Result.isAddrLabelDiff())
  10687. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  10688. // Only allow casts of lvalues if they are lossless.
  10689. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  10690. }
  10691. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  10692. Result.getInt()), E);
  10693. }
  10694. case CK_PointerToIntegral: {
  10695. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  10696. LValue LV;
  10697. if (!EvaluatePointer(SubExpr, LV, Info))
  10698. return false;
  10699. if (LV.getLValueBase()) {
  10700. // Only allow based lvalue casts if they are lossless.
  10701. // FIXME: Allow a larger integer size than the pointer size, and allow
  10702. // narrowing back down to pointer width in subsequent integral casts.
  10703. // FIXME: Check integer type's active bits, not its type size.
  10704. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  10705. return Error(E);
  10706. LV.Designator.setInvalid();
  10707. LV.moveInto(Result);
  10708. return true;
  10709. }
  10710. APSInt AsInt;
  10711. APValue V;
  10712. LV.moveInto(V);
  10713. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  10714. llvm_unreachable("Can't cast this!");
  10715. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  10716. }
  10717. case CK_IntegralComplexToReal: {
  10718. ComplexValue C;
  10719. if (!EvaluateComplex(SubExpr, C, Info))
  10720. return false;
  10721. return Success(C.getComplexIntReal(), E);
  10722. }
  10723. case CK_FloatingToIntegral: {
  10724. APFloat F(0.0);
  10725. if (!EvaluateFloat(SubExpr, F, Info))
  10726. return false;
  10727. APSInt Value;
  10728. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  10729. return false;
  10730. return Success(Value, E);
  10731. }
  10732. }
  10733. llvm_unreachable("unknown cast resulting in integral value");
  10734. }
  10735. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10736. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10737. ComplexValue LV;
  10738. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10739. return false;
  10740. if (!LV.isComplexInt())
  10741. return Error(E);
  10742. return Success(LV.getComplexIntReal(), E);
  10743. }
  10744. return Visit(E->getSubExpr());
  10745. }
  10746. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10747. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  10748. ComplexValue LV;
  10749. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10750. return false;
  10751. if (!LV.isComplexInt())
  10752. return Error(E);
  10753. return Success(LV.getComplexIntImag(), E);
  10754. }
  10755. VisitIgnoredValue(E->getSubExpr());
  10756. return Success(0, E);
  10757. }
  10758. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  10759. return Success(E->getPackLength(), E);
  10760. }
  10761. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  10762. return Success(E->getValue(), E);
  10763. }
  10764. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10765. switch (E->getOpcode()) {
  10766. default:
  10767. // Invalid unary operators
  10768. return Error(E);
  10769. case UO_Plus:
  10770. // The result is just the value.
  10771. return Visit(E->getSubExpr());
  10772. case UO_Minus: {
  10773. if (!Visit(E->getSubExpr())) return false;
  10774. if (!Result.isFixedPoint())
  10775. return Error(E);
  10776. bool Overflowed;
  10777. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  10778. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  10779. return false;
  10780. return Success(Negated, E);
  10781. }
  10782. case UO_LNot: {
  10783. bool bres;
  10784. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10785. return false;
  10786. return Success(!bres, E);
  10787. }
  10788. }
  10789. }
  10790. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10791. const Expr *SubExpr = E->getSubExpr();
  10792. QualType DestType = E->getType();
  10793. assert(DestType->isFixedPointType() &&
  10794. "Expected destination type to be a fixed point type");
  10795. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  10796. switch (E->getCastKind()) {
  10797. case CK_FixedPointCast: {
  10798. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  10799. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10800. return false;
  10801. bool Overflowed;
  10802. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  10803. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10804. return false;
  10805. return Success(Result, E);
  10806. }
  10807. case CK_IntegralToFixedPoint: {
  10808. APSInt Src;
  10809. if (!EvaluateInteger(SubExpr, Src, Info))
  10810. return false;
  10811. bool Overflowed;
  10812. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10813. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  10814. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  10815. return false;
  10816. return Success(IntResult, E);
  10817. }
  10818. case CK_NoOp:
  10819. case CK_LValueToRValue:
  10820. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10821. default:
  10822. return Error(E);
  10823. }
  10824. }
  10825. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10826. const Expr *LHS = E->getLHS();
  10827. const Expr *RHS = E->getRHS();
  10828. FixedPointSemantics ResultFXSema =
  10829. Info.Ctx.getFixedPointSemantics(E->getType());
  10830. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  10831. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  10832. return false;
  10833. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  10834. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  10835. return false;
  10836. switch (E->getOpcode()) {
  10837. case BO_Add: {
  10838. bool AddOverflow, ConversionOverflow;
  10839. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  10840. .convert(ResultFXSema, &ConversionOverflow);
  10841. if ((AddOverflow || ConversionOverflow) &&
  10842. !HandleOverflow(Info, E, Result, E->getType()))
  10843. return false;
  10844. return Success(Result, E);
  10845. }
  10846. default:
  10847. return false;
  10848. }
  10849. llvm_unreachable("Should've exited before this");
  10850. }
  10851. //===----------------------------------------------------------------------===//
  10852. // Float Evaluation
  10853. //===----------------------------------------------------------------------===//
  10854. namespace {
  10855. class FloatExprEvaluator
  10856. : public ExprEvaluatorBase<FloatExprEvaluator> {
  10857. APFloat &Result;
  10858. public:
  10859. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  10860. : ExprEvaluatorBaseTy(info), Result(result) {}
  10861. bool Success(const APValue &V, const Expr *e) {
  10862. Result = V.getFloat();
  10863. return true;
  10864. }
  10865. bool ZeroInitialization(const Expr *E) {
  10866. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  10867. return true;
  10868. }
  10869. bool VisitCallExpr(const CallExpr *E);
  10870. bool VisitUnaryOperator(const UnaryOperator *E);
  10871. bool VisitBinaryOperator(const BinaryOperator *E);
  10872. bool VisitFloatingLiteral(const FloatingLiteral *E);
  10873. bool VisitCastExpr(const CastExpr *E);
  10874. bool VisitUnaryReal(const UnaryOperator *E);
  10875. bool VisitUnaryImag(const UnaryOperator *E);
  10876. // FIXME: Missing: array subscript of vector, member of vector
  10877. };
  10878. } // end anonymous namespace
  10879. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  10880. assert(E->isRValue() && E->getType()->isRealFloatingType());
  10881. return FloatExprEvaluator(Info, Result).Visit(E);
  10882. }
  10883. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  10884. QualType ResultTy,
  10885. const Expr *Arg,
  10886. bool SNaN,
  10887. llvm::APFloat &Result) {
  10888. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  10889. if (!S) return false;
  10890. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  10891. llvm::APInt fill;
  10892. // Treat empty strings as if they were zero.
  10893. if (S->getString().empty())
  10894. fill = llvm::APInt(32, 0);
  10895. else if (S->getString().getAsInteger(0, fill))
  10896. return false;
  10897. if (Context.getTargetInfo().isNan2008()) {
  10898. if (SNaN)
  10899. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10900. else
  10901. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10902. } else {
  10903. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  10904. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  10905. // a different encoding to what became a standard in 2008, and for pre-
  10906. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  10907. // sNaN. This is now known as "legacy NaN" encoding.
  10908. if (SNaN)
  10909. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10910. else
  10911. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10912. }
  10913. return true;
  10914. }
  10915. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10916. switch (E->getBuiltinCallee()) {
  10917. default:
  10918. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10919. case Builtin::BI__builtin_huge_val:
  10920. case Builtin::BI__builtin_huge_valf:
  10921. case Builtin::BI__builtin_huge_vall:
  10922. case Builtin::BI__builtin_huge_valf128:
  10923. case Builtin::BI__builtin_inf:
  10924. case Builtin::BI__builtin_inff:
  10925. case Builtin::BI__builtin_infl:
  10926. case Builtin::BI__builtin_inff128: {
  10927. const llvm::fltSemantics &Sem =
  10928. Info.Ctx.getFloatTypeSemantics(E->getType());
  10929. Result = llvm::APFloat::getInf(Sem);
  10930. return true;
  10931. }
  10932. case Builtin::BI__builtin_nans:
  10933. case Builtin::BI__builtin_nansf:
  10934. case Builtin::BI__builtin_nansl:
  10935. case Builtin::BI__builtin_nansf128:
  10936. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10937. true, Result))
  10938. return Error(E);
  10939. return true;
  10940. case Builtin::BI__builtin_nan:
  10941. case Builtin::BI__builtin_nanf:
  10942. case Builtin::BI__builtin_nanl:
  10943. case Builtin::BI__builtin_nanf128:
  10944. // If this is __builtin_nan() turn this into a nan, otherwise we
  10945. // can't constant fold it.
  10946. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10947. false, Result))
  10948. return Error(E);
  10949. return true;
  10950. case Builtin::BI__builtin_fabs:
  10951. case Builtin::BI__builtin_fabsf:
  10952. case Builtin::BI__builtin_fabsl:
  10953. case Builtin::BI__builtin_fabsf128:
  10954. if (!EvaluateFloat(E->getArg(0), Result, Info))
  10955. return false;
  10956. if (Result.isNegative())
  10957. Result.changeSign();
  10958. return true;
  10959. // FIXME: Builtin::BI__builtin_powi
  10960. // FIXME: Builtin::BI__builtin_powif
  10961. // FIXME: Builtin::BI__builtin_powil
  10962. case Builtin::BI__builtin_copysign:
  10963. case Builtin::BI__builtin_copysignf:
  10964. case Builtin::BI__builtin_copysignl:
  10965. case Builtin::BI__builtin_copysignf128: {
  10966. APFloat RHS(0.);
  10967. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  10968. !EvaluateFloat(E->getArg(1), RHS, Info))
  10969. return false;
  10970. Result.copySign(RHS);
  10971. return true;
  10972. }
  10973. }
  10974. }
  10975. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10976. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10977. ComplexValue CV;
  10978. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10979. return false;
  10980. Result = CV.FloatReal;
  10981. return true;
  10982. }
  10983. return Visit(E->getSubExpr());
  10984. }
  10985. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10986. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10987. ComplexValue CV;
  10988. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10989. return false;
  10990. Result = CV.FloatImag;
  10991. return true;
  10992. }
  10993. VisitIgnoredValue(E->getSubExpr());
  10994. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  10995. Result = llvm::APFloat::getZero(Sem);
  10996. return true;
  10997. }
  10998. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10999. switch (E->getOpcode()) {
  11000. default: return Error(E);
  11001. case UO_Plus:
  11002. return EvaluateFloat(E->getSubExpr(), Result, Info);
  11003. case UO_Minus:
  11004. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  11005. return false;
  11006. Result.changeSign();
  11007. return true;
  11008. }
  11009. }
  11010. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  11011. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  11012. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11013. APFloat RHS(0.0);
  11014. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  11015. if (!LHSOK && !Info.noteFailure())
  11016. return false;
  11017. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  11018. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  11019. }
  11020. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  11021. Result = E->getValue();
  11022. return true;
  11023. }
  11024. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11025. const Expr* SubExpr = E->getSubExpr();
  11026. switch (E->getCastKind()) {
  11027. default:
  11028. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11029. case CK_IntegralToFloating: {
  11030. APSInt IntResult;
  11031. return EvaluateInteger(SubExpr, IntResult, Info) &&
  11032. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  11033. E->getType(), Result);
  11034. }
  11035. case CK_FloatingCast: {
  11036. if (!Visit(SubExpr))
  11037. return false;
  11038. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  11039. Result);
  11040. }
  11041. case CK_FloatingComplexToReal: {
  11042. ComplexValue V;
  11043. if (!EvaluateComplex(SubExpr, V, Info))
  11044. return false;
  11045. Result = V.getComplexFloatReal();
  11046. return true;
  11047. }
  11048. }
  11049. }
  11050. //===----------------------------------------------------------------------===//
  11051. // Complex Evaluation (for float and integer)
  11052. //===----------------------------------------------------------------------===//
  11053. namespace {
  11054. class ComplexExprEvaluator
  11055. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  11056. ComplexValue &Result;
  11057. public:
  11058. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  11059. : ExprEvaluatorBaseTy(info), Result(Result) {}
  11060. bool Success(const APValue &V, const Expr *e) {
  11061. Result.setFrom(V);
  11062. return true;
  11063. }
  11064. bool ZeroInitialization(const Expr *E);
  11065. //===--------------------------------------------------------------------===//
  11066. // Visitor Methods
  11067. //===--------------------------------------------------------------------===//
  11068. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  11069. bool VisitCastExpr(const CastExpr *E);
  11070. bool VisitBinaryOperator(const BinaryOperator *E);
  11071. bool VisitUnaryOperator(const UnaryOperator *E);
  11072. bool VisitInitListExpr(const InitListExpr *E);
  11073. };
  11074. } // end anonymous namespace
  11075. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  11076. EvalInfo &Info) {
  11077. assert(E->isRValue() && E->getType()->isAnyComplexType());
  11078. return ComplexExprEvaluator(Info, Result).Visit(E);
  11079. }
  11080. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  11081. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  11082. if (ElemTy->isRealFloatingType()) {
  11083. Result.makeComplexFloat();
  11084. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  11085. Result.FloatReal = Zero;
  11086. Result.FloatImag = Zero;
  11087. } else {
  11088. Result.makeComplexInt();
  11089. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  11090. Result.IntReal = Zero;
  11091. Result.IntImag = Zero;
  11092. }
  11093. return true;
  11094. }
  11095. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  11096. const Expr* SubExpr = E->getSubExpr();
  11097. if (SubExpr->getType()->isRealFloatingType()) {
  11098. Result.makeComplexFloat();
  11099. APFloat &Imag = Result.FloatImag;
  11100. if (!EvaluateFloat(SubExpr, Imag, Info))
  11101. return false;
  11102. Result.FloatReal = APFloat(Imag.getSemantics());
  11103. return true;
  11104. } else {
  11105. assert(SubExpr->getType()->isIntegerType() &&
  11106. "Unexpected imaginary literal.");
  11107. Result.makeComplexInt();
  11108. APSInt &Imag = Result.IntImag;
  11109. if (!EvaluateInteger(SubExpr, Imag, Info))
  11110. return false;
  11111. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  11112. return true;
  11113. }
  11114. }
  11115. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11116. switch (E->getCastKind()) {
  11117. case CK_BitCast:
  11118. case CK_BaseToDerived:
  11119. case CK_DerivedToBase:
  11120. case CK_UncheckedDerivedToBase:
  11121. case CK_Dynamic:
  11122. case CK_ToUnion:
  11123. case CK_ArrayToPointerDecay:
  11124. case CK_FunctionToPointerDecay:
  11125. case CK_NullToPointer:
  11126. case CK_NullToMemberPointer:
  11127. case CK_BaseToDerivedMemberPointer:
  11128. case CK_DerivedToBaseMemberPointer:
  11129. case CK_MemberPointerToBoolean:
  11130. case CK_ReinterpretMemberPointer:
  11131. case CK_ConstructorConversion:
  11132. case CK_IntegralToPointer:
  11133. case CK_PointerToIntegral:
  11134. case CK_PointerToBoolean:
  11135. case CK_ToVoid:
  11136. case CK_VectorSplat:
  11137. case CK_IntegralCast:
  11138. case CK_BooleanToSignedIntegral:
  11139. case CK_IntegralToBoolean:
  11140. case CK_IntegralToFloating:
  11141. case CK_FloatingToIntegral:
  11142. case CK_FloatingToBoolean:
  11143. case CK_FloatingCast:
  11144. case CK_CPointerToObjCPointerCast:
  11145. case CK_BlockPointerToObjCPointerCast:
  11146. case CK_AnyPointerToBlockPointerCast:
  11147. case CK_ObjCObjectLValueCast:
  11148. case CK_FloatingComplexToReal:
  11149. case CK_FloatingComplexToBoolean:
  11150. case CK_IntegralComplexToReal:
  11151. case CK_IntegralComplexToBoolean:
  11152. case CK_ARCProduceObject:
  11153. case CK_ARCConsumeObject:
  11154. case CK_ARCReclaimReturnedObject:
  11155. case CK_ARCExtendBlockObject:
  11156. case CK_CopyAndAutoreleaseBlockObject:
  11157. case CK_BuiltinFnToFnPtr:
  11158. case CK_ZeroToOCLOpaqueType:
  11159. case CK_NonAtomicToAtomic:
  11160. case CK_AddressSpaceConversion:
  11161. case CK_IntToOCLSampler:
  11162. case CK_FixedPointCast:
  11163. case CK_FixedPointToBoolean:
  11164. case CK_FixedPointToIntegral:
  11165. case CK_IntegralToFixedPoint:
  11166. llvm_unreachable("invalid cast kind for complex value");
  11167. case CK_LValueToRValue:
  11168. case CK_AtomicToNonAtomic:
  11169. case CK_NoOp:
  11170. case CK_LValueToRValueBitCast:
  11171. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11172. case CK_Dependent:
  11173. case CK_LValueBitCast:
  11174. case CK_UserDefinedConversion:
  11175. return Error(E);
  11176. case CK_FloatingRealToComplex: {
  11177. APFloat &Real = Result.FloatReal;
  11178. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  11179. return false;
  11180. Result.makeComplexFloat();
  11181. Result.FloatImag = APFloat(Real.getSemantics());
  11182. return true;
  11183. }
  11184. case CK_FloatingComplexCast: {
  11185. if (!Visit(E->getSubExpr()))
  11186. return false;
  11187. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11188. QualType From
  11189. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11190. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  11191. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  11192. }
  11193. case CK_FloatingComplexToIntegralComplex: {
  11194. if (!Visit(E->getSubExpr()))
  11195. return false;
  11196. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11197. QualType From
  11198. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11199. Result.makeComplexInt();
  11200. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  11201. To, Result.IntReal) &&
  11202. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  11203. To, Result.IntImag);
  11204. }
  11205. case CK_IntegralRealToComplex: {
  11206. APSInt &Real = Result.IntReal;
  11207. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  11208. return false;
  11209. Result.makeComplexInt();
  11210. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  11211. return true;
  11212. }
  11213. case CK_IntegralComplexCast: {
  11214. if (!Visit(E->getSubExpr()))
  11215. return false;
  11216. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11217. QualType From
  11218. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11219. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  11220. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  11221. return true;
  11222. }
  11223. case CK_IntegralComplexToFloatingComplex: {
  11224. if (!Visit(E->getSubExpr()))
  11225. return false;
  11226. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11227. QualType From
  11228. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11229. Result.makeComplexFloat();
  11230. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  11231. To, Result.FloatReal) &&
  11232. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  11233. To, Result.FloatImag);
  11234. }
  11235. }
  11236. llvm_unreachable("unknown cast resulting in complex value");
  11237. }
  11238. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  11239. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  11240. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11241. // Track whether the LHS or RHS is real at the type system level. When this is
  11242. // the case we can simplify our evaluation strategy.
  11243. bool LHSReal = false, RHSReal = false;
  11244. bool LHSOK;
  11245. if (E->getLHS()->getType()->isRealFloatingType()) {
  11246. LHSReal = true;
  11247. APFloat &Real = Result.FloatReal;
  11248. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  11249. if (LHSOK) {
  11250. Result.makeComplexFloat();
  11251. Result.FloatImag = APFloat(Real.getSemantics());
  11252. }
  11253. } else {
  11254. LHSOK = Visit(E->getLHS());
  11255. }
  11256. if (!LHSOK && !Info.noteFailure())
  11257. return false;
  11258. ComplexValue RHS;
  11259. if (E->getRHS()->getType()->isRealFloatingType()) {
  11260. RHSReal = true;
  11261. APFloat &Real = RHS.FloatReal;
  11262. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  11263. return false;
  11264. RHS.makeComplexFloat();
  11265. RHS.FloatImag = APFloat(Real.getSemantics());
  11266. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  11267. return false;
  11268. assert(!(LHSReal && RHSReal) &&
  11269. "Cannot have both operands of a complex operation be real.");
  11270. switch (E->getOpcode()) {
  11271. default: return Error(E);
  11272. case BO_Add:
  11273. if (Result.isComplexFloat()) {
  11274. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  11275. APFloat::rmNearestTiesToEven);
  11276. if (LHSReal)
  11277. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  11278. else if (!RHSReal)
  11279. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  11280. APFloat::rmNearestTiesToEven);
  11281. } else {
  11282. Result.getComplexIntReal() += RHS.getComplexIntReal();
  11283. Result.getComplexIntImag() += RHS.getComplexIntImag();
  11284. }
  11285. break;
  11286. case BO_Sub:
  11287. if (Result.isComplexFloat()) {
  11288. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  11289. APFloat::rmNearestTiesToEven);
  11290. if (LHSReal) {
  11291. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  11292. Result.getComplexFloatImag().changeSign();
  11293. } else if (!RHSReal) {
  11294. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  11295. APFloat::rmNearestTiesToEven);
  11296. }
  11297. } else {
  11298. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  11299. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  11300. }
  11301. break;
  11302. case BO_Mul:
  11303. if (Result.isComplexFloat()) {
  11304. // This is an implementation of complex multiplication according to the
  11305. // constraints laid out in C11 Annex G. The implementation uses the
  11306. // following naming scheme:
  11307. // (a + ib) * (c + id)
  11308. ComplexValue LHS = Result;
  11309. APFloat &A = LHS.getComplexFloatReal();
  11310. APFloat &B = LHS.getComplexFloatImag();
  11311. APFloat &C = RHS.getComplexFloatReal();
  11312. APFloat &D = RHS.getComplexFloatImag();
  11313. APFloat &ResR = Result.getComplexFloatReal();
  11314. APFloat &ResI = Result.getComplexFloatImag();
  11315. if (LHSReal) {
  11316. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  11317. ResR = A * C;
  11318. ResI = A * D;
  11319. } else if (RHSReal) {
  11320. ResR = C * A;
  11321. ResI = C * B;
  11322. } else {
  11323. // In the fully general case, we need to handle NaNs and infinities
  11324. // robustly.
  11325. APFloat AC = A * C;
  11326. APFloat BD = B * D;
  11327. APFloat AD = A * D;
  11328. APFloat BC = B * C;
  11329. ResR = AC - BD;
  11330. ResI = AD + BC;
  11331. if (ResR.isNaN() && ResI.isNaN()) {
  11332. bool Recalc = false;
  11333. if (A.isInfinity() || B.isInfinity()) {
  11334. A = APFloat::copySign(
  11335. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11336. B = APFloat::copySign(
  11337. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11338. if (C.isNaN())
  11339. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11340. if (D.isNaN())
  11341. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11342. Recalc = true;
  11343. }
  11344. if (C.isInfinity() || D.isInfinity()) {
  11345. C = APFloat::copySign(
  11346. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11347. D = APFloat::copySign(
  11348. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11349. if (A.isNaN())
  11350. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11351. if (B.isNaN())
  11352. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11353. Recalc = true;
  11354. }
  11355. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  11356. AD.isInfinity() || BC.isInfinity())) {
  11357. if (A.isNaN())
  11358. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11359. if (B.isNaN())
  11360. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11361. if (C.isNaN())
  11362. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11363. if (D.isNaN())
  11364. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11365. Recalc = true;
  11366. }
  11367. if (Recalc) {
  11368. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  11369. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  11370. }
  11371. }
  11372. }
  11373. } else {
  11374. ComplexValue LHS = Result;
  11375. Result.getComplexIntReal() =
  11376. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  11377. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  11378. Result.getComplexIntImag() =
  11379. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  11380. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  11381. }
  11382. break;
  11383. case BO_Div:
  11384. if (Result.isComplexFloat()) {
  11385. // This is an implementation of complex division according to the
  11386. // constraints laid out in C11 Annex G. The implementation uses the
  11387. // following naming scheme:
  11388. // (a + ib) / (c + id)
  11389. ComplexValue LHS = Result;
  11390. APFloat &A = LHS.getComplexFloatReal();
  11391. APFloat &B = LHS.getComplexFloatImag();
  11392. APFloat &C = RHS.getComplexFloatReal();
  11393. APFloat &D = RHS.getComplexFloatImag();
  11394. APFloat &ResR = Result.getComplexFloatReal();
  11395. APFloat &ResI = Result.getComplexFloatImag();
  11396. if (RHSReal) {
  11397. ResR = A / C;
  11398. ResI = B / C;
  11399. } else {
  11400. if (LHSReal) {
  11401. // No real optimizations we can do here, stub out with zero.
  11402. B = APFloat::getZero(A.getSemantics());
  11403. }
  11404. int DenomLogB = 0;
  11405. APFloat MaxCD = maxnum(abs(C), abs(D));
  11406. if (MaxCD.isFinite()) {
  11407. DenomLogB = ilogb(MaxCD);
  11408. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  11409. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  11410. }
  11411. APFloat Denom = C * C + D * D;
  11412. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  11413. APFloat::rmNearestTiesToEven);
  11414. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  11415. APFloat::rmNearestTiesToEven);
  11416. if (ResR.isNaN() && ResI.isNaN()) {
  11417. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  11418. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  11419. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  11420. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  11421. D.isFinite()) {
  11422. A = APFloat::copySign(
  11423. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11424. B = APFloat::copySign(
  11425. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11426. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  11427. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  11428. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  11429. C = APFloat::copySign(
  11430. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11431. D = APFloat::copySign(
  11432. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11433. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  11434. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  11435. }
  11436. }
  11437. }
  11438. } else {
  11439. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  11440. return Error(E, diag::note_expr_divide_by_zero);
  11441. ComplexValue LHS = Result;
  11442. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11443. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  11444. Result.getComplexIntReal() =
  11445. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11446. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  11447. Result.getComplexIntImag() =
  11448. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  11449. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  11450. }
  11451. break;
  11452. }
  11453. return true;
  11454. }
  11455. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11456. // Get the operand value into 'Result'.
  11457. if (!Visit(E->getSubExpr()))
  11458. return false;
  11459. switch (E->getOpcode()) {
  11460. default:
  11461. return Error(E);
  11462. case UO_Extension:
  11463. return true;
  11464. case UO_Plus:
  11465. // The result is always just the subexpr.
  11466. return true;
  11467. case UO_Minus:
  11468. if (Result.isComplexFloat()) {
  11469. Result.getComplexFloatReal().changeSign();
  11470. Result.getComplexFloatImag().changeSign();
  11471. }
  11472. else {
  11473. Result.getComplexIntReal() = -Result.getComplexIntReal();
  11474. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11475. }
  11476. return true;
  11477. case UO_Not:
  11478. if (Result.isComplexFloat())
  11479. Result.getComplexFloatImag().changeSign();
  11480. else
  11481. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11482. return true;
  11483. }
  11484. }
  11485. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  11486. if (E->getNumInits() == 2) {
  11487. if (E->getType()->isComplexType()) {
  11488. Result.makeComplexFloat();
  11489. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  11490. return false;
  11491. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  11492. return false;
  11493. } else {
  11494. Result.makeComplexInt();
  11495. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  11496. return false;
  11497. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  11498. return false;
  11499. }
  11500. return true;
  11501. }
  11502. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  11503. }
  11504. //===----------------------------------------------------------------------===//
  11505. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  11506. // implicit conversion.
  11507. //===----------------------------------------------------------------------===//
  11508. namespace {
  11509. class AtomicExprEvaluator :
  11510. public ExprEvaluatorBase<AtomicExprEvaluator> {
  11511. const LValue *This;
  11512. APValue &Result;
  11513. public:
  11514. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  11515. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  11516. bool Success(const APValue &V, const Expr *E) {
  11517. Result = V;
  11518. return true;
  11519. }
  11520. bool ZeroInitialization(const Expr *E) {
  11521. ImplicitValueInitExpr VIE(
  11522. E->getType()->castAs<AtomicType>()->getValueType());
  11523. // For atomic-qualified class (and array) types in C++, initialize the
  11524. // _Atomic-wrapped subobject directly, in-place.
  11525. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  11526. : Evaluate(Result, Info, &VIE);
  11527. }
  11528. bool VisitCastExpr(const CastExpr *E) {
  11529. switch (E->getCastKind()) {
  11530. default:
  11531. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11532. case CK_NonAtomicToAtomic:
  11533. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  11534. : Evaluate(Result, Info, E->getSubExpr());
  11535. }
  11536. }
  11537. };
  11538. } // end anonymous namespace
  11539. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  11540. EvalInfo &Info) {
  11541. assert(E->isRValue() && E->getType()->isAtomicType());
  11542. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  11543. }
  11544. //===----------------------------------------------------------------------===//
  11545. // Void expression evaluation, primarily for a cast to void on the LHS of a
  11546. // comma operator
  11547. //===----------------------------------------------------------------------===//
  11548. namespace {
  11549. class VoidExprEvaluator
  11550. : public ExprEvaluatorBase<VoidExprEvaluator> {
  11551. public:
  11552. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  11553. bool Success(const APValue &V, const Expr *e) { return true; }
  11554. bool ZeroInitialization(const Expr *E) { return true; }
  11555. bool VisitCastExpr(const CastExpr *E) {
  11556. switch (E->getCastKind()) {
  11557. default:
  11558. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11559. case CK_ToVoid:
  11560. VisitIgnoredValue(E->getSubExpr());
  11561. return true;
  11562. }
  11563. }
  11564. bool VisitCallExpr(const CallExpr *E) {
  11565. switch (E->getBuiltinCallee()) {
  11566. case Builtin::BI__assume:
  11567. case Builtin::BI__builtin_assume:
  11568. // The argument is not evaluated!
  11569. return true;
  11570. case Builtin::BI__builtin_operator_delete:
  11571. return HandleOperatorDeleteCall(Info, E);
  11572. default:
  11573. break;
  11574. }
  11575. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  11576. }
  11577. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  11578. };
  11579. } // end anonymous namespace
  11580. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  11581. // We cannot speculatively evaluate a delete expression.
  11582. if (Info.SpeculativeEvaluationDepth)
  11583. return false;
  11584. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  11585. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  11586. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  11587. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  11588. return false;
  11589. }
  11590. const Expr *Arg = E->getArgument();
  11591. LValue Pointer;
  11592. if (!EvaluatePointer(Arg, Pointer, Info))
  11593. return false;
  11594. if (Pointer.Designator.Invalid)
  11595. return false;
  11596. // Deleting a null pointer has no effect.
  11597. if (Pointer.isNullPointer()) {
  11598. // This is the only case where we need to produce an extension warning:
  11599. // the only other way we can succeed is if we find a dynamic allocation,
  11600. // and we will have warned when we allocated it in that case.
  11601. if (!Info.getLangOpts().CPlusPlus2a)
  11602. Info.CCEDiag(E, diag::note_constexpr_new);
  11603. return true;
  11604. }
  11605. Optional<DynAlloc *> Alloc = CheckDeleteKind(
  11606. Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
  11607. if (!Alloc)
  11608. return false;
  11609. QualType AllocType = Pointer.Base.getDynamicAllocType();
  11610. // For the non-array case, the designator must be empty if the static type
  11611. // does not have a virtual destructor.
  11612. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  11613. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  11614. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  11615. << Arg->getType()->getPointeeType() << AllocType;
  11616. return false;
  11617. }
  11618. if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
  11619. (*Alloc)->Value, AllocType))
  11620. return false;
  11621. if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
  11622. // The element was already erased. This means the destructor call also
  11623. // deleted the object.
  11624. // FIXME: This probably results in undefined behavior before we get this
  11625. // far, and should be diagnosed elsewhere first.
  11626. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11627. return false;
  11628. }
  11629. return true;
  11630. }
  11631. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  11632. assert(E->isRValue() && E->getType()->isVoidType());
  11633. return VoidExprEvaluator(Info).Visit(E);
  11634. }
  11635. //===----------------------------------------------------------------------===//
  11636. // Top level Expr::EvaluateAsRValue method.
  11637. //===----------------------------------------------------------------------===//
  11638. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  11639. // In C, function designators are not lvalues, but we evaluate them as if they
  11640. // are.
  11641. QualType T = E->getType();
  11642. if (E->isGLValue() || T->isFunctionType()) {
  11643. LValue LV;
  11644. if (!EvaluateLValue(E, LV, Info))
  11645. return false;
  11646. LV.moveInto(Result);
  11647. } else if (T->isVectorType()) {
  11648. if (!EvaluateVector(E, Result, Info))
  11649. return false;
  11650. } else if (T->isIntegralOrEnumerationType()) {
  11651. if (!IntExprEvaluator(Info, Result).Visit(E))
  11652. return false;
  11653. } else if (T->hasPointerRepresentation()) {
  11654. LValue LV;
  11655. if (!EvaluatePointer(E, LV, Info))
  11656. return false;
  11657. LV.moveInto(Result);
  11658. } else if (T->isRealFloatingType()) {
  11659. llvm::APFloat F(0.0);
  11660. if (!EvaluateFloat(E, F, Info))
  11661. return false;
  11662. Result = APValue(F);
  11663. } else if (T->isAnyComplexType()) {
  11664. ComplexValue C;
  11665. if (!EvaluateComplex(E, C, Info))
  11666. return false;
  11667. C.moveInto(Result);
  11668. } else if (T->isFixedPointType()) {
  11669. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  11670. } else if (T->isMemberPointerType()) {
  11671. MemberPtr P;
  11672. if (!EvaluateMemberPointer(E, P, Info))
  11673. return false;
  11674. P.moveInto(Result);
  11675. return true;
  11676. } else if (T->isArrayType()) {
  11677. LValue LV;
  11678. APValue &Value =
  11679. Info.CurrentCall->createTemporary(E, T, false, LV);
  11680. if (!EvaluateArray(E, LV, Value, Info))
  11681. return false;
  11682. Result = Value;
  11683. } else if (T->isRecordType()) {
  11684. LValue LV;
  11685. APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
  11686. if (!EvaluateRecord(E, LV, Value, Info))
  11687. return false;
  11688. Result = Value;
  11689. } else if (T->isVoidType()) {
  11690. if (!Info.getLangOpts().CPlusPlus11)
  11691. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  11692. << E->getType();
  11693. if (!EvaluateVoid(E, Info))
  11694. return false;
  11695. } else if (T->isAtomicType()) {
  11696. QualType Unqual = T.getAtomicUnqualifiedType();
  11697. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  11698. LValue LV;
  11699. APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
  11700. if (!EvaluateAtomic(E, &LV, Value, Info))
  11701. return false;
  11702. } else {
  11703. if (!EvaluateAtomic(E, nullptr, Result, Info))
  11704. return false;
  11705. }
  11706. } else if (Info.getLangOpts().CPlusPlus11) {
  11707. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  11708. return false;
  11709. } else {
  11710. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11711. return false;
  11712. }
  11713. return true;
  11714. }
  11715. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  11716. /// cases, the in-place evaluation is essential, since later initializers for
  11717. /// an object can indirectly refer to subobjects which were initialized earlier.
  11718. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  11719. const Expr *E, bool AllowNonLiteralTypes) {
  11720. assert(!E->isValueDependent());
  11721. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  11722. return false;
  11723. if (E->isRValue()) {
  11724. // Evaluate arrays and record types in-place, so that later initializers can
  11725. // refer to earlier-initialized members of the object.
  11726. QualType T = E->getType();
  11727. if (T->isArrayType())
  11728. return EvaluateArray(E, This, Result, Info);
  11729. else if (T->isRecordType())
  11730. return EvaluateRecord(E, This, Result, Info);
  11731. else if (T->isAtomicType()) {
  11732. QualType Unqual = T.getAtomicUnqualifiedType();
  11733. if (Unqual->isArrayType() || Unqual->isRecordType())
  11734. return EvaluateAtomic(E, &This, Result, Info);
  11735. }
  11736. }
  11737. // For any other type, in-place evaluation is unimportant.
  11738. return Evaluate(Result, Info, E);
  11739. }
  11740. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  11741. /// lvalue-to-rvalue cast if it is an lvalue.
  11742. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  11743. if (Info.EnableNewConstInterp) {
  11744. auto &InterpCtx = Info.Ctx.getInterpContext();
  11745. switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
  11746. case interp::InterpResult::Success:
  11747. return true;
  11748. case interp::InterpResult::Fail:
  11749. return false;
  11750. case interp::InterpResult::Bail:
  11751. break;
  11752. }
  11753. }
  11754. if (E->getType().isNull())
  11755. return false;
  11756. if (!CheckLiteralType(Info, E))
  11757. return false;
  11758. if (!::Evaluate(Result, Info, E))
  11759. return false;
  11760. if (E->isGLValue()) {
  11761. LValue LV;
  11762. LV.setFrom(Info.Ctx, Result);
  11763. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11764. return false;
  11765. }
  11766. // Check this core constant expression is a constant expression.
  11767. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
  11768. CheckMemoryLeaks(Info);
  11769. }
  11770. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  11771. const ASTContext &Ctx, bool &IsConst) {
  11772. // Fast-path evaluations of integer literals, since we sometimes see files
  11773. // containing vast quantities of these.
  11774. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  11775. Result.Val = APValue(APSInt(L->getValue(),
  11776. L->getType()->isUnsignedIntegerType()));
  11777. IsConst = true;
  11778. return true;
  11779. }
  11780. // This case should be rare, but we need to check it before we check on
  11781. // the type below.
  11782. if (Exp->getType().isNull()) {
  11783. IsConst = false;
  11784. return true;
  11785. }
  11786. // FIXME: Evaluating values of large array and record types can cause
  11787. // performance problems. Only do so in C++11 for now.
  11788. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  11789. Exp->getType()->isRecordType()) &&
  11790. !Ctx.getLangOpts().CPlusPlus11) {
  11791. IsConst = false;
  11792. return true;
  11793. }
  11794. return false;
  11795. }
  11796. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  11797. Expr::SideEffectsKind SEK) {
  11798. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  11799. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  11800. }
  11801. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  11802. const ASTContext &Ctx, EvalInfo &Info) {
  11803. bool IsConst;
  11804. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  11805. return IsConst;
  11806. return EvaluateAsRValue(Info, E, Result.Val);
  11807. }
  11808. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  11809. const ASTContext &Ctx,
  11810. Expr::SideEffectsKind AllowSideEffects,
  11811. EvalInfo &Info) {
  11812. if (!E->getType()->isIntegralOrEnumerationType())
  11813. return false;
  11814. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  11815. !ExprResult.Val.isInt() ||
  11816. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11817. return false;
  11818. return true;
  11819. }
  11820. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  11821. const ASTContext &Ctx,
  11822. Expr::SideEffectsKind AllowSideEffects,
  11823. EvalInfo &Info) {
  11824. if (!E->getType()->isFixedPointType())
  11825. return false;
  11826. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  11827. return false;
  11828. if (!ExprResult.Val.isFixedPoint() ||
  11829. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11830. return false;
  11831. return true;
  11832. }
  11833. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  11834. /// any crazy technique (that has nothing to do with language standards) that
  11835. /// we want to. If this function returns true, it returns the folded constant
  11836. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  11837. /// will be applied to the result.
  11838. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  11839. bool InConstantContext) const {
  11840. assert(!isValueDependent() &&
  11841. "Expression evaluator can't be called on a dependent expression.");
  11842. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11843. Info.InConstantContext = InConstantContext;
  11844. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  11845. }
  11846. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  11847. bool InConstantContext) const {
  11848. assert(!isValueDependent() &&
  11849. "Expression evaluator can't be called on a dependent expression.");
  11850. EvalResult Scratch;
  11851. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  11852. HandleConversionToBool(Scratch.Val, Result);
  11853. }
  11854. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  11855. SideEffectsKind AllowSideEffects,
  11856. bool InConstantContext) const {
  11857. assert(!isValueDependent() &&
  11858. "Expression evaluator can't be called on a dependent expression.");
  11859. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11860. Info.InConstantContext = InConstantContext;
  11861. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  11862. }
  11863. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  11864. SideEffectsKind AllowSideEffects,
  11865. bool InConstantContext) const {
  11866. assert(!isValueDependent() &&
  11867. "Expression evaluator can't be called on a dependent expression.");
  11868. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11869. Info.InConstantContext = InConstantContext;
  11870. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  11871. }
  11872. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  11873. SideEffectsKind AllowSideEffects,
  11874. bool InConstantContext) const {
  11875. assert(!isValueDependent() &&
  11876. "Expression evaluator can't be called on a dependent expression.");
  11877. if (!getType()->isRealFloatingType())
  11878. return false;
  11879. EvalResult ExprResult;
  11880. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  11881. !ExprResult.Val.isFloat() ||
  11882. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11883. return false;
  11884. Result = ExprResult.Val.getFloat();
  11885. return true;
  11886. }
  11887. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  11888. bool InConstantContext) const {
  11889. assert(!isValueDependent() &&
  11890. "Expression evaluator can't be called on a dependent expression.");
  11891. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  11892. Info.InConstantContext = InConstantContext;
  11893. LValue LV;
  11894. CheckedTemporaries CheckedTemps;
  11895. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  11896. Result.HasSideEffects ||
  11897. !CheckLValueConstantExpression(Info, getExprLoc(),
  11898. Ctx.getLValueReferenceType(getType()), LV,
  11899. Expr::EvaluateForCodeGen, CheckedTemps))
  11900. return false;
  11901. LV.moveInto(Result.Val);
  11902. return true;
  11903. }
  11904. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  11905. const ASTContext &Ctx) const {
  11906. assert(!isValueDependent() &&
  11907. "Expression evaluator can't be called on a dependent expression.");
  11908. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  11909. EvalInfo Info(Ctx, Result, EM);
  11910. Info.InConstantContext = true;
  11911. if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
  11912. return false;
  11913. if (!Info.discardCleanups())
  11914. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11915. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  11916. Usage) &&
  11917. CheckMemoryLeaks(Info);
  11918. }
  11919. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  11920. const VarDecl *VD,
  11921. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11922. assert(!isValueDependent() &&
  11923. "Expression evaluator can't be called on a dependent expression.");
  11924. // FIXME: Evaluating initializers for large array and record types can cause
  11925. // performance problems. Only do so in C++11 for now.
  11926. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  11927. !Ctx.getLangOpts().CPlusPlus11)
  11928. return false;
  11929. Expr::EvalStatus EStatus;
  11930. EStatus.Diag = &Notes;
  11931. EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
  11932. ? EvalInfo::EM_ConstantExpression
  11933. : EvalInfo::EM_ConstantFold);
  11934. Info.setEvaluatingDecl(VD, Value);
  11935. Info.InConstantContext = true;
  11936. SourceLocation DeclLoc = VD->getLocation();
  11937. QualType DeclTy = VD->getType();
  11938. if (Info.EnableNewConstInterp) {
  11939. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  11940. switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
  11941. case interp::InterpResult::Fail:
  11942. // Bail out if an error was encountered.
  11943. return false;
  11944. case interp::InterpResult::Success:
  11945. // Evaluation succeeded and value was set.
  11946. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  11947. case interp::InterpResult::Bail:
  11948. // Evaluate the value again for the tree evaluator to use.
  11949. break;
  11950. }
  11951. }
  11952. LValue LVal;
  11953. LVal.set(VD);
  11954. // C++11 [basic.start.init]p2:
  11955. // Variables with static storage duration or thread storage duration shall be
  11956. // zero-initialized before any other initialization takes place.
  11957. // This behavior is not present in C.
  11958. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  11959. !DeclTy->isReferenceType()) {
  11960. ImplicitValueInitExpr VIE(DeclTy);
  11961. if (!EvaluateInPlace(Value, Info, LVal, &VIE,
  11962. /*AllowNonLiteralTypes=*/true))
  11963. return false;
  11964. }
  11965. if (!EvaluateInPlace(Value, Info, LVal, this,
  11966. /*AllowNonLiteralTypes=*/true) ||
  11967. EStatus.HasSideEffects)
  11968. return false;
  11969. // At this point, any lifetime-extended temporaries are completely
  11970. // initialized.
  11971. Info.performLifetimeExtension();
  11972. if (!Info.discardCleanups())
  11973. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11974. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
  11975. CheckMemoryLeaks(Info);
  11976. }
  11977. bool VarDecl::evaluateDestruction(
  11978. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11979. assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
  11980. "cannot evaluate destruction of non-constant-initialized variable");
  11981. Expr::EvalStatus EStatus;
  11982. EStatus.Diag = &Notes;
  11983. // Make a copy of the value for the destructor to mutate.
  11984. APValue DestroyedValue = *getEvaluatedValue();
  11985. EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
  11986. Info.setEvaluatingDecl(this, DestroyedValue,
  11987. EvalInfo::EvaluatingDeclKind::Dtor);
  11988. Info.InConstantContext = true;
  11989. SourceLocation DeclLoc = getLocation();
  11990. QualType DeclTy = getType();
  11991. LValue LVal;
  11992. LVal.set(this);
  11993. // FIXME: Consider storing whether this variable has constant destruction in
  11994. // the EvaluatedStmt so that CodeGen can query it.
  11995. if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
  11996. EStatus.HasSideEffects)
  11997. return false;
  11998. if (!Info.discardCleanups())
  11999. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  12000. ensureEvaluatedStmt()->HasConstantDestruction = true;
  12001. return true;
  12002. }
  12003. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  12004. /// constant folded, but discard the result.
  12005. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  12006. assert(!isValueDependent() &&
  12007. "Expression evaluator can't be called on a dependent expression.");
  12008. EvalResult Result;
  12009. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  12010. !hasUnacceptableSideEffect(Result, SEK);
  12011. }
  12012. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  12013. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  12014. assert(!isValueDependent() &&
  12015. "Expression evaluator can't be called on a dependent expression.");
  12016. EvalResult EVResult;
  12017. EVResult.Diag = Diag;
  12018. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  12019. Info.InConstantContext = true;
  12020. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  12021. (void)Result;
  12022. assert(Result && "Could not evaluate expression");
  12023. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  12024. return EVResult.Val.getInt();
  12025. }
  12026. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  12027. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  12028. assert(!isValueDependent() &&
  12029. "Expression evaluator can't be called on a dependent expression.");
  12030. EvalResult EVResult;
  12031. EVResult.Diag = Diag;
  12032. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  12033. Info.InConstantContext = true;
  12034. Info.CheckingForUndefinedBehavior = true;
  12035. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  12036. (void)Result;
  12037. assert(Result && "Could not evaluate expression");
  12038. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  12039. return EVResult.Val.getInt();
  12040. }
  12041. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  12042. assert(!isValueDependent() &&
  12043. "Expression evaluator can't be called on a dependent expression.");
  12044. bool IsConst;
  12045. EvalResult EVResult;
  12046. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  12047. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  12048. Info.CheckingForUndefinedBehavior = true;
  12049. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  12050. }
  12051. }
  12052. bool Expr::EvalResult::isGlobalLValue() const {
  12053. assert(Val.isLValue());
  12054. return IsGlobalLValue(Val.getLValueBase());
  12055. }
  12056. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  12057. /// an integer constant expression.
  12058. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  12059. /// comma, etc
  12060. // CheckICE - This function does the fundamental ICE checking: the returned
  12061. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  12062. // and a (possibly null) SourceLocation indicating the location of the problem.
  12063. //
  12064. // Note that to reduce code duplication, this helper does no evaluation
  12065. // itself; the caller checks whether the expression is evaluatable, and
  12066. // in the rare cases where CheckICE actually cares about the evaluated
  12067. // value, it calls into Evaluate.
  12068. namespace {
  12069. enum ICEKind {
  12070. /// This expression is an ICE.
  12071. IK_ICE,
  12072. /// This expression is not an ICE, but if it isn't evaluated, it's
  12073. /// a legal subexpression for an ICE. This return value is used to handle
  12074. /// the comma operator in C99 mode, and non-constant subexpressions.
  12075. IK_ICEIfUnevaluated,
  12076. /// This expression is not an ICE, and is not a legal subexpression for one.
  12077. IK_NotICE
  12078. };
  12079. struct ICEDiag {
  12080. ICEKind Kind;
  12081. SourceLocation Loc;
  12082. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  12083. };
  12084. }
  12085. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  12086. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  12087. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  12088. Expr::EvalResult EVResult;
  12089. Expr::EvalStatus Status;
  12090. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12091. Info.InConstantContext = true;
  12092. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  12093. !EVResult.Val.isInt())
  12094. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12095. return NoDiag();
  12096. }
  12097. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  12098. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  12099. if (!E->getType()->isIntegralOrEnumerationType())
  12100. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12101. switch (E->getStmtClass()) {
  12102. #define ABSTRACT_STMT(Node)
  12103. #define STMT(Node, Base) case Expr::Node##Class:
  12104. #define EXPR(Node, Base)
  12105. #include "clang/AST/StmtNodes.inc"
  12106. case Expr::PredefinedExprClass:
  12107. case Expr::FloatingLiteralClass:
  12108. case Expr::ImaginaryLiteralClass:
  12109. case Expr::StringLiteralClass:
  12110. case Expr::ArraySubscriptExprClass:
  12111. case Expr::OMPArraySectionExprClass:
  12112. case Expr::MemberExprClass:
  12113. case Expr::CompoundAssignOperatorClass:
  12114. case Expr::CompoundLiteralExprClass:
  12115. case Expr::ExtVectorElementExprClass:
  12116. case Expr::DesignatedInitExprClass:
  12117. case Expr::ArrayInitLoopExprClass:
  12118. case Expr::ArrayInitIndexExprClass:
  12119. case Expr::NoInitExprClass:
  12120. case Expr::DesignatedInitUpdateExprClass:
  12121. case Expr::ImplicitValueInitExprClass:
  12122. case Expr::ParenListExprClass:
  12123. case Expr::VAArgExprClass:
  12124. case Expr::AddrLabelExprClass:
  12125. case Expr::StmtExprClass:
  12126. case Expr::CXXMemberCallExprClass:
  12127. case Expr::CUDAKernelCallExprClass:
  12128. case Expr::CXXDynamicCastExprClass:
  12129. case Expr::CXXTypeidExprClass:
  12130. case Expr::CXXUuidofExprClass:
  12131. case Expr::MSPropertyRefExprClass:
  12132. case Expr::MSPropertySubscriptExprClass:
  12133. case Expr::CXXNullPtrLiteralExprClass:
  12134. case Expr::UserDefinedLiteralClass:
  12135. case Expr::CXXThisExprClass:
  12136. case Expr::CXXThrowExprClass:
  12137. case Expr::CXXNewExprClass:
  12138. case Expr::CXXDeleteExprClass:
  12139. case Expr::CXXPseudoDestructorExprClass:
  12140. case Expr::UnresolvedLookupExprClass:
  12141. case Expr::TypoExprClass:
  12142. case Expr::DependentScopeDeclRefExprClass:
  12143. case Expr::CXXConstructExprClass:
  12144. case Expr::CXXInheritedCtorInitExprClass:
  12145. case Expr::CXXStdInitializerListExprClass:
  12146. case Expr::CXXBindTemporaryExprClass:
  12147. case Expr::ExprWithCleanupsClass:
  12148. case Expr::CXXTemporaryObjectExprClass:
  12149. case Expr::CXXUnresolvedConstructExprClass:
  12150. case Expr::CXXDependentScopeMemberExprClass:
  12151. case Expr::UnresolvedMemberExprClass:
  12152. case Expr::ObjCStringLiteralClass:
  12153. case Expr::ObjCBoxedExprClass:
  12154. case Expr::ObjCArrayLiteralClass:
  12155. case Expr::ObjCDictionaryLiteralClass:
  12156. case Expr::ObjCEncodeExprClass:
  12157. case Expr::ObjCMessageExprClass:
  12158. case Expr::ObjCSelectorExprClass:
  12159. case Expr::ObjCProtocolExprClass:
  12160. case Expr::ObjCIvarRefExprClass:
  12161. case Expr::ObjCPropertyRefExprClass:
  12162. case Expr::ObjCSubscriptRefExprClass:
  12163. case Expr::ObjCIsaExprClass:
  12164. case Expr::ObjCAvailabilityCheckExprClass:
  12165. case Expr::ShuffleVectorExprClass:
  12166. case Expr::ConvertVectorExprClass:
  12167. case Expr::BlockExprClass:
  12168. case Expr::NoStmtClass:
  12169. case Expr::OpaqueValueExprClass:
  12170. case Expr::PackExpansionExprClass:
  12171. case Expr::SubstNonTypeTemplateParmPackExprClass:
  12172. case Expr::FunctionParmPackExprClass:
  12173. case Expr::AsTypeExprClass:
  12174. case Expr::ObjCIndirectCopyRestoreExprClass:
  12175. case Expr::MaterializeTemporaryExprClass:
  12176. case Expr::PseudoObjectExprClass:
  12177. case Expr::AtomicExprClass:
  12178. case Expr::LambdaExprClass:
  12179. case Expr::CXXFoldExprClass:
  12180. case Expr::CoawaitExprClass:
  12181. case Expr::DependentCoawaitExprClass:
  12182. case Expr::CoyieldExprClass:
  12183. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12184. case Expr::InitListExprClass: {
  12185. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  12186. // form "T x = { a };" is equivalent to "T x = a;".
  12187. // Unless we're initializing a reference, T is a scalar as it is known to be
  12188. // of integral or enumeration type.
  12189. if (E->isRValue())
  12190. if (cast<InitListExpr>(E)->getNumInits() == 1)
  12191. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  12192. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12193. }
  12194. case Expr::SizeOfPackExprClass:
  12195. case Expr::GNUNullExprClass:
  12196. case Expr::SourceLocExprClass:
  12197. return NoDiag();
  12198. case Expr::SubstNonTypeTemplateParmExprClass:
  12199. return
  12200. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  12201. case Expr::ConstantExprClass:
  12202. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  12203. case Expr::ParenExprClass:
  12204. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  12205. case Expr::GenericSelectionExprClass:
  12206. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  12207. case Expr::IntegerLiteralClass:
  12208. case Expr::FixedPointLiteralClass:
  12209. case Expr::CharacterLiteralClass:
  12210. case Expr::ObjCBoolLiteralExprClass:
  12211. case Expr::CXXBoolLiteralExprClass:
  12212. case Expr::CXXScalarValueInitExprClass:
  12213. case Expr::TypeTraitExprClass:
  12214. case Expr::ArrayTypeTraitExprClass:
  12215. case Expr::ExpressionTraitExprClass:
  12216. case Expr::CXXNoexceptExprClass:
  12217. return NoDiag();
  12218. case Expr::CallExprClass:
  12219. case Expr::CXXOperatorCallExprClass: {
  12220. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  12221. // constant expressions, but they can never be ICEs because an ICE cannot
  12222. // contain an operand of (pointer to) function type.
  12223. const CallExpr *CE = cast<CallExpr>(E);
  12224. if (CE->getBuiltinCallee())
  12225. return CheckEvalInICE(E, Ctx);
  12226. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12227. }
  12228. case Expr::DeclRefExprClass: {
  12229. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  12230. return NoDiag();
  12231. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  12232. if (Ctx.getLangOpts().CPlusPlus &&
  12233. D && IsConstNonVolatile(D->getType())) {
  12234. // Parameter variables are never constants. Without this check,
  12235. // getAnyInitializer() can find a default argument, which leads
  12236. // to chaos.
  12237. if (isa<ParmVarDecl>(D))
  12238. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12239. // C++ 7.1.5.1p2
  12240. // A variable of non-volatile const-qualified integral or enumeration
  12241. // type initialized by an ICE can be used in ICEs.
  12242. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  12243. if (!Dcl->getType()->isIntegralOrEnumerationType())
  12244. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12245. const VarDecl *VD;
  12246. // Look for a declaration of this variable that has an initializer, and
  12247. // check whether it is an ICE.
  12248. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  12249. return NoDiag();
  12250. else
  12251. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12252. }
  12253. }
  12254. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12255. }
  12256. case Expr::UnaryOperatorClass: {
  12257. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  12258. switch (Exp->getOpcode()) {
  12259. case UO_PostInc:
  12260. case UO_PostDec:
  12261. case UO_PreInc:
  12262. case UO_PreDec:
  12263. case UO_AddrOf:
  12264. case UO_Deref:
  12265. case UO_Coawait:
  12266. // C99 6.6/3 allows increment and decrement within unevaluated
  12267. // subexpressions of constant expressions, but they can never be ICEs
  12268. // because an ICE cannot contain an lvalue operand.
  12269. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12270. case UO_Extension:
  12271. case UO_LNot:
  12272. case UO_Plus:
  12273. case UO_Minus:
  12274. case UO_Not:
  12275. case UO_Real:
  12276. case UO_Imag:
  12277. return CheckICE(Exp->getSubExpr(), Ctx);
  12278. }
  12279. llvm_unreachable("invalid unary operator class");
  12280. }
  12281. case Expr::OffsetOfExprClass: {
  12282. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  12283. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  12284. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  12285. // compliance: we should warn earlier for offsetof expressions with
  12286. // array subscripts that aren't ICEs, and if the array subscripts
  12287. // are ICEs, the value of the offsetof must be an integer constant.
  12288. return CheckEvalInICE(E, Ctx);
  12289. }
  12290. case Expr::UnaryExprOrTypeTraitExprClass: {
  12291. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  12292. if ((Exp->getKind() == UETT_SizeOf) &&
  12293. Exp->getTypeOfArgument()->isVariableArrayType())
  12294. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12295. return NoDiag();
  12296. }
  12297. case Expr::BinaryOperatorClass: {
  12298. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  12299. switch (Exp->getOpcode()) {
  12300. case BO_PtrMemD:
  12301. case BO_PtrMemI:
  12302. case BO_Assign:
  12303. case BO_MulAssign:
  12304. case BO_DivAssign:
  12305. case BO_RemAssign:
  12306. case BO_AddAssign:
  12307. case BO_SubAssign:
  12308. case BO_ShlAssign:
  12309. case BO_ShrAssign:
  12310. case BO_AndAssign:
  12311. case BO_XorAssign:
  12312. case BO_OrAssign:
  12313. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  12314. // constant expressions, but they can never be ICEs because an ICE cannot
  12315. // contain an lvalue operand.
  12316. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12317. case BO_Mul:
  12318. case BO_Div:
  12319. case BO_Rem:
  12320. case BO_Add:
  12321. case BO_Sub:
  12322. case BO_Shl:
  12323. case BO_Shr:
  12324. case BO_LT:
  12325. case BO_GT:
  12326. case BO_LE:
  12327. case BO_GE:
  12328. case BO_EQ:
  12329. case BO_NE:
  12330. case BO_And:
  12331. case BO_Xor:
  12332. case BO_Or:
  12333. case BO_Comma:
  12334. case BO_Cmp: {
  12335. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12336. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12337. if (Exp->getOpcode() == BO_Div ||
  12338. Exp->getOpcode() == BO_Rem) {
  12339. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  12340. // we don't evaluate one.
  12341. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  12342. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  12343. if (REval == 0)
  12344. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12345. if (REval.isSigned() && REval.isAllOnesValue()) {
  12346. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  12347. if (LEval.isMinSignedValue())
  12348. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12349. }
  12350. }
  12351. }
  12352. if (Exp->getOpcode() == BO_Comma) {
  12353. if (Ctx.getLangOpts().C99) {
  12354. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  12355. // if it isn't evaluated.
  12356. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  12357. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12358. } else {
  12359. // In both C89 and C++, commas in ICEs are illegal.
  12360. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12361. }
  12362. }
  12363. return Worst(LHSResult, RHSResult);
  12364. }
  12365. case BO_LAnd:
  12366. case BO_LOr: {
  12367. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12368. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12369. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  12370. // Rare case where the RHS has a comma "side-effect"; we need
  12371. // to actually check the condition to see whether the side
  12372. // with the comma is evaluated.
  12373. if ((Exp->getOpcode() == BO_LAnd) !=
  12374. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  12375. return RHSResult;
  12376. return NoDiag();
  12377. }
  12378. return Worst(LHSResult, RHSResult);
  12379. }
  12380. }
  12381. llvm_unreachable("invalid binary operator kind");
  12382. }
  12383. case Expr::ImplicitCastExprClass:
  12384. case Expr::CStyleCastExprClass:
  12385. case Expr::CXXFunctionalCastExprClass:
  12386. case Expr::CXXStaticCastExprClass:
  12387. case Expr::CXXReinterpretCastExprClass:
  12388. case Expr::CXXConstCastExprClass:
  12389. case Expr::ObjCBridgedCastExprClass: {
  12390. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  12391. if (isa<ExplicitCastExpr>(E)) {
  12392. if (const FloatingLiteral *FL
  12393. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  12394. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  12395. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  12396. APSInt IgnoredVal(DestWidth, !DestSigned);
  12397. bool Ignored;
  12398. // If the value does not fit in the destination type, the behavior is
  12399. // undefined, so we are not required to treat it as a constant
  12400. // expression.
  12401. if (FL->getValue().convertToInteger(IgnoredVal,
  12402. llvm::APFloat::rmTowardZero,
  12403. &Ignored) & APFloat::opInvalidOp)
  12404. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12405. return NoDiag();
  12406. }
  12407. }
  12408. switch (cast<CastExpr>(E)->getCastKind()) {
  12409. case CK_LValueToRValue:
  12410. case CK_AtomicToNonAtomic:
  12411. case CK_NonAtomicToAtomic:
  12412. case CK_NoOp:
  12413. case CK_IntegralToBoolean:
  12414. case CK_IntegralCast:
  12415. return CheckICE(SubExpr, Ctx);
  12416. default:
  12417. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12418. }
  12419. }
  12420. case Expr::BinaryConditionalOperatorClass: {
  12421. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  12422. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  12423. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  12424. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12425. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  12426. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  12427. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  12428. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  12429. return FalseResult;
  12430. }
  12431. case Expr::ConditionalOperatorClass: {
  12432. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  12433. // If the condition (ignoring parens) is a __builtin_constant_p call,
  12434. // then only the true side is actually considered in an integer constant
  12435. // expression, and it is fully evaluated. This is an important GNU
  12436. // extension. See GCC PR38377 for discussion.
  12437. if (const CallExpr *CallCE
  12438. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  12439. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  12440. return CheckEvalInICE(E, Ctx);
  12441. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  12442. if (CondResult.Kind == IK_NotICE)
  12443. return CondResult;
  12444. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  12445. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12446. if (TrueResult.Kind == IK_NotICE)
  12447. return TrueResult;
  12448. if (FalseResult.Kind == IK_NotICE)
  12449. return FalseResult;
  12450. if (CondResult.Kind == IK_ICEIfUnevaluated)
  12451. return CondResult;
  12452. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  12453. return NoDiag();
  12454. // Rare case where the diagnostics depend on which side is evaluated
  12455. // Note that if we get here, CondResult is 0, and at least one of
  12456. // TrueResult and FalseResult is non-zero.
  12457. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  12458. return FalseResult;
  12459. return TrueResult;
  12460. }
  12461. case Expr::CXXDefaultArgExprClass:
  12462. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  12463. case Expr::CXXDefaultInitExprClass:
  12464. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  12465. case Expr::ChooseExprClass: {
  12466. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  12467. }
  12468. case Expr::BuiltinBitCastExprClass: {
  12469. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  12470. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12471. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  12472. }
  12473. }
  12474. llvm_unreachable("Invalid StmtClass!");
  12475. }
  12476. /// Evaluate an expression as a C++11 integral constant expression.
  12477. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  12478. const Expr *E,
  12479. llvm::APSInt *Value,
  12480. SourceLocation *Loc) {
  12481. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12482. if (Loc) *Loc = E->getExprLoc();
  12483. return false;
  12484. }
  12485. APValue Result;
  12486. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  12487. return false;
  12488. if (!Result.isInt()) {
  12489. if (Loc) *Loc = E->getExprLoc();
  12490. return false;
  12491. }
  12492. if (Value) *Value = Result.getInt();
  12493. return true;
  12494. }
  12495. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  12496. SourceLocation *Loc) const {
  12497. assert(!isValueDependent() &&
  12498. "Expression evaluator can't be called on a dependent expression.");
  12499. if (Ctx.getLangOpts().CPlusPlus11)
  12500. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  12501. ICEDiag D = CheckICE(this, Ctx);
  12502. if (D.Kind != IK_ICE) {
  12503. if (Loc) *Loc = D.Loc;
  12504. return false;
  12505. }
  12506. return true;
  12507. }
  12508. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  12509. SourceLocation *Loc, bool isEvaluated) const {
  12510. assert(!isValueDependent() &&
  12511. "Expression evaluator can't be called on a dependent expression.");
  12512. if (Ctx.getLangOpts().CPlusPlus11)
  12513. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  12514. if (!isIntegerConstantExpr(Ctx, Loc))
  12515. return false;
  12516. // The only possible side-effects here are due to UB discovered in the
  12517. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  12518. // required to treat the expression as an ICE, so we produce the folded
  12519. // value.
  12520. EvalResult ExprResult;
  12521. Expr::EvalStatus Status;
  12522. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  12523. Info.InConstantContext = true;
  12524. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  12525. llvm_unreachable("ICE cannot be evaluated!");
  12526. Value = ExprResult.Val.getInt();
  12527. return true;
  12528. }
  12529. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  12530. assert(!isValueDependent() &&
  12531. "Expression evaluator can't be called on a dependent expression.");
  12532. return CheckICE(this, Ctx).Kind == IK_ICE;
  12533. }
  12534. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  12535. SourceLocation *Loc) const {
  12536. assert(!isValueDependent() &&
  12537. "Expression evaluator can't be called on a dependent expression.");
  12538. // We support this checking in C++98 mode in order to diagnose compatibility
  12539. // issues.
  12540. assert(Ctx.getLangOpts().CPlusPlus);
  12541. // Build evaluation settings.
  12542. Expr::EvalStatus Status;
  12543. SmallVector<PartialDiagnosticAt, 8> Diags;
  12544. Status.Diag = &Diags;
  12545. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12546. APValue Scratch;
  12547. bool IsConstExpr =
  12548. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  12549. // FIXME: We don't produce a diagnostic for this, but the callers that
  12550. // call us on arbitrary full-expressions should generally not care.
  12551. Info.discardCleanups() && !Status.HasSideEffects;
  12552. if (!Diags.empty()) {
  12553. IsConstExpr = false;
  12554. if (Loc) *Loc = Diags[0].first;
  12555. } else if (!IsConstExpr) {
  12556. // FIXME: This shouldn't happen.
  12557. if (Loc) *Loc = getExprLoc();
  12558. }
  12559. return IsConstExpr;
  12560. }
  12561. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  12562. const FunctionDecl *Callee,
  12563. ArrayRef<const Expr*> Args,
  12564. const Expr *This) const {
  12565. assert(!isValueDependent() &&
  12566. "Expression evaluator can't be called on a dependent expression.");
  12567. Expr::EvalStatus Status;
  12568. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  12569. Info.InConstantContext = true;
  12570. LValue ThisVal;
  12571. const LValue *ThisPtr = nullptr;
  12572. if (This) {
  12573. #ifndef NDEBUG
  12574. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  12575. assert(MD && "Don't provide `this` for non-methods.");
  12576. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  12577. #endif
  12578. if (EvaluateObjectArgument(Info, This, ThisVal))
  12579. ThisPtr = &ThisVal;
  12580. if (Info.EvalStatus.HasSideEffects)
  12581. return false;
  12582. }
  12583. ArgVector ArgValues(Args.size());
  12584. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  12585. I != E; ++I) {
  12586. if ((*I)->isValueDependent() ||
  12587. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  12588. // If evaluation fails, throw away the argument entirely.
  12589. ArgValues[I - Args.begin()] = APValue();
  12590. if (Info.EvalStatus.HasSideEffects)
  12591. return false;
  12592. }
  12593. // Build fake call to Callee.
  12594. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  12595. ArgValues.data());
  12596. return Evaluate(Value, Info, this) && Info.discardCleanups() &&
  12597. !Info.EvalStatus.HasSideEffects;
  12598. }
  12599. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  12600. SmallVectorImpl<
  12601. PartialDiagnosticAt> &Diags) {
  12602. // FIXME: It would be useful to check constexpr function templates, but at the
  12603. // moment the constant expression evaluator cannot cope with the non-rigorous
  12604. // ASTs which we build for dependent expressions.
  12605. if (FD->isDependentContext())
  12606. return true;
  12607. Expr::EvalStatus Status;
  12608. Status.Diag = &Diags;
  12609. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  12610. Info.InConstantContext = true;
  12611. Info.CheckingPotentialConstantExpression = true;
  12612. // The constexpr VM attempts to compile all methods to bytecode here.
  12613. if (Info.EnableNewConstInterp) {
  12614. auto &InterpCtx = Info.Ctx.getInterpContext();
  12615. switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
  12616. case interp::InterpResult::Success:
  12617. case interp::InterpResult::Fail:
  12618. return Diags.empty();
  12619. case interp::InterpResult::Bail:
  12620. break;
  12621. }
  12622. }
  12623. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  12624. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  12625. // Fabricate an arbitrary expression on the stack and pretend that it
  12626. // is a temporary being used as the 'this' pointer.
  12627. LValue This;
  12628. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  12629. This.set({&VIE, Info.CurrentCall->Index});
  12630. ArrayRef<const Expr*> Args;
  12631. APValue Scratch;
  12632. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  12633. // Evaluate the call as a constant initializer, to allow the construction
  12634. // of objects of non-literal types.
  12635. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  12636. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  12637. } else {
  12638. SourceLocation Loc = FD->getLocation();
  12639. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  12640. Args, FD->getBody(), Info, Scratch, nullptr);
  12641. }
  12642. return Diags.empty();
  12643. }
  12644. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  12645. const FunctionDecl *FD,
  12646. SmallVectorImpl<
  12647. PartialDiagnosticAt> &Diags) {
  12648. assert(!E->isValueDependent() &&
  12649. "Expression evaluator can't be called on a dependent expression.");
  12650. Expr::EvalStatus Status;
  12651. Status.Diag = &Diags;
  12652. EvalInfo Info(FD->getASTContext(), Status,
  12653. EvalInfo::EM_ConstantExpressionUnevaluated);
  12654. Info.InConstantContext = true;
  12655. Info.CheckingPotentialConstantExpression = true;
  12656. // Fabricate a call stack frame to give the arguments a plausible cover story.
  12657. ArrayRef<const Expr*> Args;
  12658. ArgVector ArgValues(0);
  12659. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  12660. (void)Success;
  12661. assert(Success &&
  12662. "Failed to set up arguments for potential constant evaluation");
  12663. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  12664. APValue ResultScratch;
  12665. Evaluate(ResultScratch, Info, E);
  12666. return Diags.empty();
  12667. }
  12668. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  12669. unsigned Type) const {
  12670. if (!getType()->isPointerType())
  12671. return false;
  12672. Expr::EvalStatus Status;
  12673. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  12674. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  12675. }