ExprConstant.cpp 514 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451
  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(const ASTContext &Ctx, const 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 && I == N)) ||
  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_Succeeded : ESR_Failed;
  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 (unsigned Idx = 0; Idx < Args.size(); Idx++) {
  4834. if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
  4835. // If we're checking for a potential constant expression, evaluate all
  4836. // initializers even if some of them fail.
  4837. if (!Info.noteFailure())
  4838. return false;
  4839. Success = false;
  4840. } else if (!ForbiddenNullArgs.empty() &&
  4841. ForbiddenNullArgs[Idx] &&
  4842. ArgValues[Idx].isLValue() &&
  4843. ArgValues[Idx].isNullPointer()) {
  4844. Info.CCEDiag(Args[Idx], 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. static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
  5346. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  5347. if (CXXDestructorDecl *DD = RD->getDestructor())
  5348. return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
  5349. return nullptr;
  5350. }
  5351. /// Check that the given object is a suitable pointer to a heap allocation that
  5352. /// still exists and is of the right kind for the purpose of a deletion.
  5353. ///
  5354. /// On success, returns the heap allocation to deallocate. On failure, produces
  5355. /// a diagnostic and returns None.
  5356. static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
  5357. const LValue &Pointer,
  5358. DynAlloc::Kind DeallocKind) {
  5359. auto PointerAsString = [&] {
  5360. return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
  5361. };
  5362. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  5363. if (!DA) {
  5364. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  5365. << PointerAsString();
  5366. if (Pointer.Base)
  5367. NoteLValueLocation(Info, Pointer.Base);
  5368. return None;
  5369. }
  5370. Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
  5371. if (!Alloc) {
  5372. Info.FFDiag(E, diag::note_constexpr_double_delete);
  5373. return None;
  5374. }
  5375. QualType AllocType = Pointer.Base.getDynamicAllocType();
  5376. if (DeallocKind != (*Alloc)->getKind()) {
  5377. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  5378. << DeallocKind << (*Alloc)->getKind() << AllocType;
  5379. NoteLValueLocation(Info, Pointer.Base);
  5380. return None;
  5381. }
  5382. bool Subobject = false;
  5383. if (DeallocKind == DynAlloc::New) {
  5384. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  5385. Pointer.Designator.isOnePastTheEnd();
  5386. } else {
  5387. Subobject = Pointer.Designator.Entries.size() != 1 ||
  5388. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  5389. }
  5390. if (Subobject) {
  5391. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  5392. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  5393. return None;
  5394. }
  5395. return Alloc;
  5396. }
  5397. // Perform a call to 'operator delete' or '__builtin_operator_delete'.
  5398. bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
  5399. if (Info.checkingPotentialConstantExpression() ||
  5400. Info.SpeculativeEvaluationDepth)
  5401. return false;
  5402. // This is permitted only within a call to std::allocator<T>::deallocate.
  5403. if (!Info.getStdAllocatorCaller("deallocate")) {
  5404. Info.FFDiag(E->getExprLoc());
  5405. return true;
  5406. }
  5407. LValue Pointer;
  5408. if (!EvaluatePointer(E->getArg(0), Pointer, Info))
  5409. return false;
  5410. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
  5411. EvaluateIgnoredValue(Info, E->getArg(I));
  5412. if (Pointer.Designator.Invalid)
  5413. return false;
  5414. // Deleting a null pointer has no effect.
  5415. if (Pointer.isNullPointer())
  5416. return true;
  5417. if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
  5418. return false;
  5419. Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
  5420. return true;
  5421. }
  5422. //===----------------------------------------------------------------------===//
  5423. // Generic Evaluation
  5424. //===----------------------------------------------------------------------===//
  5425. namespace {
  5426. class BitCastBuffer {
  5427. // FIXME: We're going to need bit-level granularity when we support
  5428. // bit-fields.
  5429. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  5430. // we don't support a host or target where that is the case. Still, we should
  5431. // use a more generic type in case we ever do.
  5432. SmallVector<Optional<unsigned char>, 32> Bytes;
  5433. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  5434. "Need at least 8 bit unsigned char");
  5435. bool TargetIsLittleEndian;
  5436. public:
  5437. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  5438. : Bytes(Width.getQuantity()),
  5439. TargetIsLittleEndian(TargetIsLittleEndian) {}
  5440. LLVM_NODISCARD
  5441. bool readObject(CharUnits Offset, CharUnits Width,
  5442. SmallVectorImpl<unsigned char> &Output) const {
  5443. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  5444. // If a byte of an integer is uninitialized, then the whole integer is
  5445. // uninitalized.
  5446. if (!Bytes[I.getQuantity()])
  5447. return false;
  5448. Output.push_back(*Bytes[I.getQuantity()]);
  5449. }
  5450. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5451. std::reverse(Output.begin(), Output.end());
  5452. return true;
  5453. }
  5454. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  5455. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  5456. std::reverse(Input.begin(), Input.end());
  5457. size_t Index = 0;
  5458. for (unsigned char Byte : Input) {
  5459. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  5460. Bytes[Offset.getQuantity() + Index] = Byte;
  5461. ++Index;
  5462. }
  5463. }
  5464. size_t size() { return Bytes.size(); }
  5465. };
  5466. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  5467. /// target would represent the value at runtime.
  5468. class APValueToBufferConverter {
  5469. EvalInfo &Info;
  5470. BitCastBuffer Buffer;
  5471. const CastExpr *BCE;
  5472. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  5473. const CastExpr *BCE)
  5474. : Info(Info),
  5475. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  5476. BCE(BCE) {}
  5477. bool visit(const APValue &Val, QualType Ty) {
  5478. return visit(Val, Ty, CharUnits::fromQuantity(0));
  5479. }
  5480. // Write out Val with type Ty into Buffer starting at Offset.
  5481. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  5482. assert((size_t)Offset.getQuantity() <= Buffer.size());
  5483. // As a special case, nullptr_t has an indeterminate value.
  5484. if (Ty->isNullPtrType())
  5485. return true;
  5486. // Dig through Src to find the byte at SrcOffset.
  5487. switch (Val.getKind()) {
  5488. case APValue::Indeterminate:
  5489. case APValue::None:
  5490. return true;
  5491. case APValue::Int:
  5492. return visitInt(Val.getInt(), Ty, Offset);
  5493. case APValue::Float:
  5494. return visitFloat(Val.getFloat(), Ty, Offset);
  5495. case APValue::Array:
  5496. return visitArray(Val, Ty, Offset);
  5497. case APValue::Struct:
  5498. return visitRecord(Val, Ty, Offset);
  5499. case APValue::ComplexInt:
  5500. case APValue::ComplexFloat:
  5501. case APValue::Vector:
  5502. case APValue::FixedPoint:
  5503. // FIXME: We should support these.
  5504. case APValue::Union:
  5505. case APValue::MemberPointer:
  5506. case APValue::AddrLabelDiff: {
  5507. Info.FFDiag(BCE->getBeginLoc(),
  5508. diag::note_constexpr_bit_cast_unsupported_type)
  5509. << Ty;
  5510. return false;
  5511. }
  5512. case APValue::LValue:
  5513. llvm_unreachable("LValue subobject in bit_cast?");
  5514. }
  5515. llvm_unreachable("Unhandled APValue::ValueKind");
  5516. }
  5517. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  5518. const RecordDecl *RD = Ty->getAsRecordDecl();
  5519. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5520. // Visit the base classes.
  5521. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5522. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5523. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5524. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5525. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  5526. Layout.getBaseClassOffset(BaseDecl) + Offset))
  5527. return false;
  5528. }
  5529. }
  5530. // Visit the fields.
  5531. unsigned FieldIdx = 0;
  5532. for (FieldDecl *FD : RD->fields()) {
  5533. if (FD->isBitField()) {
  5534. Info.FFDiag(BCE->getBeginLoc(),
  5535. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5536. return false;
  5537. }
  5538. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5539. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  5540. "only bit-fields can have sub-char alignment");
  5541. CharUnits FieldOffset =
  5542. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  5543. QualType FieldTy = FD->getType();
  5544. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  5545. return false;
  5546. ++FieldIdx;
  5547. }
  5548. return true;
  5549. }
  5550. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  5551. const auto *CAT =
  5552. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  5553. if (!CAT)
  5554. return false;
  5555. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  5556. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  5557. unsigned ArraySize = Val.getArraySize();
  5558. // First, initialize the initialized elements.
  5559. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  5560. const APValue &SubObj = Val.getArrayInitializedElt(I);
  5561. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  5562. return false;
  5563. }
  5564. // Next, initialize the rest of the array using the filler.
  5565. if (Val.hasArrayFiller()) {
  5566. const APValue &Filler = Val.getArrayFiller();
  5567. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  5568. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  5569. return false;
  5570. }
  5571. }
  5572. return true;
  5573. }
  5574. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  5575. CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
  5576. SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
  5577. llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
  5578. Buffer.writeObject(Offset, Bytes);
  5579. return true;
  5580. }
  5581. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  5582. APSInt AsInt(Val.bitcastToAPInt());
  5583. return visitInt(AsInt, Ty, Offset);
  5584. }
  5585. public:
  5586. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  5587. const CastExpr *BCE) {
  5588. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  5589. APValueToBufferConverter Converter(Info, DstSize, BCE);
  5590. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  5591. return None;
  5592. return Converter.Buffer;
  5593. }
  5594. };
  5595. /// Write an BitCastBuffer into an APValue.
  5596. class BufferToAPValueConverter {
  5597. EvalInfo &Info;
  5598. const BitCastBuffer &Buffer;
  5599. const CastExpr *BCE;
  5600. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  5601. const CastExpr *BCE)
  5602. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  5603. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  5604. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  5605. // Ideally this will be unreachable.
  5606. llvm::NoneType unsupportedType(QualType Ty) {
  5607. Info.FFDiag(BCE->getBeginLoc(),
  5608. diag::note_constexpr_bit_cast_unsupported_type)
  5609. << Ty;
  5610. return None;
  5611. }
  5612. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  5613. const EnumType *EnumSugar = nullptr) {
  5614. if (T->isNullPtrType()) {
  5615. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  5616. return APValue((Expr *)nullptr,
  5617. /*Offset=*/CharUnits::fromQuantity(NullValue),
  5618. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  5619. }
  5620. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  5621. SmallVector<uint8_t, 8> Bytes;
  5622. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  5623. // If this is std::byte or unsigned char, then its okay to store an
  5624. // indeterminate value.
  5625. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  5626. bool IsUChar =
  5627. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  5628. T->isSpecificBuiltinType(BuiltinType::Char_U));
  5629. if (!IsStdByte && !IsUChar) {
  5630. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  5631. Info.FFDiag(BCE->getExprLoc(),
  5632. diag::note_constexpr_bit_cast_indet_dest)
  5633. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  5634. return None;
  5635. }
  5636. return APValue::IndeterminateValue();
  5637. }
  5638. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  5639. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  5640. if (T->isIntegralOrEnumerationType()) {
  5641. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  5642. return APValue(Val);
  5643. }
  5644. if (T->isRealFloatingType()) {
  5645. const llvm::fltSemantics &Semantics =
  5646. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  5647. return APValue(APFloat(Semantics, Val));
  5648. }
  5649. return unsupportedType(QualType(T, 0));
  5650. }
  5651. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  5652. const RecordDecl *RD = RTy->getAsRecordDecl();
  5653. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5654. unsigned NumBases = 0;
  5655. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5656. NumBases = CXXRD->getNumBases();
  5657. APValue ResultVal(APValue::UninitStruct(), NumBases,
  5658. std::distance(RD->field_begin(), RD->field_end()));
  5659. // Visit the base classes.
  5660. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5661. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  5662. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  5663. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  5664. if (BaseDecl->isEmpty() ||
  5665. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  5666. continue;
  5667. Optional<APValue> SubObj = visitType(
  5668. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  5669. if (!SubObj)
  5670. return None;
  5671. ResultVal.getStructBase(I) = *SubObj;
  5672. }
  5673. }
  5674. // Visit the fields.
  5675. unsigned FieldIdx = 0;
  5676. for (FieldDecl *FD : RD->fields()) {
  5677. // FIXME: We don't currently support bit-fields. A lot of the logic for
  5678. // this is in CodeGen, so we need to factor it around.
  5679. if (FD->isBitField()) {
  5680. Info.FFDiag(BCE->getBeginLoc(),
  5681. diag::note_constexpr_bit_cast_unsupported_bitfield);
  5682. return None;
  5683. }
  5684. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  5685. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  5686. CharUnits FieldOffset =
  5687. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  5688. Offset;
  5689. QualType FieldTy = FD->getType();
  5690. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  5691. if (!SubObj)
  5692. return None;
  5693. ResultVal.getStructField(FieldIdx) = *SubObj;
  5694. ++FieldIdx;
  5695. }
  5696. return ResultVal;
  5697. }
  5698. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  5699. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  5700. assert(!RepresentationType.isNull() &&
  5701. "enum forward decl should be caught by Sema");
  5702. const auto *AsBuiltin =
  5703. RepresentationType.getCanonicalType()->castAs<BuiltinType>();
  5704. // Recurse into the underlying type. Treat std::byte transparently as
  5705. // unsigned char.
  5706. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  5707. }
  5708. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  5709. size_t Size = Ty->getSize().getLimitedValue();
  5710. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  5711. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  5712. for (size_t I = 0; I != Size; ++I) {
  5713. Optional<APValue> ElementValue =
  5714. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  5715. if (!ElementValue)
  5716. return None;
  5717. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  5718. }
  5719. return ArrayValue;
  5720. }
  5721. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  5722. return unsupportedType(QualType(Ty, 0));
  5723. }
  5724. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  5725. QualType Can = Ty.getCanonicalType();
  5726. switch (Can->getTypeClass()) {
  5727. #define TYPE(Class, Base) \
  5728. case Type::Class: \
  5729. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  5730. #define ABSTRACT_TYPE(Class, Base)
  5731. #define NON_CANONICAL_TYPE(Class, Base) \
  5732. case Type::Class: \
  5733. llvm_unreachable("non-canonical type should be impossible!");
  5734. #define DEPENDENT_TYPE(Class, Base) \
  5735. case Type::Class: \
  5736. llvm_unreachable( \
  5737. "dependent types aren't supported in the constant evaluator!");
  5738. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  5739. case Type::Class: \
  5740. llvm_unreachable("either dependent or not canonical!");
  5741. #include "clang/AST/TypeNodes.inc"
  5742. }
  5743. llvm_unreachable("Unhandled Type::TypeClass");
  5744. }
  5745. public:
  5746. // Pull out a full value of type DstType.
  5747. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  5748. const CastExpr *BCE) {
  5749. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  5750. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  5751. }
  5752. };
  5753. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  5754. QualType Ty, EvalInfo *Info,
  5755. const ASTContext &Ctx,
  5756. bool CheckingDest) {
  5757. Ty = Ty.getCanonicalType();
  5758. auto diag = [&](int Reason) {
  5759. if (Info)
  5760. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  5761. << CheckingDest << (Reason == 4) << Reason;
  5762. return false;
  5763. };
  5764. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  5765. if (Info)
  5766. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  5767. << NoteTy << Construct << Ty;
  5768. return false;
  5769. };
  5770. if (Ty->isUnionType())
  5771. return diag(0);
  5772. if (Ty->isPointerType())
  5773. return diag(1);
  5774. if (Ty->isMemberPointerType())
  5775. return diag(2);
  5776. if (Ty.isVolatileQualified())
  5777. return diag(3);
  5778. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  5779. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  5780. for (CXXBaseSpecifier &BS : CXXRD->bases())
  5781. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  5782. CheckingDest))
  5783. return note(1, BS.getType(), BS.getBeginLoc());
  5784. }
  5785. for (FieldDecl *FD : Record->fields()) {
  5786. if (FD->getType()->isReferenceType())
  5787. return diag(4);
  5788. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  5789. CheckingDest))
  5790. return note(0, FD->getType(), FD->getBeginLoc());
  5791. }
  5792. }
  5793. if (Ty->isArrayType() &&
  5794. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  5795. Info, Ctx, CheckingDest))
  5796. return false;
  5797. return true;
  5798. }
  5799. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  5800. const ASTContext &Ctx,
  5801. const CastExpr *BCE) {
  5802. bool DestOK = checkBitCastConstexprEligibilityType(
  5803. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  5804. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  5805. BCE->getBeginLoc(),
  5806. BCE->getSubExpr()->getType(), Info, Ctx, false);
  5807. return SourceOK;
  5808. }
  5809. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  5810. APValue &SourceValue,
  5811. const CastExpr *BCE) {
  5812. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  5813. "no host or target supports non 8-bit chars");
  5814. assert(SourceValue.isLValue() &&
  5815. "LValueToRValueBitcast requires an lvalue operand!");
  5816. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  5817. return false;
  5818. LValue SourceLValue;
  5819. APValue SourceRValue;
  5820. SourceLValue.setFrom(Info.Ctx, SourceValue);
  5821. if (!handleLValueToRValueConversion(
  5822. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  5823. SourceRValue, /*WantObjectRepresentation=*/true))
  5824. return false;
  5825. // Read out SourceValue into a char buffer.
  5826. Optional<BitCastBuffer> Buffer =
  5827. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  5828. if (!Buffer)
  5829. return false;
  5830. // Write out the buffer into a new APValue.
  5831. Optional<APValue> MaybeDestValue =
  5832. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  5833. if (!MaybeDestValue)
  5834. return false;
  5835. DestValue = std::move(*MaybeDestValue);
  5836. return true;
  5837. }
  5838. template <class Derived>
  5839. class ExprEvaluatorBase
  5840. : public ConstStmtVisitor<Derived, bool> {
  5841. private:
  5842. Derived &getDerived() { return static_cast<Derived&>(*this); }
  5843. bool DerivedSuccess(const APValue &V, const Expr *E) {
  5844. return getDerived().Success(V, E);
  5845. }
  5846. bool DerivedZeroInitialization(const Expr *E) {
  5847. return getDerived().ZeroInitialization(E);
  5848. }
  5849. // Check whether a conditional operator with a non-constant condition is a
  5850. // potential constant expression. If neither arm is a potential constant
  5851. // expression, then the conditional operator is not either.
  5852. template<typename ConditionalOperator>
  5853. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  5854. assert(Info.checkingPotentialConstantExpression());
  5855. // Speculatively evaluate both arms.
  5856. SmallVector<PartialDiagnosticAt, 8> Diag;
  5857. {
  5858. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5859. StmtVisitorTy::Visit(E->getFalseExpr());
  5860. if (Diag.empty())
  5861. return;
  5862. }
  5863. {
  5864. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  5865. Diag.clear();
  5866. StmtVisitorTy::Visit(E->getTrueExpr());
  5867. if (Diag.empty())
  5868. return;
  5869. }
  5870. Error(E, diag::note_constexpr_conditional_never_const);
  5871. }
  5872. template<typename ConditionalOperator>
  5873. bool HandleConditionalOperator(const ConditionalOperator *E) {
  5874. bool BoolResult;
  5875. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  5876. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  5877. CheckPotentialConstantConditional(E);
  5878. return false;
  5879. }
  5880. if (Info.noteFailure()) {
  5881. StmtVisitorTy::Visit(E->getTrueExpr());
  5882. StmtVisitorTy::Visit(E->getFalseExpr());
  5883. }
  5884. return false;
  5885. }
  5886. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  5887. return StmtVisitorTy::Visit(EvalExpr);
  5888. }
  5889. protected:
  5890. EvalInfo &Info;
  5891. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  5892. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  5893. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  5894. return Info.CCEDiag(E, D);
  5895. }
  5896. bool ZeroInitialization(const Expr *E) { return Error(E); }
  5897. public:
  5898. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  5899. EvalInfo &getEvalInfo() { return Info; }
  5900. /// Report an evaluation error. This should only be called when an error is
  5901. /// first discovered. When propagating an error, just return false.
  5902. bool Error(const Expr *E, diag::kind D) {
  5903. Info.FFDiag(E, D);
  5904. return false;
  5905. }
  5906. bool Error(const Expr *E) {
  5907. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  5908. }
  5909. bool VisitStmt(const Stmt *) {
  5910. llvm_unreachable("Expression evaluator should not be called on stmts");
  5911. }
  5912. bool VisitExpr(const Expr *E) {
  5913. return Error(E);
  5914. }
  5915. bool VisitConstantExpr(const ConstantExpr *E)
  5916. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5917. bool VisitParenExpr(const ParenExpr *E)
  5918. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5919. bool VisitUnaryExtension(const UnaryOperator *E)
  5920. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5921. bool VisitUnaryPlus(const UnaryOperator *E)
  5922. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  5923. bool VisitChooseExpr(const ChooseExpr *E)
  5924. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  5925. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  5926. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  5927. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  5928. { return StmtVisitorTy::Visit(E->getReplacement()); }
  5929. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  5930. TempVersionRAII RAII(*Info.CurrentCall);
  5931. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5932. return StmtVisitorTy::Visit(E->getExpr());
  5933. }
  5934. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  5935. TempVersionRAII RAII(*Info.CurrentCall);
  5936. // The initializer may not have been parsed yet, or might be erroneous.
  5937. if (!E->getExpr())
  5938. return Error(E);
  5939. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  5940. return StmtVisitorTy::Visit(E->getExpr());
  5941. }
  5942. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  5943. FullExpressionRAII Scope(Info);
  5944. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  5945. }
  5946. // Temporaries are registered when created, so we don't care about
  5947. // CXXBindTemporaryExpr.
  5948. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  5949. return StmtVisitorTy::Visit(E->getSubExpr());
  5950. }
  5951. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  5952. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  5953. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5954. }
  5955. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  5956. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  5957. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  5958. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5959. }
  5960. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  5961. return static_cast<Derived*>(this)->VisitCastExpr(E);
  5962. }
  5963. bool VisitBinaryOperator(const BinaryOperator *E) {
  5964. switch (E->getOpcode()) {
  5965. default:
  5966. return Error(E);
  5967. case BO_Comma:
  5968. VisitIgnoredValue(E->getLHS());
  5969. return StmtVisitorTy::Visit(E->getRHS());
  5970. case BO_PtrMemD:
  5971. case BO_PtrMemI: {
  5972. LValue Obj;
  5973. if (!HandleMemberPointerAccess(Info, E, Obj))
  5974. return false;
  5975. APValue Result;
  5976. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  5977. return false;
  5978. return DerivedSuccess(Result, E);
  5979. }
  5980. }
  5981. }
  5982. bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
  5983. return StmtVisitorTy::Visit(E->getSemanticForm());
  5984. }
  5985. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  5986. // Evaluate and cache the common expression. We treat it as a temporary,
  5987. // even though it's not quite the same thing.
  5988. LValue CommonLV;
  5989. if (!Evaluate(Info.CurrentCall->createTemporary(
  5990. E->getOpaqueValue(),
  5991. getStorageType(Info.Ctx, E->getOpaqueValue()), false,
  5992. CommonLV),
  5993. Info, E->getCommon()))
  5994. return false;
  5995. return HandleConditionalOperator(E);
  5996. }
  5997. bool VisitConditionalOperator(const ConditionalOperator *E) {
  5998. bool IsBcpCall = false;
  5999. // If the condition (ignoring parens) is a __builtin_constant_p call,
  6000. // the result is a constant expression if it can be folded without
  6001. // side-effects. This is an important GNU extension. See GCC PR38377
  6002. // for discussion.
  6003. if (const CallExpr *CallCE =
  6004. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  6005. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  6006. IsBcpCall = true;
  6007. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  6008. // constant expression; we can't check whether it's potentially foldable.
  6009. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  6010. // it would return 'false' in this mode.
  6011. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  6012. return false;
  6013. FoldConstant Fold(Info, IsBcpCall);
  6014. if (!HandleConditionalOperator(E)) {
  6015. Fold.keepDiagnostics();
  6016. return false;
  6017. }
  6018. return true;
  6019. }
  6020. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  6021. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  6022. return DerivedSuccess(*Value, E);
  6023. const Expr *Source = E->getSourceExpr();
  6024. if (!Source)
  6025. return Error(E);
  6026. if (Source == E) { // sanity checking.
  6027. assert(0 && "OpaqueValueExpr recursively refers to itself");
  6028. return Error(E);
  6029. }
  6030. return StmtVisitorTy::Visit(Source);
  6031. }
  6032. bool VisitCallExpr(const CallExpr *E) {
  6033. APValue Result;
  6034. if (!handleCallExpr(E, Result, nullptr))
  6035. return false;
  6036. return DerivedSuccess(Result, E);
  6037. }
  6038. bool handleCallExpr(const CallExpr *E, APValue &Result,
  6039. const LValue *ResultSlot) {
  6040. const Expr *Callee = E->getCallee()->IgnoreParens();
  6041. QualType CalleeType = Callee->getType();
  6042. const FunctionDecl *FD = nullptr;
  6043. LValue *This = nullptr, ThisVal;
  6044. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  6045. bool HasQualifier = false;
  6046. // Extract function decl and 'this' pointer from the callee.
  6047. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  6048. const CXXMethodDecl *Member = nullptr;
  6049. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  6050. // Explicit bound member calls, such as x.f() or p->g();
  6051. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  6052. return false;
  6053. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  6054. if (!Member)
  6055. return Error(Callee);
  6056. This = &ThisVal;
  6057. HasQualifier = ME->hasQualifier();
  6058. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  6059. // Indirect bound member calls ('.*' or '->*').
  6060. const ValueDecl *D =
  6061. HandleMemberPointerAccess(Info, BE, ThisVal, false);
  6062. if (!D)
  6063. return false;
  6064. Member = dyn_cast<CXXMethodDecl>(D);
  6065. if (!Member)
  6066. return Error(Callee);
  6067. This = &ThisVal;
  6068. } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
  6069. if (!Info.getLangOpts().CPlusPlus2a)
  6070. Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
  6071. // FIXME: If pseudo-destructor calls ever start ending the lifetime of
  6072. // their callee, we should start calling HandleDestruction here.
  6073. // For now, we just evaluate the object argument and discard it.
  6074. return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
  6075. } else
  6076. return Error(Callee);
  6077. FD = Member;
  6078. } else if (CalleeType->isFunctionPointerType()) {
  6079. LValue Call;
  6080. if (!EvaluatePointer(Callee, Call, Info))
  6081. return false;
  6082. if (!Call.getLValueOffset().isZero())
  6083. return Error(Callee);
  6084. FD = dyn_cast_or_null<FunctionDecl>(
  6085. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  6086. if (!FD)
  6087. return Error(Callee);
  6088. // Don't call function pointers which have been cast to some other type.
  6089. // Per DR (no number yet), the caller and callee can differ in noexcept.
  6090. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  6091. CalleeType->getPointeeType(), FD->getType())) {
  6092. return Error(E);
  6093. }
  6094. // Overloaded operator calls to member functions are represented as normal
  6095. // calls with '*this' as the first argument.
  6096. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6097. if (MD && !MD->isStatic()) {
  6098. // FIXME: When selecting an implicit conversion for an overloaded
  6099. // operator delete, we sometimes try to evaluate calls to conversion
  6100. // operators without a 'this' parameter!
  6101. if (Args.empty())
  6102. return Error(E);
  6103. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  6104. return false;
  6105. This = &ThisVal;
  6106. Args = Args.slice(1);
  6107. } else if (MD && MD->isLambdaStaticInvoker()) {
  6108. // Map the static invoker for the lambda back to the call operator.
  6109. // Conveniently, we don't have to slice out the 'this' argument (as is
  6110. // being done for the non-static case), since a static member function
  6111. // doesn't have an implicit argument passed in.
  6112. const CXXRecordDecl *ClosureClass = MD->getParent();
  6113. assert(
  6114. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  6115. "Number of captures must be zero for conversion to function-ptr");
  6116. const CXXMethodDecl *LambdaCallOp =
  6117. ClosureClass->getLambdaCallOperator();
  6118. // Set 'FD', the function that will be called below, to the call
  6119. // operator. If the closure object represents a generic lambda, find
  6120. // the corresponding specialization of the call operator.
  6121. if (ClosureClass->isGenericLambda()) {
  6122. assert(MD->isFunctionTemplateSpecialization() &&
  6123. "A generic lambda's static-invoker function must be a "
  6124. "template specialization");
  6125. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  6126. FunctionTemplateDecl *CallOpTemplate =
  6127. LambdaCallOp->getDescribedFunctionTemplate();
  6128. void *InsertPos = nullptr;
  6129. FunctionDecl *CorrespondingCallOpSpecialization =
  6130. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  6131. assert(CorrespondingCallOpSpecialization &&
  6132. "We must always have a function call operator specialization "
  6133. "that corresponds to our static invoker specialization");
  6134. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  6135. } else
  6136. FD = LambdaCallOp;
  6137. } else if (FD->isReplaceableGlobalAllocationFunction()) {
  6138. if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
  6139. FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
  6140. LValue Ptr;
  6141. if (!HandleOperatorNewCall(Info, E, Ptr))
  6142. return false;
  6143. Ptr.moveInto(Result);
  6144. return true;
  6145. } else {
  6146. return HandleOperatorDeleteCall(Info, E);
  6147. }
  6148. }
  6149. } else
  6150. return Error(E);
  6151. SmallVector<QualType, 4> CovariantAdjustmentPath;
  6152. if (This) {
  6153. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  6154. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  6155. // Perform virtual dispatch, if necessary.
  6156. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  6157. CovariantAdjustmentPath);
  6158. if (!FD)
  6159. return false;
  6160. } else {
  6161. // Check that the 'this' pointer points to an object of the right type.
  6162. // FIXME: If this is an assignment operator call, we may need to change
  6163. // the active union member before we check this.
  6164. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
  6165. return false;
  6166. }
  6167. }
  6168. // Destructor calls are different enough that they have their own codepath.
  6169. if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
  6170. assert(This && "no 'this' pointer for destructor call");
  6171. return HandleDestruction(Info, E, *This,
  6172. Info.Ctx.getRecordType(DD->getParent()));
  6173. }
  6174. const FunctionDecl *Definition = nullptr;
  6175. Stmt *Body = FD->getBody(Definition);
  6176. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  6177. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  6178. Result, ResultSlot))
  6179. return false;
  6180. if (!CovariantAdjustmentPath.empty() &&
  6181. !HandleCovariantReturnAdjustment(Info, E, Result,
  6182. CovariantAdjustmentPath))
  6183. return false;
  6184. return true;
  6185. }
  6186. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6187. return StmtVisitorTy::Visit(E->getInitializer());
  6188. }
  6189. bool VisitInitListExpr(const InitListExpr *E) {
  6190. if (E->getNumInits() == 0)
  6191. return DerivedZeroInitialization(E);
  6192. if (E->getNumInits() == 1)
  6193. return StmtVisitorTy::Visit(E->getInit(0));
  6194. return Error(E);
  6195. }
  6196. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  6197. return DerivedZeroInitialization(E);
  6198. }
  6199. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  6200. return DerivedZeroInitialization(E);
  6201. }
  6202. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  6203. return DerivedZeroInitialization(E);
  6204. }
  6205. /// A member expression where the object is a prvalue is itself a prvalue.
  6206. bool VisitMemberExpr(const MemberExpr *E) {
  6207. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  6208. "missing temporary materialization conversion");
  6209. assert(!E->isArrow() && "missing call to bound member function?");
  6210. APValue Val;
  6211. if (!Evaluate(Val, Info, E->getBase()))
  6212. return false;
  6213. QualType BaseTy = E->getBase()->getType();
  6214. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  6215. if (!FD) return Error(E);
  6216. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  6217. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6218. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6219. // Note: there is no lvalue base here. But this case should only ever
  6220. // happen in C or in C++98, where we cannot be evaluating a constexpr
  6221. // constructor, which is the only case the base matters.
  6222. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  6223. SubobjectDesignator Designator(BaseTy);
  6224. Designator.addDeclUnchecked(FD);
  6225. APValue Result;
  6226. return extractSubobject(Info, E, Obj, Designator, Result) &&
  6227. DerivedSuccess(Result, E);
  6228. }
  6229. bool VisitCastExpr(const CastExpr *E) {
  6230. switch (E->getCastKind()) {
  6231. default:
  6232. break;
  6233. case CK_AtomicToNonAtomic: {
  6234. APValue AtomicVal;
  6235. // This does not need to be done in place even for class/array types:
  6236. // atomic-to-non-atomic conversion implies copying the object
  6237. // representation.
  6238. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  6239. return false;
  6240. return DerivedSuccess(AtomicVal, E);
  6241. }
  6242. case CK_NoOp:
  6243. case CK_UserDefinedConversion:
  6244. return StmtVisitorTy::Visit(E->getSubExpr());
  6245. case CK_LValueToRValue: {
  6246. LValue LVal;
  6247. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  6248. return false;
  6249. APValue RVal;
  6250. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6251. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6252. LVal, RVal))
  6253. return false;
  6254. return DerivedSuccess(RVal, E);
  6255. }
  6256. case CK_LValueToRValueBitCast: {
  6257. APValue DestValue, SourceValue;
  6258. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  6259. return false;
  6260. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  6261. return false;
  6262. return DerivedSuccess(DestValue, E);
  6263. }
  6264. }
  6265. return Error(E);
  6266. }
  6267. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  6268. return VisitUnaryPostIncDec(UO);
  6269. }
  6270. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  6271. return VisitUnaryPostIncDec(UO);
  6272. }
  6273. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  6274. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6275. return Error(UO);
  6276. LValue LVal;
  6277. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  6278. return false;
  6279. APValue RVal;
  6280. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  6281. UO->isIncrementOp(), &RVal))
  6282. return false;
  6283. return DerivedSuccess(RVal, UO);
  6284. }
  6285. bool VisitStmtExpr(const StmtExpr *E) {
  6286. // We will have checked the full-expressions inside the statement expression
  6287. // when they were completed, and don't need to check them again now.
  6288. if (Info.checkingForUndefinedBehavior())
  6289. return Error(E);
  6290. const CompoundStmt *CS = E->getSubStmt();
  6291. if (CS->body_empty())
  6292. return true;
  6293. BlockScopeRAII Scope(Info);
  6294. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  6295. BE = CS->body_end();
  6296. /**/; ++BI) {
  6297. if (BI + 1 == BE) {
  6298. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  6299. if (!FinalExpr) {
  6300. Info.FFDiag((*BI)->getBeginLoc(),
  6301. diag::note_constexpr_stmt_expr_unsupported);
  6302. return false;
  6303. }
  6304. return this->Visit(FinalExpr) && Scope.destroy();
  6305. }
  6306. APValue ReturnValue;
  6307. StmtResult Result = { ReturnValue, nullptr };
  6308. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  6309. if (ESR != ESR_Succeeded) {
  6310. // FIXME: If the statement-expression terminated due to 'return',
  6311. // 'break', or 'continue', it would be nice to propagate that to
  6312. // the outer statement evaluation rather than bailing out.
  6313. if (ESR != ESR_Failed)
  6314. Info.FFDiag((*BI)->getBeginLoc(),
  6315. diag::note_constexpr_stmt_expr_unsupported);
  6316. return false;
  6317. }
  6318. }
  6319. llvm_unreachable("Return from function from the loop above.");
  6320. }
  6321. /// Visit a value which is evaluated, but whose value is ignored.
  6322. void VisitIgnoredValue(const Expr *E) {
  6323. EvaluateIgnoredValue(Info, E);
  6324. }
  6325. /// Potentially visit a MemberExpr's base expression.
  6326. void VisitIgnoredBaseExpression(const Expr *E) {
  6327. // While MSVC doesn't evaluate the base expression, it does diagnose the
  6328. // presence of side-effecting behavior.
  6329. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  6330. return;
  6331. VisitIgnoredValue(E);
  6332. }
  6333. };
  6334. } // namespace
  6335. //===----------------------------------------------------------------------===//
  6336. // Common base class for lvalue and temporary evaluation.
  6337. //===----------------------------------------------------------------------===//
  6338. namespace {
  6339. template<class Derived>
  6340. class LValueExprEvaluatorBase
  6341. : public ExprEvaluatorBase<Derived> {
  6342. protected:
  6343. LValue &Result;
  6344. bool InvalidBaseOK;
  6345. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  6346. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  6347. bool Success(APValue::LValueBase B) {
  6348. Result.set(B);
  6349. return true;
  6350. }
  6351. bool evaluatePointer(const Expr *E, LValue &Result) {
  6352. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  6353. }
  6354. public:
  6355. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  6356. : ExprEvaluatorBaseTy(Info), Result(Result),
  6357. InvalidBaseOK(InvalidBaseOK) {}
  6358. bool Success(const APValue &V, const Expr *E) {
  6359. Result.setFrom(this->Info.Ctx, V);
  6360. return true;
  6361. }
  6362. bool VisitMemberExpr(const MemberExpr *E) {
  6363. // Handle non-static data members.
  6364. QualType BaseTy;
  6365. bool EvalOK;
  6366. if (E->isArrow()) {
  6367. EvalOK = evaluatePointer(E->getBase(), Result);
  6368. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  6369. } else if (E->getBase()->isRValue()) {
  6370. assert(E->getBase()->getType()->isRecordType());
  6371. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  6372. BaseTy = E->getBase()->getType();
  6373. } else {
  6374. EvalOK = this->Visit(E->getBase());
  6375. BaseTy = E->getBase()->getType();
  6376. }
  6377. if (!EvalOK) {
  6378. if (!InvalidBaseOK)
  6379. return false;
  6380. Result.setInvalid(E);
  6381. return true;
  6382. }
  6383. const ValueDecl *MD = E->getMemberDecl();
  6384. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  6385. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6386. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6387. (void)BaseTy;
  6388. if (!HandleLValueMember(this->Info, E, Result, FD))
  6389. return false;
  6390. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  6391. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  6392. return false;
  6393. } else
  6394. return this->Error(E);
  6395. if (MD->getType()->isReferenceType()) {
  6396. APValue RefValue;
  6397. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  6398. RefValue))
  6399. return false;
  6400. return Success(RefValue, E);
  6401. }
  6402. return true;
  6403. }
  6404. bool VisitBinaryOperator(const BinaryOperator *E) {
  6405. switch (E->getOpcode()) {
  6406. default:
  6407. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6408. case BO_PtrMemD:
  6409. case BO_PtrMemI:
  6410. return HandleMemberPointerAccess(this->Info, E, Result);
  6411. }
  6412. }
  6413. bool VisitCastExpr(const CastExpr *E) {
  6414. switch (E->getCastKind()) {
  6415. default:
  6416. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6417. case CK_DerivedToBase:
  6418. case CK_UncheckedDerivedToBase:
  6419. if (!this->Visit(E->getSubExpr()))
  6420. return false;
  6421. // Now figure out the necessary offset to add to the base LV to get from
  6422. // the derived class to the base class.
  6423. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  6424. Result);
  6425. }
  6426. }
  6427. };
  6428. }
  6429. //===----------------------------------------------------------------------===//
  6430. // LValue Evaluation
  6431. //
  6432. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  6433. // function designators (in C), decl references to void objects (in C), and
  6434. // temporaries (if building with -Wno-address-of-temporary).
  6435. //
  6436. // LValue evaluation produces values comprising a base expression of one of the
  6437. // following types:
  6438. // - Declarations
  6439. // * VarDecl
  6440. // * FunctionDecl
  6441. // - Literals
  6442. // * CompoundLiteralExpr in C (and in global scope in C++)
  6443. // * StringLiteral
  6444. // * PredefinedExpr
  6445. // * ObjCStringLiteralExpr
  6446. // * ObjCEncodeExpr
  6447. // * AddrLabelExpr
  6448. // * BlockExpr
  6449. // * CallExpr for a MakeStringConstant builtin
  6450. // - typeid(T) expressions, as TypeInfoLValues
  6451. // - Locals and temporaries
  6452. // * MaterializeTemporaryExpr
  6453. // * Any Expr, with a CallIndex indicating the function in which the temporary
  6454. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  6455. // from the AST (FIXME).
  6456. // * A MaterializeTemporaryExpr that has static storage duration, with no
  6457. // CallIndex, for a lifetime-extended temporary.
  6458. // plus an offset in bytes.
  6459. //===----------------------------------------------------------------------===//
  6460. namespace {
  6461. class LValueExprEvaluator
  6462. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  6463. public:
  6464. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  6465. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  6466. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  6467. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  6468. bool VisitDeclRefExpr(const DeclRefExpr *E);
  6469. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  6470. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  6471. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  6472. bool VisitMemberExpr(const MemberExpr *E);
  6473. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  6474. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  6475. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  6476. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  6477. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  6478. bool VisitUnaryDeref(const UnaryOperator *E);
  6479. bool VisitUnaryReal(const UnaryOperator *E);
  6480. bool VisitUnaryImag(const UnaryOperator *E);
  6481. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  6482. return VisitUnaryPreIncDec(UO);
  6483. }
  6484. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  6485. return VisitUnaryPreIncDec(UO);
  6486. }
  6487. bool VisitBinAssign(const BinaryOperator *BO);
  6488. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  6489. bool VisitCastExpr(const CastExpr *E) {
  6490. switch (E->getCastKind()) {
  6491. default:
  6492. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6493. case CK_LValueBitCast:
  6494. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  6495. if (!Visit(E->getSubExpr()))
  6496. return false;
  6497. Result.Designator.setInvalid();
  6498. return true;
  6499. case CK_BaseToDerived:
  6500. if (!Visit(E->getSubExpr()))
  6501. return false;
  6502. return HandleBaseToDerivedCast(Info, E, Result);
  6503. case CK_Dynamic:
  6504. if (!Visit(E->getSubExpr()))
  6505. return false;
  6506. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  6507. }
  6508. }
  6509. };
  6510. } // end anonymous namespace
  6511. /// Evaluate an expression as an lvalue. This can be legitimately called on
  6512. /// expressions which are not glvalues, in three cases:
  6513. /// * function designators in C, and
  6514. /// * "extern void" objects
  6515. /// * @selector() expressions in Objective-C
  6516. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  6517. bool InvalidBaseOK) {
  6518. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  6519. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  6520. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6521. }
  6522. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  6523. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  6524. return Success(FD);
  6525. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  6526. return VisitVarDecl(E, VD);
  6527. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  6528. return Visit(BD->getBinding());
  6529. return Error(E);
  6530. }
  6531. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  6532. // If we are within a lambda's call operator, check whether the 'VD' referred
  6533. // to within 'E' actually represents a lambda-capture that maps to a
  6534. // data-member/field within the closure object, and if so, evaluate to the
  6535. // field or what the field refers to.
  6536. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  6537. isa<DeclRefExpr>(E) &&
  6538. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  6539. // We don't always have a complete capture-map when checking or inferring if
  6540. // the function call operator meets the requirements of a constexpr function
  6541. // - but we don't need to evaluate the captures to determine constexprness
  6542. // (dcl.constexpr C++17).
  6543. if (Info.checkingPotentialConstantExpression())
  6544. return false;
  6545. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  6546. // Start with 'Result' referring to the complete closure object...
  6547. Result = *Info.CurrentCall->This;
  6548. // ... then update it to refer to the field of the closure object
  6549. // that represents the capture.
  6550. if (!HandleLValueMember(Info, E, Result, FD))
  6551. return false;
  6552. // And if the field is of reference type, update 'Result' to refer to what
  6553. // the field refers to.
  6554. if (FD->getType()->isReferenceType()) {
  6555. APValue RVal;
  6556. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  6557. RVal))
  6558. return false;
  6559. Result.setFrom(Info.Ctx, RVal);
  6560. }
  6561. return true;
  6562. }
  6563. }
  6564. CallStackFrame *Frame = nullptr;
  6565. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  6566. // Only if a local variable was declared in the function currently being
  6567. // evaluated, do we expect to be able to find its value in the current
  6568. // frame. (Otherwise it was likely declared in an enclosing context and
  6569. // could either have a valid evaluatable value (for e.g. a constexpr
  6570. // variable) or be ill-formed (and trigger an appropriate evaluation
  6571. // diagnostic)).
  6572. if (Info.CurrentCall->Callee &&
  6573. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  6574. Frame = Info.CurrentCall;
  6575. }
  6576. }
  6577. if (!VD->getType()->isReferenceType()) {
  6578. if (Frame) {
  6579. Result.set({VD, Frame->Index,
  6580. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  6581. return true;
  6582. }
  6583. return Success(VD);
  6584. }
  6585. APValue *V;
  6586. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  6587. return false;
  6588. if (!V->hasValue()) {
  6589. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  6590. // adjust the diagnostic to say that.
  6591. if (!Info.checkingPotentialConstantExpression())
  6592. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  6593. return false;
  6594. }
  6595. return Success(*V, E);
  6596. }
  6597. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  6598. const MaterializeTemporaryExpr *E) {
  6599. // Walk through the expression to find the materialized temporary itself.
  6600. SmallVector<const Expr *, 2> CommaLHSs;
  6601. SmallVector<SubobjectAdjustment, 2> Adjustments;
  6602. const Expr *Inner = E->GetTemporaryExpr()->
  6603. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  6604. // If we passed any comma operators, evaluate their LHSs.
  6605. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  6606. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  6607. return false;
  6608. // A materialized temporary with static storage duration can appear within the
  6609. // result of a constant expression evaluation, so we need to preserve its
  6610. // value for use outside this evaluation.
  6611. APValue *Value;
  6612. if (E->getStorageDuration() == SD_Static) {
  6613. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  6614. *Value = APValue();
  6615. Result.set(E);
  6616. } else {
  6617. Value = &Info.CurrentCall->createTemporary(
  6618. E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
  6619. }
  6620. QualType Type = Inner->getType();
  6621. // Materialize the temporary itself.
  6622. if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
  6623. *Value = APValue();
  6624. return false;
  6625. }
  6626. // Adjust our lvalue to refer to the desired subobject.
  6627. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  6628. --I;
  6629. switch (Adjustments[I].Kind) {
  6630. case SubobjectAdjustment::DerivedToBaseAdjustment:
  6631. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  6632. Type, Result))
  6633. return false;
  6634. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  6635. break;
  6636. case SubobjectAdjustment::FieldAdjustment:
  6637. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  6638. return false;
  6639. Type = Adjustments[I].Field->getType();
  6640. break;
  6641. case SubobjectAdjustment::MemberPointerAdjustment:
  6642. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  6643. Adjustments[I].Ptr.RHS))
  6644. return false;
  6645. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  6646. break;
  6647. }
  6648. }
  6649. return true;
  6650. }
  6651. bool
  6652. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6653. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  6654. "lvalue compound literal in c++?");
  6655. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  6656. // only see this when folding in C, so there's no standard to follow here.
  6657. return Success(E);
  6658. }
  6659. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  6660. TypeInfoLValue TypeInfo;
  6661. if (!E->isPotentiallyEvaluated()) {
  6662. if (E->isTypeOperand())
  6663. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  6664. else
  6665. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  6666. } else {
  6667. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  6668. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  6669. << E->getExprOperand()->getType()
  6670. << E->getExprOperand()->getSourceRange();
  6671. }
  6672. if (!Visit(E->getExprOperand()))
  6673. return false;
  6674. Optional<DynamicType> DynType =
  6675. ComputeDynamicType(Info, E, Result, AK_TypeId);
  6676. if (!DynType)
  6677. return false;
  6678. TypeInfo =
  6679. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  6680. }
  6681. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  6682. }
  6683. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  6684. return Success(E);
  6685. }
  6686. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  6687. // Handle static data members.
  6688. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  6689. VisitIgnoredBaseExpression(E->getBase());
  6690. return VisitVarDecl(E, VD);
  6691. }
  6692. // Handle static member functions.
  6693. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  6694. if (MD->isStatic()) {
  6695. VisitIgnoredBaseExpression(E->getBase());
  6696. return Success(MD);
  6697. }
  6698. }
  6699. // Handle non-static data members.
  6700. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  6701. }
  6702. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  6703. // FIXME: Deal with vectors as array subscript bases.
  6704. if (E->getBase()->getType()->isVectorType())
  6705. return Error(E);
  6706. bool Success = true;
  6707. if (!evaluatePointer(E->getBase(), Result)) {
  6708. if (!Info.noteFailure())
  6709. return false;
  6710. Success = false;
  6711. }
  6712. APSInt Index;
  6713. if (!EvaluateInteger(E->getIdx(), Index, Info))
  6714. return false;
  6715. return Success &&
  6716. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  6717. }
  6718. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  6719. return evaluatePointer(E->getSubExpr(), Result);
  6720. }
  6721. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  6722. if (!Visit(E->getSubExpr()))
  6723. return false;
  6724. // __real is a no-op on scalar lvalues.
  6725. if (E->getSubExpr()->getType()->isAnyComplexType())
  6726. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  6727. return true;
  6728. }
  6729. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6730. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  6731. "lvalue __imag__ on scalar?");
  6732. if (!Visit(E->getSubExpr()))
  6733. return false;
  6734. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  6735. return true;
  6736. }
  6737. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  6738. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6739. return Error(UO);
  6740. if (!this->Visit(UO->getSubExpr()))
  6741. return false;
  6742. return handleIncDec(
  6743. this->Info, UO, Result, UO->getSubExpr()->getType(),
  6744. UO->isIncrementOp(), nullptr);
  6745. }
  6746. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  6747. const CompoundAssignOperator *CAO) {
  6748. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6749. return Error(CAO);
  6750. APValue RHS;
  6751. // The overall lvalue result is the result of evaluating the LHS.
  6752. if (!this->Visit(CAO->getLHS())) {
  6753. if (Info.noteFailure())
  6754. Evaluate(RHS, this->Info, CAO->getRHS());
  6755. return false;
  6756. }
  6757. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  6758. return false;
  6759. return handleCompoundAssignment(
  6760. this->Info, CAO,
  6761. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  6762. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  6763. }
  6764. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  6765. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6766. return Error(E);
  6767. APValue NewVal;
  6768. if (!this->Visit(E->getLHS())) {
  6769. if (Info.noteFailure())
  6770. Evaluate(NewVal, this->Info, E->getRHS());
  6771. return false;
  6772. }
  6773. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  6774. return false;
  6775. if (Info.getLangOpts().CPlusPlus2a &&
  6776. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  6777. return false;
  6778. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  6779. NewVal);
  6780. }
  6781. //===----------------------------------------------------------------------===//
  6782. // Pointer Evaluation
  6783. //===----------------------------------------------------------------------===//
  6784. /// Attempts to compute the number of bytes available at the pointer
  6785. /// returned by a function with the alloc_size attribute. Returns true if we
  6786. /// were successful. Places an unsigned number into `Result`.
  6787. ///
  6788. /// This expects the given CallExpr to be a call to a function with an
  6789. /// alloc_size attribute.
  6790. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6791. const CallExpr *Call,
  6792. llvm::APInt &Result) {
  6793. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  6794. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  6795. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  6796. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  6797. if (Call->getNumArgs() <= SizeArgNo)
  6798. return false;
  6799. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  6800. Expr::EvalResult ExprResult;
  6801. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  6802. return false;
  6803. Into = ExprResult.Val.getInt();
  6804. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  6805. return false;
  6806. Into = Into.zextOrSelf(BitsInSizeT);
  6807. return true;
  6808. };
  6809. APSInt SizeOfElem;
  6810. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  6811. return false;
  6812. if (!AllocSize->getNumElemsParam().isValid()) {
  6813. Result = std::move(SizeOfElem);
  6814. return true;
  6815. }
  6816. APSInt NumberOfElems;
  6817. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  6818. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  6819. return false;
  6820. bool Overflow;
  6821. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  6822. if (Overflow)
  6823. return false;
  6824. Result = std::move(BytesAvailable);
  6825. return true;
  6826. }
  6827. /// Convenience function. LVal's base must be a call to an alloc_size
  6828. /// function.
  6829. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  6830. const LValue &LVal,
  6831. llvm::APInt &Result) {
  6832. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6833. "Can't get the size of a non alloc_size function");
  6834. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  6835. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  6836. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  6837. }
  6838. /// Attempts to evaluate the given LValueBase as the result of a call to
  6839. /// a function with the alloc_size attribute. If it was possible to do so, this
  6840. /// function will return true, make Result's Base point to said function call,
  6841. /// and mark Result's Base as invalid.
  6842. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  6843. LValue &Result) {
  6844. if (Base.isNull())
  6845. return false;
  6846. // Because we do no form of static analysis, we only support const variables.
  6847. //
  6848. // Additionally, we can't support parameters, nor can we support static
  6849. // variables (in the latter case, use-before-assign isn't UB; in the former,
  6850. // we have no clue what they'll be assigned to).
  6851. const auto *VD =
  6852. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  6853. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  6854. return false;
  6855. const Expr *Init = VD->getAnyInitializer();
  6856. if (!Init)
  6857. return false;
  6858. const Expr *E = Init->IgnoreParens();
  6859. if (!tryUnwrapAllocSizeCall(E))
  6860. return false;
  6861. // Store E instead of E unwrapped so that the type of the LValue's base is
  6862. // what the user wanted.
  6863. Result.setInvalid(E);
  6864. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  6865. Result.addUnsizedArray(Info, E, Pointee);
  6866. return true;
  6867. }
  6868. namespace {
  6869. class PointerExprEvaluator
  6870. : public ExprEvaluatorBase<PointerExprEvaluator> {
  6871. LValue &Result;
  6872. bool InvalidBaseOK;
  6873. bool Success(const Expr *E) {
  6874. Result.set(E);
  6875. return true;
  6876. }
  6877. bool evaluateLValue(const Expr *E, LValue &Result) {
  6878. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  6879. }
  6880. bool evaluatePointer(const Expr *E, LValue &Result) {
  6881. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  6882. }
  6883. bool visitNonBuiltinCallExpr(const CallExpr *E);
  6884. public:
  6885. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  6886. : ExprEvaluatorBaseTy(info), Result(Result),
  6887. InvalidBaseOK(InvalidBaseOK) {}
  6888. bool Success(const APValue &V, const Expr *E) {
  6889. Result.setFrom(Info.Ctx, V);
  6890. return true;
  6891. }
  6892. bool ZeroInitialization(const Expr *E) {
  6893. Result.setNull(Info.Ctx, E->getType());
  6894. return true;
  6895. }
  6896. bool VisitBinaryOperator(const BinaryOperator *E);
  6897. bool VisitCastExpr(const CastExpr* E);
  6898. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6899. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  6900. { return Success(E); }
  6901. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  6902. if (E->isExpressibleAsConstantInitializer())
  6903. return Success(E);
  6904. if (Info.noteFailure())
  6905. EvaluateIgnoredValue(Info, E->getSubExpr());
  6906. return Error(E);
  6907. }
  6908. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  6909. { return Success(E); }
  6910. bool VisitCallExpr(const CallExpr *E);
  6911. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6912. bool VisitBlockExpr(const BlockExpr *E) {
  6913. if (!E->getBlockDecl()->hasCaptures())
  6914. return Success(E);
  6915. return Error(E);
  6916. }
  6917. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  6918. // Can't look at 'this' when checking a potential constant expression.
  6919. if (Info.checkingPotentialConstantExpression())
  6920. return false;
  6921. if (!Info.CurrentCall->This) {
  6922. if (Info.getLangOpts().CPlusPlus11)
  6923. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  6924. else
  6925. Info.FFDiag(E);
  6926. return false;
  6927. }
  6928. Result = *Info.CurrentCall->This;
  6929. // If we are inside a lambda's call operator, the 'this' expression refers
  6930. // to the enclosing '*this' object (either by value or reference) which is
  6931. // either copied into the closure object's field that represents the '*this'
  6932. // or refers to '*this'.
  6933. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  6934. // Update 'Result' to refer to the data member/field of the closure object
  6935. // that represents the '*this' capture.
  6936. if (!HandleLValueMember(Info, E, Result,
  6937. Info.CurrentCall->LambdaThisCaptureField))
  6938. return false;
  6939. // If we captured '*this' by reference, replace the field with its referent.
  6940. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  6941. ->isPointerType()) {
  6942. APValue RVal;
  6943. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  6944. RVal))
  6945. return false;
  6946. Result.setFrom(Info.Ctx, RVal);
  6947. }
  6948. }
  6949. return true;
  6950. }
  6951. bool VisitCXXNewExpr(const CXXNewExpr *E);
  6952. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  6953. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  6954. APValue LValResult = E->EvaluateInContext(
  6955. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  6956. Result.setFrom(Info.Ctx, LValResult);
  6957. return true;
  6958. }
  6959. // FIXME: Missing: @protocol, @selector
  6960. };
  6961. } // end anonymous namespace
  6962. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  6963. bool InvalidBaseOK) {
  6964. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6965. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  6966. }
  6967. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6968. if (E->getOpcode() != BO_Add &&
  6969. E->getOpcode() != BO_Sub)
  6970. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  6971. const Expr *PExp = E->getLHS();
  6972. const Expr *IExp = E->getRHS();
  6973. if (IExp->getType()->isPointerType())
  6974. std::swap(PExp, IExp);
  6975. bool EvalPtrOK = evaluatePointer(PExp, Result);
  6976. if (!EvalPtrOK && !Info.noteFailure())
  6977. return false;
  6978. llvm::APSInt Offset;
  6979. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  6980. return false;
  6981. if (E->getOpcode() == BO_Sub)
  6982. negateAsSigned(Offset);
  6983. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  6984. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  6985. }
  6986. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6987. return evaluateLValue(E->getSubExpr(), Result);
  6988. }
  6989. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6990. const Expr *SubExpr = E->getSubExpr();
  6991. switch (E->getCastKind()) {
  6992. default:
  6993. break;
  6994. case CK_BitCast:
  6995. case CK_CPointerToObjCPointerCast:
  6996. case CK_BlockPointerToObjCPointerCast:
  6997. case CK_AnyPointerToBlockPointerCast:
  6998. case CK_AddressSpaceConversion:
  6999. if (!Visit(SubExpr))
  7000. return false;
  7001. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  7002. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  7003. // also static_casts, but we disallow them as a resolution to DR1312.
  7004. if (!E->getType()->isVoidPointerType()) {
  7005. if (!Result.InvalidBase && !Result.Designator.Invalid &&
  7006. !Result.IsNullPtr &&
  7007. Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
  7008. E->getType()->getPointeeType()) &&
  7009. Info.getStdAllocatorCaller("allocate")) {
  7010. // Inside a call to std::allocator::allocate and friends, we permit
  7011. // casting from void* back to cv1 T* for a pointer that points to a
  7012. // cv2 T.
  7013. } else {
  7014. Result.Designator.setInvalid();
  7015. if (SubExpr->getType()->isVoidPointerType())
  7016. CCEDiag(E, diag::note_constexpr_invalid_cast)
  7017. << 3 << SubExpr->getType();
  7018. else
  7019. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7020. }
  7021. }
  7022. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  7023. ZeroInitialization(E);
  7024. return true;
  7025. case CK_DerivedToBase:
  7026. case CK_UncheckedDerivedToBase:
  7027. if (!evaluatePointer(E->getSubExpr(), Result))
  7028. return false;
  7029. if (!Result.Base && Result.Offset.isZero())
  7030. return true;
  7031. // Now figure out the necessary offset to add to the base LV to get from
  7032. // the derived class to the base class.
  7033. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  7034. castAs<PointerType>()->getPointeeType(),
  7035. Result);
  7036. case CK_BaseToDerived:
  7037. if (!Visit(E->getSubExpr()))
  7038. return false;
  7039. if (!Result.Base && Result.Offset.isZero())
  7040. return true;
  7041. return HandleBaseToDerivedCast(Info, E, Result);
  7042. case CK_Dynamic:
  7043. if (!Visit(E->getSubExpr()))
  7044. return false;
  7045. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  7046. case CK_NullToPointer:
  7047. VisitIgnoredValue(E->getSubExpr());
  7048. return ZeroInitialization(E);
  7049. case CK_IntegralToPointer: {
  7050. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7051. APValue Value;
  7052. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  7053. break;
  7054. if (Value.isInt()) {
  7055. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  7056. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  7057. Result.Base = (Expr*)nullptr;
  7058. Result.InvalidBase = false;
  7059. Result.Offset = CharUnits::fromQuantity(N);
  7060. Result.Designator.setInvalid();
  7061. Result.IsNullPtr = false;
  7062. return true;
  7063. } else {
  7064. // Cast is of an lvalue, no need to change value.
  7065. Result.setFrom(Info.Ctx, Value);
  7066. return true;
  7067. }
  7068. }
  7069. case CK_ArrayToPointerDecay: {
  7070. if (SubExpr->isGLValue()) {
  7071. if (!evaluateLValue(SubExpr, Result))
  7072. return false;
  7073. } else {
  7074. APValue &Value = Info.CurrentCall->createTemporary(
  7075. SubExpr, SubExpr->getType(), false, Result);
  7076. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  7077. return false;
  7078. }
  7079. // The result is a pointer to the first element of the array.
  7080. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  7081. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  7082. Result.addArray(Info, E, CAT);
  7083. else
  7084. Result.addUnsizedArray(Info, E, AT->getElementType());
  7085. return true;
  7086. }
  7087. case CK_FunctionToPointerDecay:
  7088. return evaluateLValue(SubExpr, Result);
  7089. case CK_LValueToRValue: {
  7090. LValue LVal;
  7091. if (!evaluateLValue(E->getSubExpr(), LVal))
  7092. return false;
  7093. APValue RVal;
  7094. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  7095. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  7096. LVal, RVal))
  7097. return InvalidBaseOK &&
  7098. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  7099. return Success(RVal, E);
  7100. }
  7101. }
  7102. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7103. }
  7104. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  7105. UnaryExprOrTypeTrait ExprKind) {
  7106. // C++ [expr.alignof]p3:
  7107. // When alignof is applied to a reference type, the result is the
  7108. // alignment of the referenced type.
  7109. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  7110. T = Ref->getPointeeType();
  7111. if (T.getQualifiers().hasUnaligned())
  7112. return CharUnits::One();
  7113. const bool AlignOfReturnsPreferred =
  7114. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  7115. // __alignof is defined to return the preferred alignment.
  7116. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  7117. // as well.
  7118. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  7119. return Info.Ctx.toCharUnitsFromBits(
  7120. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  7121. // alignof and _Alignof are defined to return the ABI alignment.
  7122. else if (ExprKind == UETT_AlignOf)
  7123. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  7124. else
  7125. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  7126. }
  7127. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  7128. UnaryExprOrTypeTrait ExprKind) {
  7129. E = E->IgnoreParens();
  7130. // The kinds of expressions that we have special-case logic here for
  7131. // should be kept up to date with the special checks for those
  7132. // expressions in Sema.
  7133. // alignof decl is always accepted, even if it doesn't make sense: we default
  7134. // to 1 in those cases.
  7135. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  7136. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  7137. /*RefAsPointee*/true);
  7138. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  7139. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  7140. /*RefAsPointee*/true);
  7141. return GetAlignOfType(Info, E->getType(), ExprKind);
  7142. }
  7143. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  7144. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  7145. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  7146. return true;
  7147. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  7148. return false;
  7149. Result.setInvalid(E);
  7150. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  7151. Result.addUnsizedArray(Info, E, PointeeTy);
  7152. return true;
  7153. }
  7154. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7155. if (IsStringLiteralCall(E))
  7156. return Success(E);
  7157. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7158. return VisitBuiltinCallExpr(E, BuiltinOp);
  7159. return visitNonBuiltinCallExpr(E);
  7160. }
  7161. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7162. unsigned BuiltinOp) {
  7163. switch (BuiltinOp) {
  7164. case Builtin::BI__builtin_addressof:
  7165. return evaluateLValue(E->getArg(0), Result);
  7166. case Builtin::BI__builtin_assume_aligned: {
  7167. // We need to be very careful here because: if the pointer does not have the
  7168. // asserted alignment, then the behavior is undefined, and undefined
  7169. // behavior is non-constant.
  7170. if (!evaluatePointer(E->getArg(0), Result))
  7171. return false;
  7172. LValue OffsetResult(Result);
  7173. APSInt Alignment;
  7174. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  7175. return false;
  7176. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  7177. if (E->getNumArgs() > 2) {
  7178. APSInt Offset;
  7179. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  7180. return false;
  7181. int64_t AdditionalOffset = -Offset.getZExtValue();
  7182. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  7183. }
  7184. // If there is a base object, then it must have the correct alignment.
  7185. if (OffsetResult.Base) {
  7186. CharUnits BaseAlignment;
  7187. if (const ValueDecl *VD =
  7188. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  7189. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  7190. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  7191. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  7192. } else {
  7193. BaseAlignment = GetAlignOfType(
  7194. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  7195. }
  7196. if (BaseAlignment < Align) {
  7197. Result.Designator.setInvalid();
  7198. // FIXME: Add support to Diagnostic for long / long long.
  7199. CCEDiag(E->getArg(0),
  7200. diag::note_constexpr_baa_insufficient_alignment) << 0
  7201. << (unsigned)BaseAlignment.getQuantity()
  7202. << (unsigned)Align.getQuantity();
  7203. return false;
  7204. }
  7205. }
  7206. // The offset must also have the correct alignment.
  7207. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  7208. Result.Designator.setInvalid();
  7209. (OffsetResult.Base
  7210. ? CCEDiag(E->getArg(0),
  7211. diag::note_constexpr_baa_insufficient_alignment) << 1
  7212. : CCEDiag(E->getArg(0),
  7213. diag::note_constexpr_baa_value_insufficient_alignment))
  7214. << (int)OffsetResult.Offset.getQuantity()
  7215. << (unsigned)Align.getQuantity();
  7216. return false;
  7217. }
  7218. return true;
  7219. }
  7220. case Builtin::BI__builtin_operator_new:
  7221. return HandleOperatorNewCall(Info, E, Result);
  7222. case Builtin::BI__builtin_launder:
  7223. return evaluatePointer(E->getArg(0), Result);
  7224. case Builtin::BIstrchr:
  7225. case Builtin::BIwcschr:
  7226. case Builtin::BImemchr:
  7227. case Builtin::BIwmemchr:
  7228. if (Info.getLangOpts().CPlusPlus11)
  7229. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7230. << /*isConstexpr*/0 << /*isConstructor*/0
  7231. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7232. else
  7233. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7234. LLVM_FALLTHROUGH;
  7235. case Builtin::BI__builtin_strchr:
  7236. case Builtin::BI__builtin_wcschr:
  7237. case Builtin::BI__builtin_memchr:
  7238. case Builtin::BI__builtin_char_memchr:
  7239. case Builtin::BI__builtin_wmemchr: {
  7240. if (!Visit(E->getArg(0)))
  7241. return false;
  7242. APSInt Desired;
  7243. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  7244. return false;
  7245. uint64_t MaxLength = uint64_t(-1);
  7246. if (BuiltinOp != Builtin::BIstrchr &&
  7247. BuiltinOp != Builtin::BIwcschr &&
  7248. BuiltinOp != Builtin::BI__builtin_strchr &&
  7249. BuiltinOp != Builtin::BI__builtin_wcschr) {
  7250. APSInt N;
  7251. if (!EvaluateInteger(E->getArg(2), N, Info))
  7252. return false;
  7253. MaxLength = N.getExtValue();
  7254. }
  7255. // We cannot find the value if there are no candidates to match against.
  7256. if (MaxLength == 0u)
  7257. return ZeroInitialization(E);
  7258. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  7259. Result.Designator.Invalid)
  7260. return false;
  7261. QualType CharTy = Result.Designator.getType(Info.Ctx);
  7262. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  7263. BuiltinOp == Builtin::BI__builtin_memchr;
  7264. assert(IsRawByte ||
  7265. Info.Ctx.hasSameUnqualifiedType(
  7266. CharTy, E->getArg(0)->getType()->getPointeeType()));
  7267. // Pointers to const void may point to objects of incomplete type.
  7268. if (IsRawByte && CharTy->isIncompleteType()) {
  7269. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  7270. return false;
  7271. }
  7272. // Give up on byte-oriented matching against multibyte elements.
  7273. // FIXME: We can compare the bytes in the correct order.
  7274. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  7275. return false;
  7276. // Figure out what value we're actually looking for (after converting to
  7277. // the corresponding unsigned type if necessary).
  7278. uint64_t DesiredVal;
  7279. bool StopAtNull = false;
  7280. switch (BuiltinOp) {
  7281. case Builtin::BIstrchr:
  7282. case Builtin::BI__builtin_strchr:
  7283. // strchr compares directly to the passed integer, and therefore
  7284. // always fails if given an int that is not a char.
  7285. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  7286. E->getArg(1)->getType(),
  7287. Desired),
  7288. Desired))
  7289. return ZeroInitialization(E);
  7290. StopAtNull = true;
  7291. LLVM_FALLTHROUGH;
  7292. case Builtin::BImemchr:
  7293. case Builtin::BI__builtin_memchr:
  7294. case Builtin::BI__builtin_char_memchr:
  7295. // memchr compares by converting both sides to unsigned char. That's also
  7296. // correct for strchr if we get this far (to cope with plain char being
  7297. // unsigned in the strchr case).
  7298. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  7299. break;
  7300. case Builtin::BIwcschr:
  7301. case Builtin::BI__builtin_wcschr:
  7302. StopAtNull = true;
  7303. LLVM_FALLTHROUGH;
  7304. case Builtin::BIwmemchr:
  7305. case Builtin::BI__builtin_wmemchr:
  7306. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  7307. DesiredVal = Desired.getZExtValue();
  7308. break;
  7309. }
  7310. for (; MaxLength; --MaxLength) {
  7311. APValue Char;
  7312. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  7313. !Char.isInt())
  7314. return false;
  7315. if (Char.getInt().getZExtValue() == DesiredVal)
  7316. return true;
  7317. if (StopAtNull && !Char.getInt())
  7318. break;
  7319. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  7320. return false;
  7321. }
  7322. // Not found: return nullptr.
  7323. return ZeroInitialization(E);
  7324. }
  7325. case Builtin::BImemcpy:
  7326. case Builtin::BImemmove:
  7327. case Builtin::BIwmemcpy:
  7328. case Builtin::BIwmemmove:
  7329. if (Info.getLangOpts().CPlusPlus11)
  7330. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7331. << /*isConstexpr*/0 << /*isConstructor*/0
  7332. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7333. else
  7334. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7335. LLVM_FALLTHROUGH;
  7336. case Builtin::BI__builtin_memcpy:
  7337. case Builtin::BI__builtin_memmove:
  7338. case Builtin::BI__builtin_wmemcpy:
  7339. case Builtin::BI__builtin_wmemmove: {
  7340. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  7341. BuiltinOp == Builtin::BIwmemmove ||
  7342. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  7343. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7344. bool Move = BuiltinOp == Builtin::BImemmove ||
  7345. BuiltinOp == Builtin::BIwmemmove ||
  7346. BuiltinOp == Builtin::BI__builtin_memmove ||
  7347. BuiltinOp == Builtin::BI__builtin_wmemmove;
  7348. // The result of mem* is the first argument.
  7349. if (!Visit(E->getArg(0)))
  7350. return false;
  7351. LValue Dest = Result;
  7352. LValue Src;
  7353. if (!EvaluatePointer(E->getArg(1), Src, Info))
  7354. return false;
  7355. APSInt N;
  7356. if (!EvaluateInteger(E->getArg(2), N, Info))
  7357. return false;
  7358. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  7359. // If the size is zero, we treat this as always being a valid no-op.
  7360. // (Even if one of the src and dest pointers is null.)
  7361. if (!N)
  7362. return true;
  7363. // Otherwise, if either of the operands is null, we can't proceed. Don't
  7364. // try to determine the type of the copied objects, because there aren't
  7365. // any.
  7366. if (!Src.Base || !Dest.Base) {
  7367. APValue Val;
  7368. (!Src.Base ? Src : Dest).moveInto(Val);
  7369. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  7370. << Move << WChar << !!Src.Base
  7371. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  7372. return false;
  7373. }
  7374. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  7375. return false;
  7376. // We require that Src and Dest are both pointers to arrays of
  7377. // trivially-copyable type. (For the wide version, the designator will be
  7378. // invalid if the designated object is not a wchar_t.)
  7379. QualType T = Dest.Designator.getType(Info.Ctx);
  7380. QualType SrcT = Src.Designator.getType(Info.Ctx);
  7381. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  7382. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  7383. return false;
  7384. }
  7385. if (T->isIncompleteType()) {
  7386. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  7387. return false;
  7388. }
  7389. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  7390. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  7391. return false;
  7392. }
  7393. // Figure out how many T's we're copying.
  7394. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  7395. if (!WChar) {
  7396. uint64_t Remainder;
  7397. llvm::APInt OrigN = N;
  7398. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  7399. if (Remainder) {
  7400. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7401. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  7402. << (unsigned)TSize;
  7403. return false;
  7404. }
  7405. }
  7406. // Check that the copying will remain within the arrays, just so that we
  7407. // can give a more meaningful diagnostic. This implicitly also checks that
  7408. // N fits into 64 bits.
  7409. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  7410. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  7411. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  7412. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  7413. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  7414. << N.toString(10, /*Signed*/false);
  7415. return false;
  7416. }
  7417. uint64_t NElems = N.getZExtValue();
  7418. uint64_t NBytes = NElems * TSize;
  7419. // Check for overlap.
  7420. int Direction = 1;
  7421. if (HasSameBase(Src, Dest)) {
  7422. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  7423. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  7424. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  7425. // Dest is inside the source region.
  7426. if (!Move) {
  7427. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7428. return false;
  7429. }
  7430. // For memmove and friends, copy backwards.
  7431. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  7432. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  7433. return false;
  7434. Direction = -1;
  7435. } else if (!Move && SrcOffset >= DestOffset &&
  7436. SrcOffset - DestOffset < NBytes) {
  7437. // Src is inside the destination region for memcpy: invalid.
  7438. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  7439. return false;
  7440. }
  7441. }
  7442. while (true) {
  7443. APValue Val;
  7444. // FIXME: Set WantObjectRepresentation to true if we're copying a
  7445. // char-like type?
  7446. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  7447. !handleAssignment(Info, E, Dest, T, Val))
  7448. return false;
  7449. // Do not iterate past the last element; if we're copying backwards, that
  7450. // might take us off the start of the array.
  7451. if (--NElems == 0)
  7452. return true;
  7453. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  7454. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  7455. return false;
  7456. }
  7457. }
  7458. default:
  7459. break;
  7460. }
  7461. return visitNonBuiltinCallExpr(E);
  7462. }
  7463. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  7464. APValue &Result, const InitListExpr *ILE,
  7465. QualType AllocType);
  7466. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  7467. if (!Info.getLangOpts().CPlusPlus2a)
  7468. Info.CCEDiag(E, diag::note_constexpr_new);
  7469. // We cannot speculatively evaluate a delete expression.
  7470. if (Info.SpeculativeEvaluationDepth)
  7471. return false;
  7472. FunctionDecl *OperatorNew = E->getOperatorNew();
  7473. bool IsNothrow = false;
  7474. bool IsPlacement = false;
  7475. if (OperatorNew->isReservedGlobalPlacementOperator() &&
  7476. Info.CurrentCall->isStdFunction() && !E->isArray()) {
  7477. // FIXME Support array placement new.
  7478. assert(E->getNumPlacementArgs() == 1);
  7479. if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
  7480. return false;
  7481. if (Result.Designator.Invalid)
  7482. return false;
  7483. IsPlacement = true;
  7484. } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  7485. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  7486. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  7487. return false;
  7488. } else if (E->getNumPlacementArgs()) {
  7489. // The only new-placement list we support is of the form (std::nothrow).
  7490. //
  7491. // FIXME: There is no restriction on this, but it's not clear that any
  7492. // other form makes any sense. We get here for cases such as:
  7493. //
  7494. // new (std::align_val_t{N}) X(int)
  7495. //
  7496. // (which should presumably be valid only if N is a multiple of
  7497. // alignof(int), and in any case can't be deallocated unless N is
  7498. // alignof(X) and X has new-extended alignment).
  7499. if (E->getNumPlacementArgs() != 1 ||
  7500. !E->getPlacementArg(0)->getType()->isNothrowT())
  7501. return Error(E, diag::note_constexpr_new_placement);
  7502. LValue Nothrow;
  7503. if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
  7504. return false;
  7505. IsNothrow = true;
  7506. }
  7507. const Expr *Init = E->getInitializer();
  7508. const InitListExpr *ResizedArrayILE = nullptr;
  7509. QualType AllocType = E->getAllocatedType();
  7510. if (Optional<const Expr*> ArraySize = E->getArraySize()) {
  7511. const Expr *Stripped = *ArraySize;
  7512. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  7513. Stripped = ICE->getSubExpr())
  7514. if (ICE->getCastKind() != CK_NoOp &&
  7515. ICE->getCastKind() != CK_IntegralCast)
  7516. break;
  7517. llvm::APSInt ArrayBound;
  7518. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  7519. return false;
  7520. // C++ [expr.new]p9:
  7521. // The expression is erroneous if:
  7522. // -- [...] its value before converting to size_t [or] applying the
  7523. // second standard conversion sequence is less than zero
  7524. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  7525. if (IsNothrow)
  7526. return ZeroInitialization(E);
  7527. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  7528. << ArrayBound << (*ArraySize)->getSourceRange();
  7529. return false;
  7530. }
  7531. // -- its value is such that the size of the allocated object would
  7532. // exceed the implementation-defined limit
  7533. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  7534. ArrayBound) >
  7535. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  7536. if (IsNothrow)
  7537. return ZeroInitialization(E);
  7538. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  7539. << ArrayBound << (*ArraySize)->getSourceRange();
  7540. return false;
  7541. }
  7542. // -- the new-initializer is a braced-init-list and the number of
  7543. // array elements for which initializers are provided [...]
  7544. // exceeds the number of elements to initialize
  7545. if (Init) {
  7546. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  7547. assert(CAT && "unexpected type for array initializer");
  7548. unsigned Bits =
  7549. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  7550. llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
  7551. llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
  7552. if (InitBound.ugt(AllocBound)) {
  7553. if (IsNothrow)
  7554. return ZeroInitialization(E);
  7555. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  7556. << AllocBound.toString(10, /*Signed=*/false)
  7557. << InitBound.toString(10, /*Signed=*/false)
  7558. << (*ArraySize)->getSourceRange();
  7559. return false;
  7560. }
  7561. // If the sizes differ, we must have an initializer list, and we need
  7562. // special handling for this case when we initialize.
  7563. if (InitBound != AllocBound)
  7564. ResizedArrayILE = cast<InitListExpr>(Init);
  7565. }
  7566. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
  7567. ArrayType::Normal, 0);
  7568. } else {
  7569. assert(!AllocType->isArrayType() &&
  7570. "array allocation with non-array new");
  7571. }
  7572. APValue *Val;
  7573. if (IsPlacement) {
  7574. AccessKinds AK = AK_Construct;
  7575. struct FindObjectHandler {
  7576. EvalInfo &Info;
  7577. const Expr *E;
  7578. QualType AllocType;
  7579. const AccessKinds AccessKind;
  7580. APValue *Value;
  7581. typedef bool result_type;
  7582. bool failed() { return false; }
  7583. bool found(APValue &Subobj, QualType SubobjType) {
  7584. // FIXME: Reject the cases where [basic.life]p8 would not permit the
  7585. // old name of the object to be used to name the new object.
  7586. if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
  7587. Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
  7588. SubobjType << AllocType;
  7589. return false;
  7590. }
  7591. Value = &Subobj;
  7592. return true;
  7593. }
  7594. bool found(APSInt &Value, QualType SubobjType) {
  7595. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  7596. return false;
  7597. }
  7598. bool found(APFloat &Value, QualType SubobjType) {
  7599. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  7600. return false;
  7601. }
  7602. } Handler = {Info, E, AllocType, AK, nullptr};
  7603. CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
  7604. if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
  7605. return false;
  7606. Val = Handler.Value;
  7607. // [basic.life]p1:
  7608. // The lifetime of an object o of type T ends when [...] the storage
  7609. // which the object occupies is [...] reused by an object that is not
  7610. // nested within o (6.6.2).
  7611. *Val = APValue();
  7612. } else {
  7613. // Perform the allocation and obtain a pointer to the resulting object.
  7614. Val = Info.createHeapAlloc(E, AllocType, Result);
  7615. if (!Val)
  7616. return false;
  7617. }
  7618. if (ResizedArrayILE) {
  7619. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  7620. AllocType))
  7621. return false;
  7622. } else if (Init) {
  7623. if (!EvaluateInPlace(*Val, Info, Result, Init))
  7624. return false;
  7625. } else {
  7626. *Val = getDefaultInitValue(AllocType);
  7627. }
  7628. // Array new returns a pointer to the first element, not a pointer to the
  7629. // array.
  7630. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  7631. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  7632. return true;
  7633. }
  7634. //===----------------------------------------------------------------------===//
  7635. // Member Pointer Evaluation
  7636. //===----------------------------------------------------------------------===//
  7637. namespace {
  7638. class MemberPointerExprEvaluator
  7639. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  7640. MemberPtr &Result;
  7641. bool Success(const ValueDecl *D) {
  7642. Result = MemberPtr(D);
  7643. return true;
  7644. }
  7645. public:
  7646. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  7647. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  7648. bool Success(const APValue &V, const Expr *E) {
  7649. Result.setFrom(V);
  7650. return true;
  7651. }
  7652. bool ZeroInitialization(const Expr *E) {
  7653. return Success((const ValueDecl*)nullptr);
  7654. }
  7655. bool VisitCastExpr(const CastExpr *E);
  7656. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7657. };
  7658. } // end anonymous namespace
  7659. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  7660. EvalInfo &Info) {
  7661. assert(E->isRValue() && E->getType()->isMemberPointerType());
  7662. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  7663. }
  7664. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7665. switch (E->getCastKind()) {
  7666. default:
  7667. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7668. case CK_NullToMemberPointer:
  7669. VisitIgnoredValue(E->getSubExpr());
  7670. return ZeroInitialization(E);
  7671. case CK_BaseToDerivedMemberPointer: {
  7672. if (!Visit(E->getSubExpr()))
  7673. return false;
  7674. if (E->path_empty())
  7675. return true;
  7676. // Base-to-derived member pointer casts store the path in derived-to-base
  7677. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  7678. // the wrong end of the derived->base arc, so stagger the path by one class.
  7679. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  7680. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  7681. PathI != PathE; ++PathI) {
  7682. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7683. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  7684. if (!Result.castToDerived(Derived))
  7685. return Error(E);
  7686. }
  7687. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  7688. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  7689. return Error(E);
  7690. return true;
  7691. }
  7692. case CK_DerivedToBaseMemberPointer:
  7693. if (!Visit(E->getSubExpr()))
  7694. return false;
  7695. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7696. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7697. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  7698. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7699. if (!Result.castToBase(Base))
  7700. return Error(E);
  7701. }
  7702. return true;
  7703. }
  7704. }
  7705. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7706. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  7707. // member can be formed.
  7708. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  7709. }
  7710. //===----------------------------------------------------------------------===//
  7711. // Record Evaluation
  7712. //===----------------------------------------------------------------------===//
  7713. namespace {
  7714. class RecordExprEvaluator
  7715. : public ExprEvaluatorBase<RecordExprEvaluator> {
  7716. const LValue &This;
  7717. APValue &Result;
  7718. public:
  7719. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  7720. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  7721. bool Success(const APValue &V, const Expr *E) {
  7722. Result = V;
  7723. return true;
  7724. }
  7725. bool ZeroInitialization(const Expr *E) {
  7726. return ZeroInitialization(E, E->getType());
  7727. }
  7728. bool ZeroInitialization(const Expr *E, QualType T);
  7729. bool VisitCallExpr(const CallExpr *E) {
  7730. return handleCallExpr(E, Result, &This);
  7731. }
  7732. bool VisitCastExpr(const CastExpr *E);
  7733. bool VisitInitListExpr(const InitListExpr *E);
  7734. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7735. return VisitCXXConstructExpr(E, E->getType());
  7736. }
  7737. bool VisitLambdaExpr(const LambdaExpr *E);
  7738. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  7739. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  7740. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  7741. bool VisitBinCmp(const BinaryOperator *E);
  7742. };
  7743. }
  7744. /// Perform zero-initialization on an object of non-union class type.
  7745. /// C++11 [dcl.init]p5:
  7746. /// To zero-initialize an object or reference of type T means:
  7747. /// [...]
  7748. /// -- if T is a (possibly cv-qualified) non-union class type,
  7749. /// each non-static data member and each base-class subobject is
  7750. /// zero-initialized
  7751. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  7752. const RecordDecl *RD,
  7753. const LValue &This, APValue &Result) {
  7754. assert(!RD->isUnion() && "Expected non-union class type");
  7755. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  7756. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  7757. std::distance(RD->field_begin(), RD->field_end()));
  7758. if (RD->isInvalidDecl()) return false;
  7759. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7760. if (CD) {
  7761. unsigned Index = 0;
  7762. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  7763. End = CD->bases_end(); I != End; ++I, ++Index) {
  7764. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  7765. LValue Subobject = This;
  7766. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  7767. return false;
  7768. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  7769. Result.getStructBase(Index)))
  7770. return false;
  7771. }
  7772. }
  7773. for (const auto *I : RD->fields()) {
  7774. // -- if T is a reference type, no initialization is performed.
  7775. if (I->getType()->isReferenceType())
  7776. continue;
  7777. LValue Subobject = This;
  7778. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  7779. return false;
  7780. ImplicitValueInitExpr VIE(I->getType());
  7781. if (!EvaluateInPlace(
  7782. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  7783. return false;
  7784. }
  7785. return true;
  7786. }
  7787. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  7788. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  7789. if (RD->isInvalidDecl()) return false;
  7790. if (RD->isUnion()) {
  7791. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  7792. // object's first non-static named data member is zero-initialized
  7793. RecordDecl::field_iterator I = RD->field_begin();
  7794. if (I == RD->field_end()) {
  7795. Result = APValue((const FieldDecl*)nullptr);
  7796. return true;
  7797. }
  7798. LValue Subobject = This;
  7799. if (!HandleLValueMember(Info, E, Subobject, *I))
  7800. return false;
  7801. Result = APValue(*I);
  7802. ImplicitValueInitExpr VIE(I->getType());
  7803. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  7804. }
  7805. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  7806. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  7807. return false;
  7808. }
  7809. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  7810. }
  7811. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7812. switch (E->getCastKind()) {
  7813. default:
  7814. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7815. case CK_ConstructorConversion:
  7816. return Visit(E->getSubExpr());
  7817. case CK_DerivedToBase:
  7818. case CK_UncheckedDerivedToBase: {
  7819. APValue DerivedObject;
  7820. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  7821. return false;
  7822. if (!DerivedObject.isStruct())
  7823. return Error(E->getSubExpr());
  7824. // Derived-to-base rvalue conversion: just slice off the derived part.
  7825. APValue *Value = &DerivedObject;
  7826. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  7827. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  7828. PathE = E->path_end(); PathI != PathE; ++PathI) {
  7829. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  7830. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  7831. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  7832. RD = Base;
  7833. }
  7834. Result = *Value;
  7835. return true;
  7836. }
  7837. }
  7838. }
  7839. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7840. if (E->isTransparent())
  7841. return Visit(E->getInit(0));
  7842. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  7843. if (RD->isInvalidDecl()) return false;
  7844. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  7845. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  7846. EvalInfo::EvaluatingConstructorRAII EvalObj(
  7847. Info,
  7848. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  7849. CXXRD && CXXRD->getNumBases());
  7850. if (RD->isUnion()) {
  7851. const FieldDecl *Field = E->getInitializedFieldInUnion();
  7852. Result = APValue(Field);
  7853. if (!Field)
  7854. return true;
  7855. // If the initializer list for a union does not contain any elements, the
  7856. // first element of the union is value-initialized.
  7857. // FIXME: The element should be initialized from an initializer list.
  7858. // Is this difference ever observable for initializer lists which
  7859. // we don't build?
  7860. ImplicitValueInitExpr VIE(Field->getType());
  7861. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  7862. LValue Subobject = This;
  7863. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  7864. return false;
  7865. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7866. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7867. isa<CXXDefaultInitExpr>(InitExpr));
  7868. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  7869. }
  7870. if (!Result.hasValue())
  7871. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  7872. std::distance(RD->field_begin(), RD->field_end()));
  7873. unsigned ElementNo = 0;
  7874. bool Success = true;
  7875. // Initialize base classes.
  7876. if (CXXRD && CXXRD->getNumBases()) {
  7877. for (const auto &Base : CXXRD->bases()) {
  7878. assert(ElementNo < E->getNumInits() && "missing init for base class");
  7879. const Expr *Init = E->getInit(ElementNo);
  7880. LValue Subobject = This;
  7881. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  7882. return false;
  7883. APValue &FieldVal = Result.getStructBase(ElementNo);
  7884. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  7885. if (!Info.noteFailure())
  7886. return false;
  7887. Success = false;
  7888. }
  7889. ++ElementNo;
  7890. }
  7891. EvalObj.finishedConstructingBases();
  7892. }
  7893. // Initialize members.
  7894. for (const auto *Field : RD->fields()) {
  7895. // Anonymous bit-fields are not considered members of the class for
  7896. // purposes of aggregate initialization.
  7897. if (Field->isUnnamedBitfield())
  7898. continue;
  7899. LValue Subobject = This;
  7900. bool HaveInit = ElementNo < E->getNumInits();
  7901. // FIXME: Diagnostics here should point to the end of the initializer
  7902. // list, not the start.
  7903. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  7904. Subobject, Field, &Layout))
  7905. return false;
  7906. // Perform an implicit value-initialization for members beyond the end of
  7907. // the initializer list.
  7908. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  7909. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  7910. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  7911. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  7912. isa<CXXDefaultInitExpr>(Init));
  7913. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  7914. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  7915. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  7916. FieldVal, Field))) {
  7917. if (!Info.noteFailure())
  7918. return false;
  7919. Success = false;
  7920. }
  7921. }
  7922. return Success;
  7923. }
  7924. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7925. QualType T) {
  7926. // Note that E's type is not necessarily the type of our class here; we might
  7927. // be initializing an array element instead.
  7928. const CXXConstructorDecl *FD = E->getConstructor();
  7929. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  7930. bool ZeroInit = E->requiresZeroInitialization();
  7931. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  7932. // If we've already performed zero-initialization, we're already done.
  7933. if (Result.hasValue())
  7934. return true;
  7935. if (ZeroInit)
  7936. return ZeroInitialization(E, T);
  7937. Result = getDefaultInitValue(T);
  7938. return true;
  7939. }
  7940. const FunctionDecl *Definition = nullptr;
  7941. auto Body = FD->getBody(Definition);
  7942. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7943. return false;
  7944. // Avoid materializing a temporary for an elidable copy/move constructor.
  7945. if (E->isElidable() && !ZeroInit)
  7946. if (const MaterializeTemporaryExpr *ME
  7947. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  7948. return Visit(ME->GetTemporaryExpr());
  7949. if (ZeroInit && !ZeroInitialization(E, T))
  7950. return false;
  7951. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  7952. return HandleConstructorCall(E, This, Args,
  7953. cast<CXXConstructorDecl>(Definition), Info,
  7954. Result);
  7955. }
  7956. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  7957. const CXXInheritedCtorInitExpr *E) {
  7958. if (!Info.CurrentCall) {
  7959. assert(Info.checkingPotentialConstantExpression());
  7960. return false;
  7961. }
  7962. const CXXConstructorDecl *FD = E->getConstructor();
  7963. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  7964. return false;
  7965. const FunctionDecl *Definition = nullptr;
  7966. auto Body = FD->getBody(Definition);
  7967. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  7968. return false;
  7969. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  7970. cast<CXXConstructorDecl>(Definition), Info,
  7971. Result);
  7972. }
  7973. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  7974. const CXXStdInitializerListExpr *E) {
  7975. const ConstantArrayType *ArrayType =
  7976. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  7977. LValue Array;
  7978. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  7979. return false;
  7980. // Get a pointer to the first element of the array.
  7981. Array.addArray(Info, E, ArrayType);
  7982. // FIXME: Perform the checks on the field types in SemaInit.
  7983. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  7984. RecordDecl::field_iterator Field = Record->field_begin();
  7985. if (Field == Record->field_end())
  7986. return Error(E);
  7987. // Start pointer.
  7988. if (!Field->getType()->isPointerType() ||
  7989. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7990. ArrayType->getElementType()))
  7991. return Error(E);
  7992. // FIXME: What if the initializer_list type has base classes, etc?
  7993. Result = APValue(APValue::UninitStruct(), 0, 2);
  7994. Array.moveInto(Result.getStructField(0));
  7995. if (++Field == Record->field_end())
  7996. return Error(E);
  7997. if (Field->getType()->isPointerType() &&
  7998. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  7999. ArrayType->getElementType())) {
  8000. // End pointer.
  8001. if (!HandleLValueArrayAdjustment(Info, E, Array,
  8002. ArrayType->getElementType(),
  8003. ArrayType->getSize().getZExtValue()))
  8004. return false;
  8005. Array.moveInto(Result.getStructField(1));
  8006. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  8007. // Length.
  8008. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  8009. else
  8010. return Error(E);
  8011. if (++Field != Record->field_end())
  8012. return Error(E);
  8013. return true;
  8014. }
  8015. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  8016. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  8017. if (ClosureClass->isInvalidDecl())
  8018. return false;
  8019. const size_t NumFields =
  8020. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  8021. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  8022. E->capture_init_end()) &&
  8023. "The number of lambda capture initializers should equal the number of "
  8024. "fields within the closure type");
  8025. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  8026. // Iterate through all the lambda's closure object's fields and initialize
  8027. // them.
  8028. auto *CaptureInitIt = E->capture_init_begin();
  8029. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  8030. bool Success = true;
  8031. for (const auto *Field : ClosureClass->fields()) {
  8032. assert(CaptureInitIt != E->capture_init_end());
  8033. // Get the initializer for this field
  8034. Expr *const CurFieldInit = *CaptureInitIt++;
  8035. // If there is no initializer, either this is a VLA or an error has
  8036. // occurred.
  8037. if (!CurFieldInit)
  8038. return Error(E);
  8039. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  8040. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  8041. if (!Info.keepEvaluatingAfterFailure())
  8042. return false;
  8043. Success = false;
  8044. }
  8045. ++CaptureIt;
  8046. }
  8047. return Success;
  8048. }
  8049. static bool EvaluateRecord(const Expr *E, const LValue &This,
  8050. APValue &Result, EvalInfo &Info) {
  8051. assert(E->isRValue() && E->getType()->isRecordType() &&
  8052. "can't evaluate expression as a record rvalue");
  8053. return RecordExprEvaluator(Info, This, Result).Visit(E);
  8054. }
  8055. //===----------------------------------------------------------------------===//
  8056. // Temporary Evaluation
  8057. //
  8058. // Temporaries are represented in the AST as rvalues, but generally behave like
  8059. // lvalues. The full-object of which the temporary is a subobject is implicitly
  8060. // materialized so that a reference can bind to it.
  8061. //===----------------------------------------------------------------------===//
  8062. namespace {
  8063. class TemporaryExprEvaluator
  8064. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  8065. public:
  8066. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  8067. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  8068. /// Visit an expression which constructs the value of this temporary.
  8069. bool VisitConstructExpr(const Expr *E) {
  8070. APValue &Value =
  8071. Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
  8072. return EvaluateInPlace(Value, Info, Result, E);
  8073. }
  8074. bool VisitCastExpr(const CastExpr *E) {
  8075. switch (E->getCastKind()) {
  8076. default:
  8077. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  8078. case CK_ConstructorConversion:
  8079. return VisitConstructExpr(E->getSubExpr());
  8080. }
  8081. }
  8082. bool VisitInitListExpr(const InitListExpr *E) {
  8083. return VisitConstructExpr(E);
  8084. }
  8085. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8086. return VisitConstructExpr(E);
  8087. }
  8088. bool VisitCallExpr(const CallExpr *E) {
  8089. return VisitConstructExpr(E);
  8090. }
  8091. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  8092. return VisitConstructExpr(E);
  8093. }
  8094. bool VisitLambdaExpr(const LambdaExpr *E) {
  8095. return VisitConstructExpr(E);
  8096. }
  8097. };
  8098. } // end anonymous namespace
  8099. /// Evaluate an expression of record type as a temporary.
  8100. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  8101. assert(E->isRValue() && E->getType()->isRecordType());
  8102. return TemporaryExprEvaluator(Info, Result).Visit(E);
  8103. }
  8104. //===----------------------------------------------------------------------===//
  8105. // Vector Evaluation
  8106. //===----------------------------------------------------------------------===//
  8107. namespace {
  8108. class VectorExprEvaluator
  8109. : public ExprEvaluatorBase<VectorExprEvaluator> {
  8110. APValue &Result;
  8111. public:
  8112. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  8113. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8114. bool Success(ArrayRef<APValue> V, const Expr *E) {
  8115. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  8116. // FIXME: remove this APValue copy.
  8117. Result = APValue(V.data(), V.size());
  8118. return true;
  8119. }
  8120. bool Success(const APValue &V, const Expr *E) {
  8121. assert(V.isVector());
  8122. Result = V;
  8123. return true;
  8124. }
  8125. bool ZeroInitialization(const Expr *E);
  8126. bool VisitUnaryReal(const UnaryOperator *E)
  8127. { return Visit(E->getSubExpr()); }
  8128. bool VisitCastExpr(const CastExpr* E);
  8129. bool VisitInitListExpr(const InitListExpr *E);
  8130. bool VisitUnaryImag(const UnaryOperator *E);
  8131. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  8132. // binary comparisons, binary and/or/xor,
  8133. // shufflevector, ExtVectorElementExpr
  8134. };
  8135. } // end anonymous namespace
  8136. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  8137. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  8138. return VectorExprEvaluator(Info, Result).Visit(E);
  8139. }
  8140. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8141. const VectorType *VTy = E->getType()->castAs<VectorType>();
  8142. unsigned NElts = VTy->getNumElements();
  8143. const Expr *SE = E->getSubExpr();
  8144. QualType SETy = SE->getType();
  8145. switch (E->getCastKind()) {
  8146. case CK_VectorSplat: {
  8147. APValue Val = APValue();
  8148. if (SETy->isIntegerType()) {
  8149. APSInt IntResult;
  8150. if (!EvaluateInteger(SE, IntResult, Info))
  8151. return false;
  8152. Val = APValue(std::move(IntResult));
  8153. } else if (SETy->isRealFloatingType()) {
  8154. APFloat FloatResult(0.0);
  8155. if (!EvaluateFloat(SE, FloatResult, Info))
  8156. return false;
  8157. Val = APValue(std::move(FloatResult));
  8158. } else {
  8159. return Error(E);
  8160. }
  8161. // Splat and create vector APValue.
  8162. SmallVector<APValue, 4> Elts(NElts, Val);
  8163. return Success(Elts, E);
  8164. }
  8165. case CK_BitCast: {
  8166. // Evaluate the operand into an APInt we can extract from.
  8167. llvm::APInt SValInt;
  8168. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  8169. return false;
  8170. // Extract the elements
  8171. QualType EltTy = VTy->getElementType();
  8172. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  8173. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  8174. SmallVector<APValue, 4> Elts;
  8175. if (EltTy->isRealFloatingType()) {
  8176. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  8177. unsigned FloatEltSize = EltSize;
  8178. if (&Sem == &APFloat::x87DoubleExtended())
  8179. FloatEltSize = 80;
  8180. for (unsigned i = 0; i < NElts; i++) {
  8181. llvm::APInt Elt;
  8182. if (BigEndian)
  8183. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  8184. else
  8185. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  8186. Elts.push_back(APValue(APFloat(Sem, Elt)));
  8187. }
  8188. } else if (EltTy->isIntegerType()) {
  8189. for (unsigned i = 0; i < NElts; i++) {
  8190. llvm::APInt Elt;
  8191. if (BigEndian)
  8192. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  8193. else
  8194. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  8195. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  8196. }
  8197. } else {
  8198. return Error(E);
  8199. }
  8200. return Success(Elts, E);
  8201. }
  8202. default:
  8203. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8204. }
  8205. }
  8206. bool
  8207. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  8208. const VectorType *VT = E->getType()->castAs<VectorType>();
  8209. unsigned NumInits = E->getNumInits();
  8210. unsigned NumElements = VT->getNumElements();
  8211. QualType EltTy = VT->getElementType();
  8212. SmallVector<APValue, 4> Elements;
  8213. // The number of initializers can be less than the number of
  8214. // vector elements. For OpenCL, this can be due to nested vector
  8215. // initialization. For GCC compatibility, missing trailing elements
  8216. // should be initialized with zeroes.
  8217. unsigned CountInits = 0, CountElts = 0;
  8218. while (CountElts < NumElements) {
  8219. // Handle nested vector initialization.
  8220. if (CountInits < NumInits
  8221. && E->getInit(CountInits)->getType()->isVectorType()) {
  8222. APValue v;
  8223. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  8224. return Error(E);
  8225. unsigned vlen = v.getVectorLength();
  8226. for (unsigned j = 0; j < vlen; j++)
  8227. Elements.push_back(v.getVectorElt(j));
  8228. CountElts += vlen;
  8229. } else if (EltTy->isIntegerType()) {
  8230. llvm::APSInt sInt(32);
  8231. if (CountInits < NumInits) {
  8232. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  8233. return false;
  8234. } else // trailing integer zero.
  8235. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  8236. Elements.push_back(APValue(sInt));
  8237. CountElts++;
  8238. } else {
  8239. llvm::APFloat f(0.0);
  8240. if (CountInits < NumInits) {
  8241. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  8242. return false;
  8243. } else // trailing float zero.
  8244. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  8245. Elements.push_back(APValue(f));
  8246. CountElts++;
  8247. }
  8248. CountInits++;
  8249. }
  8250. return Success(Elements, E);
  8251. }
  8252. bool
  8253. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  8254. const auto *VT = E->getType()->castAs<VectorType>();
  8255. QualType EltTy = VT->getElementType();
  8256. APValue ZeroElement;
  8257. if (EltTy->isIntegerType())
  8258. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  8259. else
  8260. ZeroElement =
  8261. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  8262. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  8263. return Success(Elements, E);
  8264. }
  8265. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8266. VisitIgnoredValue(E->getSubExpr());
  8267. return ZeroInitialization(E);
  8268. }
  8269. //===----------------------------------------------------------------------===//
  8270. // Array Evaluation
  8271. //===----------------------------------------------------------------------===//
  8272. namespace {
  8273. class ArrayExprEvaluator
  8274. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  8275. const LValue &This;
  8276. APValue &Result;
  8277. public:
  8278. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  8279. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  8280. bool Success(const APValue &V, const Expr *E) {
  8281. assert(V.isArray() && "expected array");
  8282. Result = V;
  8283. return true;
  8284. }
  8285. bool ZeroInitialization(const Expr *E) {
  8286. const ConstantArrayType *CAT =
  8287. Info.Ctx.getAsConstantArrayType(E->getType());
  8288. if (!CAT)
  8289. return Error(E);
  8290. Result = APValue(APValue::UninitArray(), 0,
  8291. CAT->getSize().getZExtValue());
  8292. if (!Result.hasArrayFiller()) return true;
  8293. // Zero-initialize all elements.
  8294. LValue Subobject = This;
  8295. Subobject.addArray(Info, E, CAT);
  8296. ImplicitValueInitExpr VIE(CAT->getElementType());
  8297. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  8298. }
  8299. bool VisitCallExpr(const CallExpr *E) {
  8300. return handleCallExpr(E, Result, &This);
  8301. }
  8302. bool VisitInitListExpr(const InitListExpr *E,
  8303. QualType AllocType = QualType());
  8304. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  8305. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  8306. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  8307. const LValue &Subobject,
  8308. APValue *Value, QualType Type);
  8309. bool VisitStringLiteral(const StringLiteral *E,
  8310. QualType AllocType = QualType()) {
  8311. expandStringLiteral(Info, E, Result, AllocType);
  8312. return true;
  8313. }
  8314. };
  8315. } // end anonymous namespace
  8316. static bool EvaluateArray(const Expr *E, const LValue &This,
  8317. APValue &Result, EvalInfo &Info) {
  8318. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  8319. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  8320. }
  8321. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  8322. APValue &Result, const InitListExpr *ILE,
  8323. QualType AllocType) {
  8324. assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
  8325. "not an array rvalue");
  8326. return ArrayExprEvaluator(Info, This, Result)
  8327. .VisitInitListExpr(ILE, AllocType);
  8328. }
  8329. // Return true iff the given array filler may depend on the element index.
  8330. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  8331. // For now, just whitelist non-class value-initialization and initialization
  8332. // lists comprised of them.
  8333. if (isa<ImplicitValueInitExpr>(FillerExpr))
  8334. return false;
  8335. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  8336. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  8337. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  8338. return true;
  8339. }
  8340. return false;
  8341. }
  8342. return true;
  8343. }
  8344. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  8345. QualType AllocType) {
  8346. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  8347. AllocType.isNull() ? E->getType() : AllocType);
  8348. if (!CAT)
  8349. return Error(E);
  8350. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  8351. // an appropriately-typed string literal enclosed in braces.
  8352. if (E->isStringLiteralInit()) {
  8353. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
  8354. // FIXME: Support ObjCEncodeExpr here once we support it in
  8355. // ArrayExprEvaluator generally.
  8356. if (!SL)
  8357. return Error(E);
  8358. return VisitStringLiteral(SL, AllocType);
  8359. }
  8360. bool Success = true;
  8361. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  8362. "zero-initialized array shouldn't have any initialized elts");
  8363. APValue Filler;
  8364. if (Result.isArray() && Result.hasArrayFiller())
  8365. Filler = Result.getArrayFiller();
  8366. unsigned NumEltsToInit = E->getNumInits();
  8367. unsigned NumElts = CAT->getSize().getZExtValue();
  8368. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  8369. // If the initializer might depend on the array index, run it for each
  8370. // array element.
  8371. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  8372. NumEltsToInit = NumElts;
  8373. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  8374. << NumEltsToInit << ".\n");
  8375. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  8376. // If the array was previously zero-initialized, preserve the
  8377. // zero-initialized values.
  8378. if (Filler.hasValue()) {
  8379. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  8380. Result.getArrayInitializedElt(I) = Filler;
  8381. if (Result.hasArrayFiller())
  8382. Result.getArrayFiller() = Filler;
  8383. }
  8384. LValue Subobject = This;
  8385. Subobject.addArray(Info, E, CAT);
  8386. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  8387. const Expr *Init =
  8388. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  8389. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8390. Info, Subobject, Init) ||
  8391. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  8392. CAT->getElementType(), 1)) {
  8393. if (!Info.noteFailure())
  8394. return false;
  8395. Success = false;
  8396. }
  8397. }
  8398. if (!Result.hasArrayFiller())
  8399. return Success;
  8400. // If we get here, we have a trivial filler, which we can just evaluate
  8401. // once and splat over the rest of the array elements.
  8402. assert(FillerExpr && "no array filler for incomplete init list");
  8403. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  8404. FillerExpr) && Success;
  8405. }
  8406. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  8407. LValue CommonLV;
  8408. if (E->getCommonExpr() &&
  8409. !Evaluate(Info.CurrentCall->createTemporary(
  8410. E->getCommonExpr(),
  8411. getStorageType(Info.Ctx, E->getCommonExpr()), false,
  8412. CommonLV),
  8413. Info, E->getCommonExpr()->getSourceExpr()))
  8414. return false;
  8415. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  8416. uint64_t Elements = CAT->getSize().getZExtValue();
  8417. Result = APValue(APValue::UninitArray(), Elements, Elements);
  8418. LValue Subobject = This;
  8419. Subobject.addArray(Info, E, CAT);
  8420. bool Success = true;
  8421. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  8422. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  8423. Info, Subobject, E->getSubExpr()) ||
  8424. !HandleLValueArrayAdjustment(Info, E, Subobject,
  8425. CAT->getElementType(), 1)) {
  8426. if (!Info.noteFailure())
  8427. return false;
  8428. Success = false;
  8429. }
  8430. }
  8431. return Success;
  8432. }
  8433. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8434. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  8435. }
  8436. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8437. const LValue &Subobject,
  8438. APValue *Value,
  8439. QualType Type) {
  8440. bool HadZeroInit = Value->hasValue();
  8441. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  8442. unsigned N = CAT->getSize().getZExtValue();
  8443. // Preserve the array filler if we had prior zero-initialization.
  8444. APValue Filler =
  8445. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  8446. : APValue();
  8447. *Value = APValue(APValue::UninitArray(), N, N);
  8448. if (HadZeroInit)
  8449. for (unsigned I = 0; I != N; ++I)
  8450. Value->getArrayInitializedElt(I) = Filler;
  8451. // Initialize the elements.
  8452. LValue ArrayElt = Subobject;
  8453. ArrayElt.addArray(Info, E, CAT);
  8454. for (unsigned I = 0; I != N; ++I)
  8455. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  8456. CAT->getElementType()) ||
  8457. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  8458. CAT->getElementType(), 1))
  8459. return false;
  8460. return true;
  8461. }
  8462. if (!Type->isRecordType())
  8463. return Error(E);
  8464. return RecordExprEvaluator(Info, Subobject, *Value)
  8465. .VisitCXXConstructExpr(E, Type);
  8466. }
  8467. //===----------------------------------------------------------------------===//
  8468. // Integer Evaluation
  8469. //
  8470. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  8471. // types and back in constant folding. Integer values are thus represented
  8472. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  8473. //===----------------------------------------------------------------------===//
  8474. namespace {
  8475. class IntExprEvaluator
  8476. : public ExprEvaluatorBase<IntExprEvaluator> {
  8477. APValue &Result;
  8478. public:
  8479. IntExprEvaluator(EvalInfo &info, APValue &result)
  8480. : ExprEvaluatorBaseTy(info), Result(result) {}
  8481. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  8482. assert(E->getType()->isIntegralOrEnumerationType() &&
  8483. "Invalid evaluation result.");
  8484. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  8485. "Invalid evaluation result.");
  8486. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8487. "Invalid evaluation result.");
  8488. Result = APValue(SI);
  8489. return true;
  8490. }
  8491. bool Success(const llvm::APSInt &SI, const Expr *E) {
  8492. return Success(SI, E, Result);
  8493. }
  8494. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  8495. assert(E->getType()->isIntegralOrEnumerationType() &&
  8496. "Invalid evaluation result.");
  8497. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8498. "Invalid evaluation result.");
  8499. Result = APValue(APSInt(I));
  8500. Result.getInt().setIsUnsigned(
  8501. E->getType()->isUnsignedIntegerOrEnumerationType());
  8502. return true;
  8503. }
  8504. bool Success(const llvm::APInt &I, const Expr *E) {
  8505. return Success(I, E, Result);
  8506. }
  8507. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8508. assert(E->getType()->isIntegralOrEnumerationType() &&
  8509. "Invalid evaluation result.");
  8510. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  8511. return true;
  8512. }
  8513. bool Success(uint64_t Value, const Expr *E) {
  8514. return Success(Value, E, Result);
  8515. }
  8516. bool Success(CharUnits Size, const Expr *E) {
  8517. return Success(Size.getQuantity(), E);
  8518. }
  8519. bool Success(const APValue &V, const Expr *E) {
  8520. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  8521. Result = V;
  8522. return true;
  8523. }
  8524. return Success(V.getInt(), E);
  8525. }
  8526. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  8527. //===--------------------------------------------------------------------===//
  8528. // Visitor Methods
  8529. //===--------------------------------------------------------------------===//
  8530. bool VisitConstantExpr(const ConstantExpr *E);
  8531. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  8532. return Success(E->getValue(), E);
  8533. }
  8534. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  8535. return Success(E->getValue(), E);
  8536. }
  8537. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  8538. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  8539. if (CheckReferencedDecl(E, E->getDecl()))
  8540. return true;
  8541. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  8542. }
  8543. bool VisitMemberExpr(const MemberExpr *E) {
  8544. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  8545. VisitIgnoredBaseExpression(E->getBase());
  8546. return true;
  8547. }
  8548. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  8549. }
  8550. bool VisitCallExpr(const CallExpr *E);
  8551. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  8552. bool VisitBinaryOperator(const BinaryOperator *E);
  8553. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  8554. bool VisitUnaryOperator(const UnaryOperator *E);
  8555. bool VisitCastExpr(const CastExpr* E);
  8556. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  8557. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  8558. return Success(E->getValue(), E);
  8559. }
  8560. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  8561. return Success(E->getValue(), E);
  8562. }
  8563. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  8564. if (Info.ArrayInitIndex == uint64_t(-1)) {
  8565. // We were asked to evaluate this subexpression independent of the
  8566. // enclosing ArrayInitLoopExpr. We can't do that.
  8567. Info.FFDiag(E);
  8568. return false;
  8569. }
  8570. return Success(Info.ArrayInitIndex, E);
  8571. }
  8572. // Note, GNU defines __null as an integer, not a pointer.
  8573. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  8574. return ZeroInitialization(E);
  8575. }
  8576. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  8577. return Success(E->getValue(), E);
  8578. }
  8579. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  8580. return Success(E->getValue(), E);
  8581. }
  8582. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  8583. return Success(E->getValue(), E);
  8584. }
  8585. bool VisitUnaryReal(const UnaryOperator *E);
  8586. bool VisitUnaryImag(const UnaryOperator *E);
  8587. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  8588. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  8589. bool VisitSourceLocExpr(const SourceLocExpr *E);
  8590. bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
  8591. // FIXME: Missing: array subscript of vector, member of vector
  8592. };
  8593. class FixedPointExprEvaluator
  8594. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  8595. APValue &Result;
  8596. public:
  8597. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  8598. : ExprEvaluatorBaseTy(info), Result(result) {}
  8599. bool Success(const llvm::APInt &I, const Expr *E) {
  8600. return Success(
  8601. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8602. }
  8603. bool Success(uint64_t Value, const Expr *E) {
  8604. return Success(
  8605. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  8606. }
  8607. bool Success(const APValue &V, const Expr *E) {
  8608. return Success(V.getFixedPoint(), E);
  8609. }
  8610. bool Success(const APFixedPoint &V, const Expr *E) {
  8611. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  8612. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  8613. "Invalid evaluation result.");
  8614. Result = APValue(V);
  8615. return true;
  8616. }
  8617. //===--------------------------------------------------------------------===//
  8618. // Visitor Methods
  8619. //===--------------------------------------------------------------------===//
  8620. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  8621. return Success(E->getValue(), E);
  8622. }
  8623. bool VisitCastExpr(const CastExpr *E);
  8624. bool VisitUnaryOperator(const UnaryOperator *E);
  8625. bool VisitBinaryOperator(const BinaryOperator *E);
  8626. };
  8627. } // end anonymous namespace
  8628. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  8629. /// produce either the integer value or a pointer.
  8630. ///
  8631. /// GCC has a heinous extension which folds casts between pointer types and
  8632. /// pointer-sized integral types. We support this by allowing the evaluation of
  8633. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  8634. /// Some simple arithmetic on such values is supported (they are treated much
  8635. /// like char*).
  8636. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  8637. EvalInfo &Info) {
  8638. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  8639. return IntExprEvaluator(Info, Result).Visit(E);
  8640. }
  8641. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  8642. APValue Val;
  8643. if (!EvaluateIntegerOrLValue(E, Val, Info))
  8644. return false;
  8645. if (!Val.isInt()) {
  8646. // FIXME: It would be better to produce the diagnostic for casting
  8647. // a pointer to an integer.
  8648. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8649. return false;
  8650. }
  8651. Result = Val.getInt();
  8652. return true;
  8653. }
  8654. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  8655. APValue Evaluated = E->EvaluateInContext(
  8656. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  8657. return Success(Evaluated, E);
  8658. }
  8659. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  8660. EvalInfo &Info) {
  8661. if (E->getType()->isFixedPointType()) {
  8662. APValue Val;
  8663. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  8664. return false;
  8665. if (!Val.isFixedPoint())
  8666. return false;
  8667. Result = Val.getFixedPoint();
  8668. return true;
  8669. }
  8670. return false;
  8671. }
  8672. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  8673. EvalInfo &Info) {
  8674. if (E->getType()->isIntegerType()) {
  8675. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  8676. APSInt Val;
  8677. if (!EvaluateInteger(E, Val, Info))
  8678. return false;
  8679. Result = APFixedPoint(Val, FXSema);
  8680. return true;
  8681. } else if (E->getType()->isFixedPointType()) {
  8682. return EvaluateFixedPoint(E, Result, Info);
  8683. }
  8684. return false;
  8685. }
  8686. /// Check whether the given declaration can be directly converted to an integral
  8687. /// rvalue. If not, no diagnostic is produced; there are other things we can
  8688. /// try.
  8689. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  8690. // Enums are integer constant exprs.
  8691. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  8692. // Check for signedness/width mismatches between E type and ECD value.
  8693. bool SameSign = (ECD->getInitVal().isSigned()
  8694. == E->getType()->isSignedIntegerOrEnumerationType());
  8695. bool SameWidth = (ECD->getInitVal().getBitWidth()
  8696. == Info.Ctx.getIntWidth(E->getType()));
  8697. if (SameSign && SameWidth)
  8698. return Success(ECD->getInitVal(), E);
  8699. else {
  8700. // Get rid of mismatch (otherwise Success assertions will fail)
  8701. // by computing a new value matching the type of E.
  8702. llvm::APSInt Val = ECD->getInitVal();
  8703. if (!SameSign)
  8704. Val.setIsSigned(!ECD->getInitVal().isSigned());
  8705. if (!SameWidth)
  8706. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  8707. return Success(Val, E);
  8708. }
  8709. }
  8710. return false;
  8711. }
  8712. /// Values returned by __builtin_classify_type, chosen to match the values
  8713. /// produced by GCC's builtin.
  8714. enum class GCCTypeClass {
  8715. None = -1,
  8716. Void = 0,
  8717. Integer = 1,
  8718. // GCC reserves 2 for character types, but instead classifies them as
  8719. // integers.
  8720. Enum = 3,
  8721. Bool = 4,
  8722. Pointer = 5,
  8723. // GCC reserves 6 for references, but appears to never use it (because
  8724. // expressions never have reference type, presumably).
  8725. PointerToDataMember = 7,
  8726. RealFloat = 8,
  8727. Complex = 9,
  8728. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  8729. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8730. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  8731. // uses 12 for that purpose, same as for a class or struct. Maybe it
  8732. // internally implements a pointer to member as a struct? Who knows.
  8733. PointerToMemberFunction = 12, // Not a bug, see above.
  8734. ClassOrStruct = 12,
  8735. Union = 13,
  8736. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  8737. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  8738. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  8739. // literals.
  8740. };
  8741. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8742. /// as GCC.
  8743. static GCCTypeClass
  8744. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  8745. assert(!T->isDependentType() && "unexpected dependent type");
  8746. QualType CanTy = T.getCanonicalType();
  8747. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  8748. switch (CanTy->getTypeClass()) {
  8749. #define TYPE(ID, BASE)
  8750. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8751. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  8752. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  8753. #include "clang/AST/TypeNodes.inc"
  8754. case Type::Auto:
  8755. case Type::DeducedTemplateSpecialization:
  8756. llvm_unreachable("unexpected non-canonical or dependent type");
  8757. case Type::Builtin:
  8758. switch (BT->getKind()) {
  8759. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  8760. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  8761. case BuiltinType::ID: return GCCTypeClass::Integer;
  8762. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  8763. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  8764. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  8765. case BuiltinType::ID: break;
  8766. #include "clang/AST/BuiltinTypes.def"
  8767. case BuiltinType::Void:
  8768. return GCCTypeClass::Void;
  8769. case BuiltinType::Bool:
  8770. return GCCTypeClass::Bool;
  8771. case BuiltinType::Char_U:
  8772. case BuiltinType::UChar:
  8773. case BuiltinType::WChar_U:
  8774. case BuiltinType::Char8:
  8775. case BuiltinType::Char16:
  8776. case BuiltinType::Char32:
  8777. case BuiltinType::UShort:
  8778. case BuiltinType::UInt:
  8779. case BuiltinType::ULong:
  8780. case BuiltinType::ULongLong:
  8781. case BuiltinType::UInt128:
  8782. return GCCTypeClass::Integer;
  8783. case BuiltinType::UShortAccum:
  8784. case BuiltinType::UAccum:
  8785. case BuiltinType::ULongAccum:
  8786. case BuiltinType::UShortFract:
  8787. case BuiltinType::UFract:
  8788. case BuiltinType::ULongFract:
  8789. case BuiltinType::SatUShortAccum:
  8790. case BuiltinType::SatUAccum:
  8791. case BuiltinType::SatULongAccum:
  8792. case BuiltinType::SatUShortFract:
  8793. case BuiltinType::SatUFract:
  8794. case BuiltinType::SatULongFract:
  8795. return GCCTypeClass::None;
  8796. case BuiltinType::NullPtr:
  8797. case BuiltinType::ObjCId:
  8798. case BuiltinType::ObjCClass:
  8799. case BuiltinType::ObjCSel:
  8800. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  8801. case BuiltinType::Id:
  8802. #include "clang/Basic/OpenCLImageTypes.def"
  8803. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  8804. case BuiltinType::Id:
  8805. #include "clang/Basic/OpenCLExtensionTypes.def"
  8806. case BuiltinType::OCLSampler:
  8807. case BuiltinType::OCLEvent:
  8808. case BuiltinType::OCLClkEvent:
  8809. case BuiltinType::OCLQueue:
  8810. case BuiltinType::OCLReserveID:
  8811. #define SVE_TYPE(Name, Id, SingletonId) \
  8812. case BuiltinType::Id:
  8813. #include "clang/Basic/AArch64SVEACLETypes.def"
  8814. return GCCTypeClass::None;
  8815. case BuiltinType::Dependent:
  8816. llvm_unreachable("unexpected dependent type");
  8817. };
  8818. llvm_unreachable("unexpected placeholder type");
  8819. case Type::Enum:
  8820. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  8821. case Type::Pointer:
  8822. case Type::ConstantArray:
  8823. case Type::VariableArray:
  8824. case Type::IncompleteArray:
  8825. case Type::FunctionNoProto:
  8826. case Type::FunctionProto:
  8827. return GCCTypeClass::Pointer;
  8828. case Type::MemberPointer:
  8829. return CanTy->isMemberDataPointerType()
  8830. ? GCCTypeClass::PointerToDataMember
  8831. : GCCTypeClass::PointerToMemberFunction;
  8832. case Type::Complex:
  8833. return GCCTypeClass::Complex;
  8834. case Type::Record:
  8835. return CanTy->isUnionType() ? GCCTypeClass::Union
  8836. : GCCTypeClass::ClassOrStruct;
  8837. case Type::Atomic:
  8838. // GCC classifies _Atomic T the same as T.
  8839. return EvaluateBuiltinClassifyType(
  8840. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  8841. case Type::BlockPointer:
  8842. case Type::Vector:
  8843. case Type::ExtVector:
  8844. case Type::ObjCObject:
  8845. case Type::ObjCInterface:
  8846. case Type::ObjCObjectPointer:
  8847. case Type::Pipe:
  8848. // GCC classifies vectors as None. We follow its lead and classify all
  8849. // other types that don't fit into the regular classification the same way.
  8850. return GCCTypeClass::None;
  8851. case Type::LValueReference:
  8852. case Type::RValueReference:
  8853. llvm_unreachable("invalid type for expression");
  8854. }
  8855. llvm_unreachable("unexpected type class");
  8856. }
  8857. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  8858. /// as GCC.
  8859. static GCCTypeClass
  8860. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  8861. // If no argument was supplied, default to None. This isn't
  8862. // ideal, however it is what gcc does.
  8863. if (E->getNumArgs() == 0)
  8864. return GCCTypeClass::None;
  8865. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  8866. // being an ICE, but still folds it to a constant using the type of the first
  8867. // argument.
  8868. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  8869. }
  8870. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  8871. /// __builtin_constant_p when applied to the given pointer.
  8872. ///
  8873. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  8874. /// or it points to the first character of a string literal.
  8875. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  8876. APValue::LValueBase Base = LV.getLValueBase();
  8877. if (Base.isNull()) {
  8878. // A null base is acceptable.
  8879. return true;
  8880. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  8881. if (!isa<StringLiteral>(E))
  8882. return false;
  8883. return LV.getLValueOffset().isZero();
  8884. } else if (Base.is<TypeInfoLValue>()) {
  8885. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  8886. // evaluate to true.
  8887. return true;
  8888. } else {
  8889. // Any other base is not constant enough for GCC.
  8890. return false;
  8891. }
  8892. }
  8893. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  8894. /// GCC as we can manage.
  8895. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  8896. // This evaluation is not permitted to have side-effects, so evaluate it in
  8897. // a speculative evaluation context.
  8898. SpeculativeEvaluationRAII SpeculativeEval(Info);
  8899. // Constant-folding is always enabled for the operand of __builtin_constant_p
  8900. // (even when the enclosing evaluation context otherwise requires a strict
  8901. // language-specific constant expression).
  8902. FoldConstant Fold(Info, true);
  8903. QualType ArgType = Arg->getType();
  8904. // __builtin_constant_p always has one operand. The rules which gcc follows
  8905. // are not precisely documented, but are as follows:
  8906. //
  8907. // - If the operand is of integral, floating, complex or enumeration type,
  8908. // and can be folded to a known value of that type, it returns 1.
  8909. // - If the operand can be folded to a pointer to the first character
  8910. // of a string literal (or such a pointer cast to an integral type)
  8911. // or to a null pointer or an integer cast to a pointer, it returns 1.
  8912. //
  8913. // Otherwise, it returns 0.
  8914. //
  8915. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  8916. // its support for this did not work prior to GCC 9 and is not yet well
  8917. // understood.
  8918. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  8919. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  8920. ArgType->isNullPtrType()) {
  8921. APValue V;
  8922. if (!::EvaluateAsRValue(Info, Arg, V)) {
  8923. Fold.keepDiagnostics();
  8924. return false;
  8925. }
  8926. // For a pointer (possibly cast to integer), there are special rules.
  8927. if (V.getKind() == APValue::LValue)
  8928. return EvaluateBuiltinConstantPForLValue(V);
  8929. // Otherwise, any constant value is good enough.
  8930. return V.hasValue();
  8931. }
  8932. // Anything else isn't considered to be sufficiently constant.
  8933. return false;
  8934. }
  8935. /// Retrieves the "underlying object type" of the given expression,
  8936. /// as used by __builtin_object_size.
  8937. static QualType getObjectType(APValue::LValueBase B) {
  8938. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  8939. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  8940. return VD->getType();
  8941. } else if (const Expr *E = B.get<const Expr*>()) {
  8942. if (isa<CompoundLiteralExpr>(E))
  8943. return E->getType();
  8944. } else if (B.is<TypeInfoLValue>()) {
  8945. return B.getTypeInfoType();
  8946. } else if (B.is<DynamicAllocLValue>()) {
  8947. return B.getDynamicAllocType();
  8948. }
  8949. return QualType();
  8950. }
  8951. /// A more selective version of E->IgnoreParenCasts for
  8952. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  8953. /// to change the type of E.
  8954. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  8955. ///
  8956. /// Always returns an RValue with a pointer representation.
  8957. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  8958. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  8959. auto *NoParens = E->IgnoreParens();
  8960. auto *Cast = dyn_cast<CastExpr>(NoParens);
  8961. if (Cast == nullptr)
  8962. return NoParens;
  8963. // We only conservatively allow a few kinds of casts, because this code is
  8964. // inherently a simple solution that seeks to support the common case.
  8965. auto CastKind = Cast->getCastKind();
  8966. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  8967. CastKind != CK_AddressSpaceConversion)
  8968. return NoParens;
  8969. auto *SubExpr = Cast->getSubExpr();
  8970. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  8971. return NoParens;
  8972. return ignorePointerCastsAndParens(SubExpr);
  8973. }
  8974. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  8975. /// record layout. e.g.
  8976. /// struct { struct { int a, b; } fst, snd; } obj;
  8977. /// obj.fst // no
  8978. /// obj.snd // yes
  8979. /// obj.fst.a // no
  8980. /// obj.fst.b // no
  8981. /// obj.snd.a // no
  8982. /// obj.snd.b // yes
  8983. ///
  8984. /// Please note: this function is specialized for how __builtin_object_size
  8985. /// views "objects".
  8986. ///
  8987. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  8988. /// correct result, it will always return true.
  8989. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  8990. assert(!LVal.Designator.Invalid);
  8991. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  8992. const RecordDecl *Parent = FD->getParent();
  8993. Invalid = Parent->isInvalidDecl();
  8994. if (Invalid || Parent->isUnion())
  8995. return true;
  8996. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  8997. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  8998. };
  8999. auto &Base = LVal.getLValueBase();
  9000. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  9001. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  9002. bool Invalid;
  9003. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  9004. return Invalid;
  9005. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  9006. for (auto *FD : IFD->chain()) {
  9007. bool Invalid;
  9008. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  9009. return Invalid;
  9010. }
  9011. }
  9012. }
  9013. unsigned I = 0;
  9014. QualType BaseType = getType(Base);
  9015. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  9016. // If we don't know the array bound, conservatively assume we're looking at
  9017. // the final array element.
  9018. ++I;
  9019. if (BaseType->isIncompleteArrayType())
  9020. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  9021. else
  9022. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  9023. }
  9024. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  9025. const auto &Entry = LVal.Designator.Entries[I];
  9026. if (BaseType->isArrayType()) {
  9027. // Because __builtin_object_size treats arrays as objects, we can ignore
  9028. // the index iff this is the last array in the Designator.
  9029. if (I + 1 == E)
  9030. return true;
  9031. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  9032. uint64_t Index = Entry.getAsArrayIndex();
  9033. if (Index + 1 != CAT->getSize())
  9034. return false;
  9035. BaseType = CAT->getElementType();
  9036. } else if (BaseType->isAnyComplexType()) {
  9037. const auto *CT = BaseType->castAs<ComplexType>();
  9038. uint64_t Index = Entry.getAsArrayIndex();
  9039. if (Index != 1)
  9040. return false;
  9041. BaseType = CT->getElementType();
  9042. } else if (auto *FD = getAsField(Entry)) {
  9043. bool Invalid;
  9044. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  9045. return Invalid;
  9046. BaseType = FD->getType();
  9047. } else {
  9048. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  9049. return false;
  9050. }
  9051. }
  9052. return true;
  9053. }
  9054. /// Tests to see if the LValue has a user-specified designator (that isn't
  9055. /// necessarily valid). Note that this always returns 'true' if the LValue has
  9056. /// an unsized array as its first designator entry, because there's currently no
  9057. /// way to tell if the user typed *foo or foo[0].
  9058. static bool refersToCompleteObject(const LValue &LVal) {
  9059. if (LVal.Designator.Invalid)
  9060. return false;
  9061. if (!LVal.Designator.Entries.empty())
  9062. return LVal.Designator.isMostDerivedAnUnsizedArray();
  9063. if (!LVal.InvalidBase)
  9064. return true;
  9065. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  9066. // the LValueBase.
  9067. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  9068. return !E || !isa<MemberExpr>(E);
  9069. }
  9070. /// Attempts to detect a user writing into a piece of memory that's impossible
  9071. /// to figure out the size of by just using types.
  9072. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  9073. const SubobjectDesignator &Designator = LVal.Designator;
  9074. // Notes:
  9075. // - Users can only write off of the end when we have an invalid base. Invalid
  9076. // bases imply we don't know where the memory came from.
  9077. // - We used to be a bit more aggressive here; we'd only be conservative if
  9078. // the array at the end was flexible, or if it had 0 or 1 elements. This
  9079. // broke some common standard library extensions (PR30346), but was
  9080. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  9081. // with some sort of whitelist. OTOH, it seems that GCC is always
  9082. // conservative with the last element in structs (if it's an array), so our
  9083. // current behavior is more compatible than a whitelisting approach would
  9084. // be.
  9085. return LVal.InvalidBase &&
  9086. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  9087. Designator.MostDerivedIsArrayElement &&
  9088. isDesignatorAtObjectEnd(Ctx, LVal);
  9089. }
  9090. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  9091. /// Fails if the conversion would cause loss of precision.
  9092. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  9093. CharUnits &Result) {
  9094. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  9095. if (Int.ugt(CharUnitsMax))
  9096. return false;
  9097. Result = CharUnits::fromQuantity(Int.getZExtValue());
  9098. return true;
  9099. }
  9100. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  9101. /// determine how many bytes exist from the beginning of the object to either
  9102. /// the end of the current subobject, or the end of the object itself, depending
  9103. /// on what the LValue looks like + the value of Type.
  9104. ///
  9105. /// If this returns false, the value of Result is undefined.
  9106. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  9107. unsigned Type, const LValue &LVal,
  9108. CharUnits &EndOffset) {
  9109. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  9110. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  9111. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  9112. return false;
  9113. return HandleSizeof(Info, ExprLoc, Ty, Result);
  9114. };
  9115. // We want to evaluate the size of the entire object. This is a valid fallback
  9116. // for when Type=1 and the designator is invalid, because we're asked for an
  9117. // upper-bound.
  9118. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  9119. // Type=3 wants a lower bound, so we can't fall back to this.
  9120. if (Type == 3 && !DetermineForCompleteObject)
  9121. return false;
  9122. llvm::APInt APEndOffset;
  9123. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  9124. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  9125. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  9126. if (LVal.InvalidBase)
  9127. return false;
  9128. QualType BaseTy = getObjectType(LVal.getLValueBase());
  9129. return CheckedHandleSizeof(BaseTy, EndOffset);
  9130. }
  9131. // We want to evaluate the size of a subobject.
  9132. const SubobjectDesignator &Designator = LVal.Designator;
  9133. // The following is a moderately common idiom in C:
  9134. //
  9135. // struct Foo { int a; char c[1]; };
  9136. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  9137. // strcpy(&F->c[0], Bar);
  9138. //
  9139. // In order to not break too much legacy code, we need to support it.
  9140. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  9141. // If we can resolve this to an alloc_size call, we can hand that back,
  9142. // because we know for certain how many bytes there are to write to.
  9143. llvm::APInt APEndOffset;
  9144. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  9145. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  9146. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  9147. // If we cannot determine the size of the initial allocation, then we can't
  9148. // given an accurate upper-bound. However, we are still able to give
  9149. // conservative lower-bounds for Type=3.
  9150. if (Type == 1)
  9151. return false;
  9152. }
  9153. CharUnits BytesPerElem;
  9154. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  9155. return false;
  9156. // According to the GCC documentation, we want the size of the subobject
  9157. // denoted by the pointer. But that's not quite right -- what we actually
  9158. // want is the size of the immediately-enclosing array, if there is one.
  9159. int64_t ElemsRemaining;
  9160. if (Designator.MostDerivedIsArrayElement &&
  9161. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  9162. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  9163. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  9164. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  9165. } else {
  9166. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  9167. }
  9168. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  9169. return true;
  9170. }
  9171. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  9172. /// returns true and stores the result in @p Size.
  9173. ///
  9174. /// If @p WasError is non-null, this will report whether the failure to evaluate
  9175. /// is to be treated as an Error in IntExprEvaluator.
  9176. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  9177. EvalInfo &Info, uint64_t &Size) {
  9178. // Determine the denoted object.
  9179. LValue LVal;
  9180. {
  9181. // The operand of __builtin_object_size is never evaluated for side-effects.
  9182. // If there are any, but we can determine the pointed-to object anyway, then
  9183. // ignore the side-effects.
  9184. SpeculativeEvaluationRAII SpeculativeEval(Info);
  9185. IgnoreSideEffectsRAII Fold(Info);
  9186. if (E->isGLValue()) {
  9187. // It's possible for us to be given GLValues if we're called via
  9188. // Expr::tryEvaluateObjectSize.
  9189. APValue RVal;
  9190. if (!EvaluateAsRValue(Info, E, RVal))
  9191. return false;
  9192. LVal.setFrom(Info.Ctx, RVal);
  9193. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  9194. /*InvalidBaseOK=*/true))
  9195. return false;
  9196. }
  9197. // If we point to before the start of the object, there are no accessible
  9198. // bytes.
  9199. if (LVal.getLValueOffset().isNegative()) {
  9200. Size = 0;
  9201. return true;
  9202. }
  9203. CharUnits EndOffset;
  9204. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  9205. return false;
  9206. // If we've fallen outside of the end offset, just pretend there's nothing to
  9207. // write to/read from.
  9208. if (EndOffset <= LVal.getLValueOffset())
  9209. Size = 0;
  9210. else
  9211. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  9212. return true;
  9213. }
  9214. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  9215. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  9216. if (E->getResultAPValueKind() != APValue::None)
  9217. return Success(E->getAPValueResult(), E);
  9218. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  9219. }
  9220. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  9221. if (unsigned BuiltinOp = E->getBuiltinCallee())
  9222. return VisitBuiltinCallExpr(E, BuiltinOp);
  9223. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9224. }
  9225. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  9226. unsigned BuiltinOp) {
  9227. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  9228. default:
  9229. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9230. case Builtin::BI__builtin_dynamic_object_size:
  9231. case Builtin::BI__builtin_object_size: {
  9232. // The type was checked when we built the expression.
  9233. unsigned Type =
  9234. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  9235. assert(Type <= 3 && "unexpected type");
  9236. uint64_t Size;
  9237. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  9238. return Success(Size, E);
  9239. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  9240. return Success((Type & 2) ? 0 : -1, E);
  9241. // Expression had no side effects, but we couldn't statically determine the
  9242. // size of the referenced object.
  9243. switch (Info.EvalMode) {
  9244. case EvalInfo::EM_ConstantExpression:
  9245. case EvalInfo::EM_ConstantFold:
  9246. case EvalInfo::EM_IgnoreSideEffects:
  9247. // Leave it to IR generation.
  9248. return Error(E);
  9249. case EvalInfo::EM_ConstantExpressionUnevaluated:
  9250. // Reduce it to a constant now.
  9251. return Success((Type & 2) ? 0 : -1, E);
  9252. }
  9253. llvm_unreachable("unexpected EvalMode");
  9254. }
  9255. case Builtin::BI__builtin_os_log_format_buffer_size: {
  9256. analyze_os_log::OSLogBufferLayout Layout;
  9257. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  9258. return Success(Layout.size().getQuantity(), E);
  9259. }
  9260. case Builtin::BI__builtin_bswap16:
  9261. case Builtin::BI__builtin_bswap32:
  9262. case Builtin::BI__builtin_bswap64: {
  9263. APSInt Val;
  9264. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9265. return false;
  9266. return Success(Val.byteSwap(), E);
  9267. }
  9268. case Builtin::BI__builtin_classify_type:
  9269. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  9270. case Builtin::BI__builtin_clrsb:
  9271. case Builtin::BI__builtin_clrsbl:
  9272. case Builtin::BI__builtin_clrsbll: {
  9273. APSInt Val;
  9274. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9275. return false;
  9276. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  9277. }
  9278. case Builtin::BI__builtin_clz:
  9279. case Builtin::BI__builtin_clzl:
  9280. case Builtin::BI__builtin_clzll:
  9281. case Builtin::BI__builtin_clzs: {
  9282. APSInt Val;
  9283. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9284. return false;
  9285. if (!Val)
  9286. return Error(E);
  9287. return Success(Val.countLeadingZeros(), E);
  9288. }
  9289. case Builtin::BI__builtin_constant_p: {
  9290. const Expr *Arg = E->getArg(0);
  9291. if (EvaluateBuiltinConstantP(Info, Arg))
  9292. return Success(true, E);
  9293. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  9294. // Outside a constant context, eagerly evaluate to false in the presence
  9295. // of side-effects in order to avoid -Wunsequenced false-positives in
  9296. // a branch on __builtin_constant_p(expr).
  9297. return Success(false, E);
  9298. }
  9299. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9300. return false;
  9301. }
  9302. case Builtin::BI__builtin_is_constant_evaluated:
  9303. return Success(Info.InConstantContext, E);
  9304. case Builtin::BI__builtin_ctz:
  9305. case Builtin::BI__builtin_ctzl:
  9306. case Builtin::BI__builtin_ctzll:
  9307. case Builtin::BI__builtin_ctzs: {
  9308. APSInt Val;
  9309. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9310. return false;
  9311. if (!Val)
  9312. return Error(E);
  9313. return Success(Val.countTrailingZeros(), E);
  9314. }
  9315. case Builtin::BI__builtin_eh_return_data_regno: {
  9316. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  9317. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  9318. return Success(Operand, E);
  9319. }
  9320. case Builtin::BI__builtin_expect:
  9321. return Visit(E->getArg(0));
  9322. case Builtin::BI__builtin_ffs:
  9323. case Builtin::BI__builtin_ffsl:
  9324. case Builtin::BI__builtin_ffsll: {
  9325. APSInt Val;
  9326. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9327. return false;
  9328. unsigned N = Val.countTrailingZeros();
  9329. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  9330. }
  9331. case Builtin::BI__builtin_fpclassify: {
  9332. APFloat Val(0.0);
  9333. if (!EvaluateFloat(E->getArg(5), Val, Info))
  9334. return false;
  9335. unsigned Arg;
  9336. switch (Val.getCategory()) {
  9337. case APFloat::fcNaN: Arg = 0; break;
  9338. case APFloat::fcInfinity: Arg = 1; break;
  9339. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  9340. case APFloat::fcZero: Arg = 4; break;
  9341. }
  9342. return Visit(E->getArg(Arg));
  9343. }
  9344. case Builtin::BI__builtin_isinf_sign: {
  9345. APFloat Val(0.0);
  9346. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9347. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  9348. }
  9349. case Builtin::BI__builtin_isinf: {
  9350. APFloat Val(0.0);
  9351. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9352. Success(Val.isInfinity() ? 1 : 0, E);
  9353. }
  9354. case Builtin::BI__builtin_isfinite: {
  9355. APFloat Val(0.0);
  9356. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9357. Success(Val.isFinite() ? 1 : 0, E);
  9358. }
  9359. case Builtin::BI__builtin_isnan: {
  9360. APFloat Val(0.0);
  9361. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9362. Success(Val.isNaN() ? 1 : 0, E);
  9363. }
  9364. case Builtin::BI__builtin_isnormal: {
  9365. APFloat Val(0.0);
  9366. return EvaluateFloat(E->getArg(0), Val, Info) &&
  9367. Success(Val.isNormal() ? 1 : 0, E);
  9368. }
  9369. case Builtin::BI__builtin_parity:
  9370. case Builtin::BI__builtin_parityl:
  9371. case Builtin::BI__builtin_parityll: {
  9372. APSInt Val;
  9373. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9374. return false;
  9375. return Success(Val.countPopulation() % 2, E);
  9376. }
  9377. case Builtin::BI__builtin_popcount:
  9378. case Builtin::BI__builtin_popcountl:
  9379. case Builtin::BI__builtin_popcountll: {
  9380. APSInt Val;
  9381. if (!EvaluateInteger(E->getArg(0), Val, Info))
  9382. return false;
  9383. return Success(Val.countPopulation(), E);
  9384. }
  9385. case Builtin::BIstrlen:
  9386. case Builtin::BIwcslen:
  9387. // A call to strlen is not a constant expression.
  9388. if (Info.getLangOpts().CPlusPlus11)
  9389. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9390. << /*isConstexpr*/0 << /*isConstructor*/0
  9391. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9392. else
  9393. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9394. LLVM_FALLTHROUGH;
  9395. case Builtin::BI__builtin_strlen:
  9396. case Builtin::BI__builtin_wcslen: {
  9397. // As an extension, we support __builtin_strlen() as a constant expression,
  9398. // and support folding strlen() to a constant.
  9399. LValue String;
  9400. if (!EvaluatePointer(E->getArg(0), String, Info))
  9401. return false;
  9402. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  9403. // Fast path: if it's a string literal, search the string value.
  9404. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  9405. String.getLValueBase().dyn_cast<const Expr *>())) {
  9406. // The string literal may have embedded null characters. Find the first
  9407. // one and truncate there.
  9408. StringRef Str = S->getBytes();
  9409. int64_t Off = String.Offset.getQuantity();
  9410. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  9411. S->getCharByteWidth() == 1 &&
  9412. // FIXME: Add fast-path for wchar_t too.
  9413. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  9414. Str = Str.substr(Off);
  9415. StringRef::size_type Pos = Str.find(0);
  9416. if (Pos != StringRef::npos)
  9417. Str = Str.substr(0, Pos);
  9418. return Success(Str.size(), E);
  9419. }
  9420. // Fall through to slow path to issue appropriate diagnostic.
  9421. }
  9422. // Slow path: scan the bytes of the string looking for the terminating 0.
  9423. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  9424. APValue Char;
  9425. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  9426. !Char.isInt())
  9427. return false;
  9428. if (!Char.getInt())
  9429. return Success(Strlen, E);
  9430. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  9431. return false;
  9432. }
  9433. }
  9434. case Builtin::BIstrcmp:
  9435. case Builtin::BIwcscmp:
  9436. case Builtin::BIstrncmp:
  9437. case Builtin::BIwcsncmp:
  9438. case Builtin::BImemcmp:
  9439. case Builtin::BIbcmp:
  9440. case Builtin::BIwmemcmp:
  9441. // A call to strlen is not a constant expression.
  9442. if (Info.getLangOpts().CPlusPlus11)
  9443. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  9444. << /*isConstexpr*/0 << /*isConstructor*/0
  9445. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  9446. else
  9447. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9448. LLVM_FALLTHROUGH;
  9449. case Builtin::BI__builtin_strcmp:
  9450. case Builtin::BI__builtin_wcscmp:
  9451. case Builtin::BI__builtin_strncmp:
  9452. case Builtin::BI__builtin_wcsncmp:
  9453. case Builtin::BI__builtin_memcmp:
  9454. case Builtin::BI__builtin_bcmp:
  9455. case Builtin::BI__builtin_wmemcmp: {
  9456. LValue String1, String2;
  9457. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  9458. !EvaluatePointer(E->getArg(1), String2, Info))
  9459. return false;
  9460. uint64_t MaxLength = uint64_t(-1);
  9461. if (BuiltinOp != Builtin::BIstrcmp &&
  9462. BuiltinOp != Builtin::BIwcscmp &&
  9463. BuiltinOp != Builtin::BI__builtin_strcmp &&
  9464. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  9465. APSInt N;
  9466. if (!EvaluateInteger(E->getArg(2), N, Info))
  9467. return false;
  9468. MaxLength = N.getExtValue();
  9469. }
  9470. // Empty substrings compare equal by definition.
  9471. if (MaxLength == 0u)
  9472. return Success(0, E);
  9473. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9474. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  9475. String1.Designator.Invalid || String2.Designator.Invalid)
  9476. return false;
  9477. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  9478. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  9479. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  9480. BuiltinOp == Builtin::BIbcmp ||
  9481. BuiltinOp == Builtin::BI__builtin_memcmp ||
  9482. BuiltinOp == Builtin::BI__builtin_bcmp;
  9483. assert(IsRawByte ||
  9484. (Info.Ctx.hasSameUnqualifiedType(
  9485. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  9486. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  9487. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  9488. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  9489. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  9490. Char1.isInt() && Char2.isInt();
  9491. };
  9492. const auto &AdvanceElems = [&] {
  9493. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  9494. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  9495. };
  9496. if (IsRawByte) {
  9497. uint64_t BytesRemaining = MaxLength;
  9498. // Pointers to const void may point to objects of incomplete type.
  9499. if (CharTy1->isIncompleteType()) {
  9500. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  9501. return false;
  9502. }
  9503. if (CharTy2->isIncompleteType()) {
  9504. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  9505. return false;
  9506. }
  9507. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  9508. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  9509. // Give up on comparing between elements with disparate widths.
  9510. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  9511. return false;
  9512. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  9513. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  9514. "following loop considers at least one element");
  9515. while (true) {
  9516. APValue Char1, Char2;
  9517. if (!ReadCurElems(Char1, Char2))
  9518. return false;
  9519. // We have compatible in-memory widths, but a possible type and
  9520. // (for `bool`) internal representation mismatch.
  9521. // Assuming two's complement representation, including 0 for `false` and
  9522. // 1 for `true`, we can check an appropriate number of elements for
  9523. // equality even if they are not byte-sized.
  9524. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  9525. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  9526. if (Char1InMem.ne(Char2InMem)) {
  9527. // If the elements are byte-sized, then we can produce a three-way
  9528. // comparison result in a straightforward manner.
  9529. if (BytesPerElement == 1u) {
  9530. // memcmp always compares unsigned chars.
  9531. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  9532. }
  9533. // The result is byte-order sensitive, and we have multibyte elements.
  9534. // FIXME: We can compare the remaining bytes in the correct order.
  9535. return false;
  9536. }
  9537. if (!AdvanceElems())
  9538. return false;
  9539. if (BytesRemaining <= BytesPerElement)
  9540. break;
  9541. BytesRemaining -= BytesPerElement;
  9542. }
  9543. // Enough elements are equal to account for the memcmp limit.
  9544. return Success(0, E);
  9545. }
  9546. bool StopAtNull =
  9547. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  9548. BuiltinOp != Builtin::BIwmemcmp &&
  9549. BuiltinOp != Builtin::BI__builtin_memcmp &&
  9550. BuiltinOp != Builtin::BI__builtin_bcmp &&
  9551. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  9552. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  9553. BuiltinOp == Builtin::BIwcsncmp ||
  9554. BuiltinOp == Builtin::BIwmemcmp ||
  9555. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  9556. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  9557. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  9558. for (; MaxLength; --MaxLength) {
  9559. APValue Char1, Char2;
  9560. if (!ReadCurElems(Char1, Char2))
  9561. return false;
  9562. if (Char1.getInt() != Char2.getInt()) {
  9563. if (IsWide) // wmemcmp compares with wchar_t signedness.
  9564. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  9565. // memcmp always compares unsigned chars.
  9566. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  9567. }
  9568. if (StopAtNull && !Char1.getInt())
  9569. return Success(0, E);
  9570. assert(!(StopAtNull && !Char2.getInt()));
  9571. if (!AdvanceElems())
  9572. return false;
  9573. }
  9574. // We hit the strncmp / memcmp limit.
  9575. return Success(0, E);
  9576. }
  9577. case Builtin::BI__atomic_always_lock_free:
  9578. case Builtin::BI__atomic_is_lock_free:
  9579. case Builtin::BI__c11_atomic_is_lock_free: {
  9580. APSInt SizeVal;
  9581. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  9582. return false;
  9583. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  9584. // of two less than the maximum inline atomic width, we know it is
  9585. // lock-free. If the size isn't a power of two, or greater than the
  9586. // maximum alignment where we promote atomics, we know it is not lock-free
  9587. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  9588. // the answer can only be determined at runtime; for example, 16-byte
  9589. // atomics have lock-free implementations on some, but not all,
  9590. // x86-64 processors.
  9591. // Check power-of-two.
  9592. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  9593. if (Size.isPowerOfTwo()) {
  9594. // Check against inlining width.
  9595. unsigned InlineWidthBits =
  9596. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  9597. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  9598. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  9599. Size == CharUnits::One() ||
  9600. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  9601. Expr::NPC_NeverValueDependent))
  9602. // OK, we will inline appropriately-aligned operations of this size,
  9603. // and _Atomic(T) is appropriately-aligned.
  9604. return Success(1, E);
  9605. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  9606. castAs<PointerType>()->getPointeeType();
  9607. if (!PointeeType->isIncompleteType() &&
  9608. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  9609. // OK, we will inline operations on this object.
  9610. return Success(1, E);
  9611. }
  9612. }
  9613. }
  9614. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  9615. Success(0, E) : Error(E);
  9616. }
  9617. case Builtin::BIomp_is_initial_device:
  9618. // We can decide statically which value the runtime would return if called.
  9619. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  9620. case Builtin::BI__builtin_add_overflow:
  9621. case Builtin::BI__builtin_sub_overflow:
  9622. case Builtin::BI__builtin_mul_overflow:
  9623. case Builtin::BI__builtin_sadd_overflow:
  9624. case Builtin::BI__builtin_uadd_overflow:
  9625. case Builtin::BI__builtin_uaddl_overflow:
  9626. case Builtin::BI__builtin_uaddll_overflow:
  9627. case Builtin::BI__builtin_usub_overflow:
  9628. case Builtin::BI__builtin_usubl_overflow:
  9629. case Builtin::BI__builtin_usubll_overflow:
  9630. case Builtin::BI__builtin_umul_overflow:
  9631. case Builtin::BI__builtin_umull_overflow:
  9632. case Builtin::BI__builtin_umulll_overflow:
  9633. case Builtin::BI__builtin_saddl_overflow:
  9634. case Builtin::BI__builtin_saddll_overflow:
  9635. case Builtin::BI__builtin_ssub_overflow:
  9636. case Builtin::BI__builtin_ssubl_overflow:
  9637. case Builtin::BI__builtin_ssubll_overflow:
  9638. case Builtin::BI__builtin_smul_overflow:
  9639. case Builtin::BI__builtin_smull_overflow:
  9640. case Builtin::BI__builtin_smulll_overflow: {
  9641. LValue ResultLValue;
  9642. APSInt LHS, RHS;
  9643. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  9644. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  9645. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  9646. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  9647. return false;
  9648. APSInt Result;
  9649. bool DidOverflow = false;
  9650. // If the types don't have to match, enlarge all 3 to the largest of them.
  9651. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9652. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9653. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9654. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  9655. ResultType->isSignedIntegerOrEnumerationType();
  9656. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  9657. ResultType->isSignedIntegerOrEnumerationType();
  9658. uint64_t LHSSize = LHS.getBitWidth();
  9659. uint64_t RHSSize = RHS.getBitWidth();
  9660. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  9661. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  9662. // Add an additional bit if the signedness isn't uniformly agreed to. We
  9663. // could do this ONLY if there is a signed and an unsigned that both have
  9664. // MaxBits, but the code to check that is pretty nasty. The issue will be
  9665. // caught in the shrink-to-result later anyway.
  9666. if (IsSigned && !AllSigned)
  9667. ++MaxBits;
  9668. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  9669. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  9670. Result = APSInt(MaxBits, !IsSigned);
  9671. }
  9672. // Find largest int.
  9673. switch (BuiltinOp) {
  9674. default:
  9675. llvm_unreachable("Invalid value for BuiltinOp");
  9676. case Builtin::BI__builtin_add_overflow:
  9677. case Builtin::BI__builtin_sadd_overflow:
  9678. case Builtin::BI__builtin_saddl_overflow:
  9679. case Builtin::BI__builtin_saddll_overflow:
  9680. case Builtin::BI__builtin_uadd_overflow:
  9681. case Builtin::BI__builtin_uaddl_overflow:
  9682. case Builtin::BI__builtin_uaddll_overflow:
  9683. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  9684. : LHS.uadd_ov(RHS, DidOverflow);
  9685. break;
  9686. case Builtin::BI__builtin_sub_overflow:
  9687. case Builtin::BI__builtin_ssub_overflow:
  9688. case Builtin::BI__builtin_ssubl_overflow:
  9689. case Builtin::BI__builtin_ssubll_overflow:
  9690. case Builtin::BI__builtin_usub_overflow:
  9691. case Builtin::BI__builtin_usubl_overflow:
  9692. case Builtin::BI__builtin_usubll_overflow:
  9693. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  9694. : LHS.usub_ov(RHS, DidOverflow);
  9695. break;
  9696. case Builtin::BI__builtin_mul_overflow:
  9697. case Builtin::BI__builtin_smul_overflow:
  9698. case Builtin::BI__builtin_smull_overflow:
  9699. case Builtin::BI__builtin_smulll_overflow:
  9700. case Builtin::BI__builtin_umul_overflow:
  9701. case Builtin::BI__builtin_umull_overflow:
  9702. case Builtin::BI__builtin_umulll_overflow:
  9703. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  9704. : LHS.umul_ov(RHS, DidOverflow);
  9705. break;
  9706. }
  9707. // In the case where multiple sizes are allowed, truncate and see if
  9708. // the values are the same.
  9709. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  9710. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  9711. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  9712. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  9713. // since it will give us the behavior of a TruncOrSelf in the case where
  9714. // its parameter <= its size. We previously set Result to be at least the
  9715. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  9716. // will work exactly like TruncOrSelf.
  9717. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  9718. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  9719. if (!APSInt::isSameValue(Temp, Result))
  9720. DidOverflow = true;
  9721. Result = Temp;
  9722. }
  9723. APValue APV{Result};
  9724. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  9725. return false;
  9726. return Success(DidOverflow, E);
  9727. }
  9728. }
  9729. }
  9730. /// Determine whether this is a pointer past the end of the complete
  9731. /// object referred to by the lvalue.
  9732. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  9733. const LValue &LV) {
  9734. // A null pointer can be viewed as being "past the end" but we don't
  9735. // choose to look at it that way here.
  9736. if (!LV.getLValueBase())
  9737. return false;
  9738. // If the designator is valid and refers to a subobject, we're not pointing
  9739. // past the end.
  9740. if (!LV.getLValueDesignator().Invalid &&
  9741. !LV.getLValueDesignator().isOnePastTheEnd())
  9742. return false;
  9743. // A pointer to an incomplete type might be past-the-end if the type's size is
  9744. // zero. We cannot tell because the type is incomplete.
  9745. QualType Ty = getType(LV.getLValueBase());
  9746. if (Ty->isIncompleteType())
  9747. return true;
  9748. // We're a past-the-end pointer if we point to the byte after the object,
  9749. // no matter what our type or path is.
  9750. auto Size = Ctx.getTypeSizeInChars(Ty);
  9751. return LV.getLValueOffset() == Size;
  9752. }
  9753. namespace {
  9754. /// Data recursive integer evaluator of certain binary operators.
  9755. ///
  9756. /// We use a data recursive algorithm for binary operators so that we are able
  9757. /// to handle extreme cases of chained binary operators without causing stack
  9758. /// overflow.
  9759. class DataRecursiveIntBinOpEvaluator {
  9760. struct EvalResult {
  9761. APValue Val;
  9762. bool Failed;
  9763. EvalResult() : Failed(false) { }
  9764. void swap(EvalResult &RHS) {
  9765. Val.swap(RHS.Val);
  9766. Failed = RHS.Failed;
  9767. RHS.Failed = false;
  9768. }
  9769. };
  9770. struct Job {
  9771. const Expr *E;
  9772. EvalResult LHSResult; // meaningful only for binary operator expression.
  9773. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  9774. Job() = default;
  9775. Job(Job &&) = default;
  9776. void startSpeculativeEval(EvalInfo &Info) {
  9777. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  9778. }
  9779. private:
  9780. SpeculativeEvaluationRAII SpecEvalRAII;
  9781. };
  9782. SmallVector<Job, 16> Queue;
  9783. IntExprEvaluator &IntEval;
  9784. EvalInfo &Info;
  9785. APValue &FinalResult;
  9786. public:
  9787. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  9788. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  9789. /// True if \param E is a binary operator that we are going to handle
  9790. /// data recursively.
  9791. /// We handle binary operators that are comma, logical, or that have operands
  9792. /// with integral or enumeration type.
  9793. static bool shouldEnqueue(const BinaryOperator *E) {
  9794. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  9795. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  9796. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9797. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9798. }
  9799. bool Traverse(const BinaryOperator *E) {
  9800. enqueue(E);
  9801. EvalResult PrevResult;
  9802. while (!Queue.empty())
  9803. process(PrevResult);
  9804. if (PrevResult.Failed) return false;
  9805. FinalResult.swap(PrevResult.Val);
  9806. return true;
  9807. }
  9808. private:
  9809. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9810. return IntEval.Success(Value, E, Result);
  9811. }
  9812. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  9813. return IntEval.Success(Value, E, Result);
  9814. }
  9815. bool Error(const Expr *E) {
  9816. return IntEval.Error(E);
  9817. }
  9818. bool Error(const Expr *E, diag::kind D) {
  9819. return IntEval.Error(E, D);
  9820. }
  9821. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  9822. return Info.CCEDiag(E, D);
  9823. }
  9824. // Returns true if visiting the RHS is necessary, false otherwise.
  9825. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9826. bool &SuppressRHSDiags);
  9827. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9828. const BinaryOperator *E, APValue &Result);
  9829. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  9830. Result.Failed = !Evaluate(Result.Val, Info, E);
  9831. if (Result.Failed)
  9832. Result.Val = APValue();
  9833. }
  9834. void process(EvalResult &Result);
  9835. void enqueue(const Expr *E) {
  9836. E = E->IgnoreParens();
  9837. Queue.resize(Queue.size()+1);
  9838. Queue.back().E = E;
  9839. Queue.back().Kind = Job::AnyExprKind;
  9840. }
  9841. };
  9842. }
  9843. bool DataRecursiveIntBinOpEvaluator::
  9844. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  9845. bool &SuppressRHSDiags) {
  9846. if (E->getOpcode() == BO_Comma) {
  9847. // Ignore LHS but note if we could not evaluate it.
  9848. if (LHSResult.Failed)
  9849. return Info.noteSideEffect();
  9850. return true;
  9851. }
  9852. if (E->isLogicalOp()) {
  9853. bool LHSAsBool;
  9854. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  9855. // We were able to evaluate the LHS, see if we can get away with not
  9856. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  9857. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  9858. Success(LHSAsBool, E, LHSResult.Val);
  9859. return false; // Ignore RHS
  9860. }
  9861. } else {
  9862. LHSResult.Failed = true;
  9863. // Since we weren't able to evaluate the left hand side, it
  9864. // might have had side effects.
  9865. if (!Info.noteSideEffect())
  9866. return false;
  9867. // We can't evaluate the LHS; however, sometimes the result
  9868. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9869. // Don't ignore RHS and suppress diagnostics from this arm.
  9870. SuppressRHSDiags = true;
  9871. }
  9872. return true;
  9873. }
  9874. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9875. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9876. if (LHSResult.Failed && !Info.noteFailure())
  9877. return false; // Ignore RHS;
  9878. return true;
  9879. }
  9880. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  9881. bool IsSub) {
  9882. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  9883. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  9884. // offsets.
  9885. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  9886. CharUnits &Offset = LVal.getLValueOffset();
  9887. uint64_t Offset64 = Offset.getQuantity();
  9888. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  9889. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  9890. : Offset64 + Index64);
  9891. }
  9892. bool DataRecursiveIntBinOpEvaluator::
  9893. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  9894. const BinaryOperator *E, APValue &Result) {
  9895. if (E->getOpcode() == BO_Comma) {
  9896. if (RHSResult.Failed)
  9897. return false;
  9898. Result = RHSResult.Val;
  9899. return true;
  9900. }
  9901. if (E->isLogicalOp()) {
  9902. bool lhsResult, rhsResult;
  9903. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  9904. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  9905. if (LHSIsOK) {
  9906. if (RHSIsOK) {
  9907. if (E->getOpcode() == BO_LOr)
  9908. return Success(lhsResult || rhsResult, E, Result);
  9909. else
  9910. return Success(lhsResult && rhsResult, E, Result);
  9911. }
  9912. } else {
  9913. if (RHSIsOK) {
  9914. // We can't evaluate the LHS; however, sometimes the result
  9915. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  9916. if (rhsResult == (E->getOpcode() == BO_LOr))
  9917. return Success(rhsResult, E, Result);
  9918. }
  9919. }
  9920. return false;
  9921. }
  9922. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  9923. E->getRHS()->getType()->isIntegralOrEnumerationType());
  9924. if (LHSResult.Failed || RHSResult.Failed)
  9925. return false;
  9926. const APValue &LHSVal = LHSResult.Val;
  9927. const APValue &RHSVal = RHSResult.Val;
  9928. // Handle cases like (unsigned long)&a + 4.
  9929. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  9930. Result = LHSVal;
  9931. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  9932. return true;
  9933. }
  9934. // Handle cases like 4 + (unsigned long)&a
  9935. if (E->getOpcode() == BO_Add &&
  9936. RHSVal.isLValue() && LHSVal.isInt()) {
  9937. Result = RHSVal;
  9938. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  9939. return true;
  9940. }
  9941. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  9942. // Handle (intptr_t)&&A - (intptr_t)&&B.
  9943. if (!LHSVal.getLValueOffset().isZero() ||
  9944. !RHSVal.getLValueOffset().isZero())
  9945. return false;
  9946. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  9947. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  9948. if (!LHSExpr || !RHSExpr)
  9949. return false;
  9950. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9951. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9952. if (!LHSAddrExpr || !RHSAddrExpr)
  9953. return false;
  9954. // Make sure both labels come from the same function.
  9955. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9956. RHSAddrExpr->getLabel()->getDeclContext())
  9957. return false;
  9958. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  9959. return true;
  9960. }
  9961. // All the remaining cases expect both operands to be an integer
  9962. if (!LHSVal.isInt() || !RHSVal.isInt())
  9963. return Error(E);
  9964. // Set up the width and signedness manually, in case it can't be deduced
  9965. // from the operation we're performing.
  9966. // FIXME: Don't do this in the cases where we can deduce it.
  9967. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  9968. E->getType()->isUnsignedIntegerOrEnumerationType());
  9969. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  9970. RHSVal.getInt(), Value))
  9971. return false;
  9972. return Success(Value, E, Result);
  9973. }
  9974. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  9975. Job &job = Queue.back();
  9976. switch (job.Kind) {
  9977. case Job::AnyExprKind: {
  9978. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  9979. if (shouldEnqueue(Bop)) {
  9980. job.Kind = Job::BinOpKind;
  9981. enqueue(Bop->getLHS());
  9982. return;
  9983. }
  9984. }
  9985. EvaluateExpr(job.E, Result);
  9986. Queue.pop_back();
  9987. return;
  9988. }
  9989. case Job::BinOpKind: {
  9990. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  9991. bool SuppressRHSDiags = false;
  9992. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  9993. Queue.pop_back();
  9994. return;
  9995. }
  9996. if (SuppressRHSDiags)
  9997. job.startSpeculativeEval(Info);
  9998. job.LHSResult.swap(Result);
  9999. job.Kind = Job::BinOpVisitedLHSKind;
  10000. enqueue(Bop->getRHS());
  10001. return;
  10002. }
  10003. case Job::BinOpVisitedLHSKind: {
  10004. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  10005. EvalResult RHS;
  10006. RHS.swap(Result);
  10007. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  10008. Queue.pop_back();
  10009. return;
  10010. }
  10011. }
  10012. llvm_unreachable("Invalid Job::Kind!");
  10013. }
  10014. namespace {
  10015. /// Used when we determine that we should fail, but can keep evaluating prior to
  10016. /// noting that we had a failure.
  10017. class DelayedNoteFailureRAII {
  10018. EvalInfo &Info;
  10019. bool NoteFailure;
  10020. public:
  10021. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  10022. : Info(Info), NoteFailure(NoteFailure) {}
  10023. ~DelayedNoteFailureRAII() {
  10024. if (NoteFailure) {
  10025. bool ContinueAfterFailure = Info.noteFailure();
  10026. (void)ContinueAfterFailure;
  10027. assert(ContinueAfterFailure &&
  10028. "Shouldn't have kept evaluating on failure.");
  10029. }
  10030. }
  10031. };
  10032. }
  10033. template <class SuccessCB, class AfterCB>
  10034. static bool
  10035. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  10036. SuccessCB &&Success, AfterCB &&DoAfter) {
  10037. assert(E->isComparisonOp() && "expected comparison operator");
  10038. assert((E->getOpcode() == BO_Cmp ||
  10039. E->getType()->isIntegralOrEnumerationType()) &&
  10040. "unsupported binary expression evaluation");
  10041. auto Error = [&](const Expr *E) {
  10042. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10043. return false;
  10044. };
  10045. using CCR = ComparisonCategoryResult;
  10046. bool IsRelational = E->isRelationalOp();
  10047. bool IsEquality = E->isEqualityOp();
  10048. if (E->getOpcode() == BO_Cmp) {
  10049. const ComparisonCategoryInfo &CmpInfo =
  10050. Info.Ctx.CompCategories.getInfoForType(E->getType());
  10051. IsRelational = CmpInfo.isOrdered();
  10052. IsEquality = CmpInfo.isEquality();
  10053. }
  10054. QualType LHSTy = E->getLHS()->getType();
  10055. QualType RHSTy = E->getRHS()->getType();
  10056. if (LHSTy->isIntegralOrEnumerationType() &&
  10057. RHSTy->isIntegralOrEnumerationType()) {
  10058. APSInt LHS, RHS;
  10059. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  10060. if (!LHSOK && !Info.noteFailure())
  10061. return false;
  10062. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  10063. return false;
  10064. if (LHS < RHS)
  10065. return Success(CCR::Less, E);
  10066. if (LHS > RHS)
  10067. return Success(CCR::Greater, E);
  10068. return Success(CCR::Equal, E);
  10069. }
  10070. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  10071. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  10072. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  10073. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  10074. if (!LHSOK && !Info.noteFailure())
  10075. return false;
  10076. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  10077. return false;
  10078. if (LHSFX < RHSFX)
  10079. return Success(CCR::Less, E);
  10080. if (LHSFX > RHSFX)
  10081. return Success(CCR::Greater, E);
  10082. return Success(CCR::Equal, E);
  10083. }
  10084. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  10085. ComplexValue LHS, RHS;
  10086. bool LHSOK;
  10087. if (E->isAssignmentOp()) {
  10088. LValue LV;
  10089. EvaluateLValue(E->getLHS(), LV, Info);
  10090. LHSOK = false;
  10091. } else if (LHSTy->isRealFloatingType()) {
  10092. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  10093. if (LHSOK) {
  10094. LHS.makeComplexFloat();
  10095. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  10096. }
  10097. } else {
  10098. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  10099. }
  10100. if (!LHSOK && !Info.noteFailure())
  10101. return false;
  10102. if (E->getRHS()->getType()->isRealFloatingType()) {
  10103. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  10104. return false;
  10105. RHS.makeComplexFloat();
  10106. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  10107. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  10108. return false;
  10109. if (LHS.isComplexFloat()) {
  10110. APFloat::cmpResult CR_r =
  10111. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  10112. APFloat::cmpResult CR_i =
  10113. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  10114. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  10115. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  10116. } else {
  10117. assert(IsEquality && "invalid complex comparison");
  10118. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  10119. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  10120. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  10121. }
  10122. }
  10123. if (LHSTy->isRealFloatingType() &&
  10124. RHSTy->isRealFloatingType()) {
  10125. APFloat RHS(0.0), LHS(0.0);
  10126. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  10127. if (!LHSOK && !Info.noteFailure())
  10128. return false;
  10129. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  10130. return false;
  10131. assert(E->isComparisonOp() && "Invalid binary operator!");
  10132. auto GetCmpRes = [&]() {
  10133. switch (LHS.compare(RHS)) {
  10134. case APFloat::cmpEqual:
  10135. return CCR::Equal;
  10136. case APFloat::cmpLessThan:
  10137. return CCR::Less;
  10138. case APFloat::cmpGreaterThan:
  10139. return CCR::Greater;
  10140. case APFloat::cmpUnordered:
  10141. return CCR::Unordered;
  10142. }
  10143. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  10144. };
  10145. return Success(GetCmpRes(), E);
  10146. }
  10147. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  10148. LValue LHSValue, RHSValue;
  10149. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  10150. if (!LHSOK && !Info.noteFailure())
  10151. return false;
  10152. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10153. return false;
  10154. // Reject differing bases from the normal codepath; we special-case
  10155. // comparisons to null.
  10156. if (!HasSameBase(LHSValue, RHSValue)) {
  10157. // Inequalities and subtractions between unrelated pointers have
  10158. // unspecified or undefined behavior.
  10159. if (!IsEquality)
  10160. return Error(E);
  10161. // A constant address may compare equal to the address of a symbol.
  10162. // The one exception is that address of an object cannot compare equal
  10163. // to a null pointer constant.
  10164. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  10165. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  10166. return Error(E);
  10167. // It's implementation-defined whether distinct literals will have
  10168. // distinct addresses. In clang, the result of such a comparison is
  10169. // unspecified, so it is not a constant expression. However, we do know
  10170. // that the address of a literal will be non-null.
  10171. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  10172. LHSValue.Base && RHSValue.Base)
  10173. return Error(E);
  10174. // We can't tell whether weak symbols will end up pointing to the same
  10175. // object.
  10176. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  10177. return Error(E);
  10178. // We can't compare the address of the start of one object with the
  10179. // past-the-end address of another object, per C++ DR1652.
  10180. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  10181. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  10182. (RHSValue.Base && RHSValue.Offset.isZero() &&
  10183. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  10184. return Error(E);
  10185. // We can't tell whether an object is at the same address as another
  10186. // zero sized object.
  10187. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  10188. (LHSValue.Base && isZeroSized(RHSValue)))
  10189. return Error(E);
  10190. return Success(CCR::Nonequal, E);
  10191. }
  10192. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  10193. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  10194. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  10195. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  10196. // C++11 [expr.rel]p3:
  10197. // Pointers to void (after pointer conversions) can be compared, with a
  10198. // result defined as follows: If both pointers represent the same
  10199. // address or are both the null pointer value, the result is true if the
  10200. // operator is <= or >= and false otherwise; otherwise the result is
  10201. // unspecified.
  10202. // We interpret this as applying to pointers to *cv* void.
  10203. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  10204. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  10205. // C++11 [expr.rel]p2:
  10206. // - If two pointers point to non-static data members of the same object,
  10207. // or to subobjects or array elements fo such members, recursively, the
  10208. // pointer to the later declared member compares greater provided the
  10209. // two members have the same access control and provided their class is
  10210. // not a union.
  10211. // [...]
  10212. // - Otherwise pointer comparisons are unspecified.
  10213. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  10214. bool WasArrayIndex;
  10215. unsigned Mismatch = FindDesignatorMismatch(
  10216. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  10217. // At the point where the designators diverge, the comparison has a
  10218. // specified value if:
  10219. // - we are comparing array indices
  10220. // - we are comparing fields of a union, or fields with the same access
  10221. // Otherwise, the result is unspecified and thus the comparison is not a
  10222. // constant expression.
  10223. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  10224. Mismatch < RHSDesignator.Entries.size()) {
  10225. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  10226. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  10227. if (!LF && !RF)
  10228. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  10229. else if (!LF)
  10230. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  10231. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  10232. << RF->getParent() << RF;
  10233. else if (!RF)
  10234. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  10235. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  10236. << LF->getParent() << LF;
  10237. else if (!LF->getParent()->isUnion() &&
  10238. LF->getAccess() != RF->getAccess())
  10239. Info.CCEDiag(E,
  10240. diag::note_constexpr_pointer_comparison_differing_access)
  10241. << LF << LF->getAccess() << RF << RF->getAccess()
  10242. << LF->getParent();
  10243. }
  10244. }
  10245. // The comparison here must be unsigned, and performed with the same
  10246. // width as the pointer.
  10247. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  10248. uint64_t CompareLHS = LHSOffset.getQuantity();
  10249. uint64_t CompareRHS = RHSOffset.getQuantity();
  10250. assert(PtrSize <= 64 && "Unexpected pointer width");
  10251. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  10252. CompareLHS &= Mask;
  10253. CompareRHS &= Mask;
  10254. // If there is a base and this is a relational operator, we can only
  10255. // compare pointers within the object in question; otherwise, the result
  10256. // depends on where the object is located in memory.
  10257. if (!LHSValue.Base.isNull() && IsRelational) {
  10258. QualType BaseTy = getType(LHSValue.Base);
  10259. if (BaseTy->isIncompleteType())
  10260. return Error(E);
  10261. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  10262. uint64_t OffsetLimit = Size.getQuantity();
  10263. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  10264. return Error(E);
  10265. }
  10266. if (CompareLHS < CompareRHS)
  10267. return Success(CCR::Less, E);
  10268. if (CompareLHS > CompareRHS)
  10269. return Success(CCR::Greater, E);
  10270. return Success(CCR::Equal, E);
  10271. }
  10272. if (LHSTy->isMemberPointerType()) {
  10273. assert(IsEquality && "unexpected member pointer operation");
  10274. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  10275. MemberPtr LHSValue, RHSValue;
  10276. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  10277. if (!LHSOK && !Info.noteFailure())
  10278. return false;
  10279. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10280. return false;
  10281. // C++11 [expr.eq]p2:
  10282. // If both operands are null, they compare equal. Otherwise if only one is
  10283. // null, they compare unequal.
  10284. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  10285. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  10286. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  10287. }
  10288. // Otherwise if either is a pointer to a virtual member function, the
  10289. // result is unspecified.
  10290. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  10291. if (MD->isVirtual())
  10292. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  10293. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  10294. if (MD->isVirtual())
  10295. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  10296. // Otherwise they compare equal if and only if they would refer to the
  10297. // same member of the same most derived object or the same subobject if
  10298. // they were dereferenced with a hypothetical object of the associated
  10299. // class type.
  10300. bool Equal = LHSValue == RHSValue;
  10301. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  10302. }
  10303. if (LHSTy->isNullPtrType()) {
  10304. assert(E->isComparisonOp() && "unexpected nullptr operation");
  10305. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  10306. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  10307. // are compared, the result is true of the operator is <=, >= or ==, and
  10308. // false otherwise.
  10309. return Success(CCR::Equal, E);
  10310. }
  10311. return DoAfter();
  10312. }
  10313. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  10314. if (!CheckLiteralType(Info, E))
  10315. return false;
  10316. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10317. const BinaryOperator *E) {
  10318. // Evaluation succeeded. Lookup the information for the comparison category
  10319. // type and fetch the VarDecl for the result.
  10320. const ComparisonCategoryInfo &CmpInfo =
  10321. Info.Ctx.CompCategories.getInfoForType(E->getType());
  10322. const VarDecl *VD =
  10323. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  10324. // Check and evaluate the result as a constant expression.
  10325. LValue LV;
  10326. LV.set(VD);
  10327. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10328. return false;
  10329. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10330. };
  10331. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10332. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  10333. });
  10334. }
  10335. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10336. // We don't call noteFailure immediately because the assignment happens after
  10337. // we evaluate LHS and RHS.
  10338. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  10339. return Error(E);
  10340. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  10341. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  10342. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  10343. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  10344. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  10345. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  10346. if (E->isComparisonOp()) {
  10347. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  10348. // comparisons and then translating the result.
  10349. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  10350. const BinaryOperator *E) {
  10351. using CCR = ComparisonCategoryResult;
  10352. bool IsEqual = ResKind == CCR::Equal,
  10353. IsLess = ResKind == CCR::Less,
  10354. IsGreater = ResKind == CCR::Greater;
  10355. auto Op = E->getOpcode();
  10356. switch (Op) {
  10357. default:
  10358. llvm_unreachable("unsupported binary operator");
  10359. case BO_EQ:
  10360. case BO_NE:
  10361. return Success(IsEqual == (Op == BO_EQ), E);
  10362. case BO_LT: return Success(IsLess, E);
  10363. case BO_GT: return Success(IsGreater, E);
  10364. case BO_LE: return Success(IsEqual || IsLess, E);
  10365. case BO_GE: return Success(IsEqual || IsGreater, E);
  10366. }
  10367. };
  10368. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  10369. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10370. });
  10371. }
  10372. QualType LHSTy = E->getLHS()->getType();
  10373. QualType RHSTy = E->getRHS()->getType();
  10374. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  10375. E->getOpcode() == BO_Sub) {
  10376. LValue LHSValue, RHSValue;
  10377. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  10378. if (!LHSOK && !Info.noteFailure())
  10379. return false;
  10380. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  10381. return false;
  10382. // Reject differing bases from the normal codepath; we special-case
  10383. // comparisons to null.
  10384. if (!HasSameBase(LHSValue, RHSValue)) {
  10385. // Handle &&A - &&B.
  10386. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  10387. return Error(E);
  10388. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  10389. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  10390. if (!LHSExpr || !RHSExpr)
  10391. return Error(E);
  10392. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  10393. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  10394. if (!LHSAddrExpr || !RHSAddrExpr)
  10395. return Error(E);
  10396. // Make sure both labels come from the same function.
  10397. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  10398. RHSAddrExpr->getLabel()->getDeclContext())
  10399. return Error(E);
  10400. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  10401. }
  10402. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  10403. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  10404. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  10405. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  10406. // C++11 [expr.add]p6:
  10407. // Unless both pointers point to elements of the same array object, or
  10408. // one past the last element of the array object, the behavior is
  10409. // undefined.
  10410. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  10411. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  10412. RHSDesignator))
  10413. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  10414. QualType Type = E->getLHS()->getType();
  10415. QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
  10416. CharUnits ElementSize;
  10417. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  10418. return false;
  10419. // As an extension, a type may have zero size (empty struct or union in
  10420. // C, array of zero length). Pointer subtraction in such cases has
  10421. // undefined behavior, so is not constant.
  10422. if (ElementSize.isZero()) {
  10423. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  10424. << ElementType;
  10425. return false;
  10426. }
  10427. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  10428. // and produce incorrect results when it overflows. Such behavior
  10429. // appears to be non-conforming, but is common, so perhaps we should
  10430. // assume the standard intended for such cases to be undefined behavior
  10431. // and check for them.
  10432. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  10433. // overflow in the final conversion to ptrdiff_t.
  10434. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  10435. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  10436. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  10437. false);
  10438. APSInt TrueResult = (LHS - RHS) / ElemSize;
  10439. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  10440. if (Result.extend(65) != TrueResult &&
  10441. !HandleOverflow(Info, E, TrueResult, E->getType()))
  10442. return false;
  10443. return Success(Result, E);
  10444. }
  10445. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  10446. }
  10447. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  10448. /// a result as the expression's type.
  10449. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  10450. const UnaryExprOrTypeTraitExpr *E) {
  10451. switch(E->getKind()) {
  10452. case UETT_PreferredAlignOf:
  10453. case UETT_AlignOf: {
  10454. if (E->isArgumentType())
  10455. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  10456. E);
  10457. else
  10458. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  10459. E);
  10460. }
  10461. case UETT_VecStep: {
  10462. QualType Ty = E->getTypeOfArgument();
  10463. if (Ty->isVectorType()) {
  10464. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  10465. // The vec_step built-in functions that take a 3-component
  10466. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  10467. if (n == 3)
  10468. n = 4;
  10469. return Success(n, E);
  10470. } else
  10471. return Success(1, E);
  10472. }
  10473. case UETT_SizeOf: {
  10474. QualType SrcTy = E->getTypeOfArgument();
  10475. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  10476. // the result is the size of the referenced type."
  10477. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  10478. SrcTy = Ref->getPointeeType();
  10479. CharUnits Sizeof;
  10480. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  10481. return false;
  10482. return Success(Sizeof, E);
  10483. }
  10484. case UETT_OpenMPRequiredSimdAlign:
  10485. assert(E->isArgumentType());
  10486. return Success(
  10487. Info.Ctx.toCharUnitsFromBits(
  10488. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  10489. .getQuantity(),
  10490. E);
  10491. }
  10492. llvm_unreachable("unknown expr/type trait");
  10493. }
  10494. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  10495. CharUnits Result;
  10496. unsigned n = OOE->getNumComponents();
  10497. if (n == 0)
  10498. return Error(OOE);
  10499. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  10500. for (unsigned i = 0; i != n; ++i) {
  10501. OffsetOfNode ON = OOE->getComponent(i);
  10502. switch (ON.getKind()) {
  10503. case OffsetOfNode::Array: {
  10504. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  10505. APSInt IdxResult;
  10506. if (!EvaluateInteger(Idx, IdxResult, Info))
  10507. return false;
  10508. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  10509. if (!AT)
  10510. return Error(OOE);
  10511. CurrentType = AT->getElementType();
  10512. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  10513. Result += IdxResult.getSExtValue() * ElementSize;
  10514. break;
  10515. }
  10516. case OffsetOfNode::Field: {
  10517. FieldDecl *MemberDecl = ON.getField();
  10518. const RecordType *RT = CurrentType->getAs<RecordType>();
  10519. if (!RT)
  10520. return Error(OOE);
  10521. RecordDecl *RD = RT->getDecl();
  10522. if (RD->isInvalidDecl()) return false;
  10523. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10524. unsigned i = MemberDecl->getFieldIndex();
  10525. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  10526. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  10527. CurrentType = MemberDecl->getType().getNonReferenceType();
  10528. break;
  10529. }
  10530. case OffsetOfNode::Identifier:
  10531. llvm_unreachable("dependent __builtin_offsetof");
  10532. case OffsetOfNode::Base: {
  10533. CXXBaseSpecifier *BaseSpec = ON.getBase();
  10534. if (BaseSpec->isVirtual())
  10535. return Error(OOE);
  10536. // Find the layout of the class whose base we are looking into.
  10537. const RecordType *RT = CurrentType->getAs<RecordType>();
  10538. if (!RT)
  10539. return Error(OOE);
  10540. RecordDecl *RD = RT->getDecl();
  10541. if (RD->isInvalidDecl()) return false;
  10542. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  10543. // Find the base class itself.
  10544. CurrentType = BaseSpec->getType();
  10545. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  10546. if (!BaseRT)
  10547. return Error(OOE);
  10548. // Add the offset to the base.
  10549. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  10550. break;
  10551. }
  10552. }
  10553. }
  10554. return Success(Result, OOE);
  10555. }
  10556. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10557. switch (E->getOpcode()) {
  10558. default:
  10559. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  10560. // See C99 6.6p3.
  10561. return Error(E);
  10562. case UO_Extension:
  10563. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  10564. // If so, we could clear the diagnostic ID.
  10565. return Visit(E->getSubExpr());
  10566. case UO_Plus:
  10567. // The result is just the value.
  10568. return Visit(E->getSubExpr());
  10569. case UO_Minus: {
  10570. if (!Visit(E->getSubExpr()))
  10571. return false;
  10572. if (!Result.isInt()) return Error(E);
  10573. const APSInt &Value = Result.getInt();
  10574. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  10575. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  10576. E->getType()))
  10577. return false;
  10578. return Success(-Value, E);
  10579. }
  10580. case UO_Not: {
  10581. if (!Visit(E->getSubExpr()))
  10582. return false;
  10583. if (!Result.isInt()) return Error(E);
  10584. return Success(~Result.getInt(), E);
  10585. }
  10586. case UO_LNot: {
  10587. bool bres;
  10588. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10589. return false;
  10590. return Success(!bres, E);
  10591. }
  10592. }
  10593. }
  10594. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  10595. /// result type is integer.
  10596. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10597. const Expr *SubExpr = E->getSubExpr();
  10598. QualType DestType = E->getType();
  10599. QualType SrcType = SubExpr->getType();
  10600. switch (E->getCastKind()) {
  10601. case CK_BaseToDerived:
  10602. case CK_DerivedToBase:
  10603. case CK_UncheckedDerivedToBase:
  10604. case CK_Dynamic:
  10605. case CK_ToUnion:
  10606. case CK_ArrayToPointerDecay:
  10607. case CK_FunctionToPointerDecay:
  10608. case CK_NullToPointer:
  10609. case CK_NullToMemberPointer:
  10610. case CK_BaseToDerivedMemberPointer:
  10611. case CK_DerivedToBaseMemberPointer:
  10612. case CK_ReinterpretMemberPointer:
  10613. case CK_ConstructorConversion:
  10614. case CK_IntegralToPointer:
  10615. case CK_ToVoid:
  10616. case CK_VectorSplat:
  10617. case CK_IntegralToFloating:
  10618. case CK_FloatingCast:
  10619. case CK_CPointerToObjCPointerCast:
  10620. case CK_BlockPointerToObjCPointerCast:
  10621. case CK_AnyPointerToBlockPointerCast:
  10622. case CK_ObjCObjectLValueCast:
  10623. case CK_FloatingRealToComplex:
  10624. case CK_FloatingComplexToReal:
  10625. case CK_FloatingComplexCast:
  10626. case CK_FloatingComplexToIntegralComplex:
  10627. case CK_IntegralRealToComplex:
  10628. case CK_IntegralComplexCast:
  10629. case CK_IntegralComplexToFloatingComplex:
  10630. case CK_BuiltinFnToFnPtr:
  10631. case CK_ZeroToOCLOpaqueType:
  10632. case CK_NonAtomicToAtomic:
  10633. case CK_AddressSpaceConversion:
  10634. case CK_IntToOCLSampler:
  10635. case CK_FixedPointCast:
  10636. case CK_IntegralToFixedPoint:
  10637. llvm_unreachable("invalid cast kind for integral value");
  10638. case CK_BitCast:
  10639. case CK_Dependent:
  10640. case CK_LValueBitCast:
  10641. case CK_ARCProduceObject:
  10642. case CK_ARCConsumeObject:
  10643. case CK_ARCReclaimReturnedObject:
  10644. case CK_ARCExtendBlockObject:
  10645. case CK_CopyAndAutoreleaseBlockObject:
  10646. return Error(E);
  10647. case CK_UserDefinedConversion:
  10648. case CK_LValueToRValue:
  10649. case CK_AtomicToNonAtomic:
  10650. case CK_NoOp:
  10651. case CK_LValueToRValueBitCast:
  10652. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10653. case CK_MemberPointerToBoolean:
  10654. case CK_PointerToBoolean:
  10655. case CK_IntegralToBoolean:
  10656. case CK_FloatingToBoolean:
  10657. case CK_BooleanToSignedIntegral:
  10658. case CK_FloatingComplexToBoolean:
  10659. case CK_IntegralComplexToBoolean: {
  10660. bool BoolResult;
  10661. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  10662. return false;
  10663. uint64_t IntResult = BoolResult;
  10664. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  10665. IntResult = (uint64_t)-1;
  10666. return Success(IntResult, E);
  10667. }
  10668. case CK_FixedPointToIntegral: {
  10669. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  10670. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10671. return false;
  10672. bool Overflowed;
  10673. llvm::APSInt Result = Src.convertToInt(
  10674. Info.Ctx.getIntWidth(DestType),
  10675. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  10676. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10677. return false;
  10678. return Success(Result, E);
  10679. }
  10680. case CK_FixedPointToBoolean: {
  10681. // Unsigned padding does not affect this.
  10682. APValue Val;
  10683. if (!Evaluate(Val, Info, SubExpr))
  10684. return false;
  10685. return Success(Val.getFixedPoint().getBoolValue(), E);
  10686. }
  10687. case CK_IntegralCast: {
  10688. if (!Visit(SubExpr))
  10689. return false;
  10690. if (!Result.isInt()) {
  10691. // Allow casts of address-of-label differences if they are no-ops
  10692. // or narrowing. (The narrowing case isn't actually guaranteed to
  10693. // be constant-evaluatable except in some narrow cases which are hard
  10694. // to detect here. We let it through on the assumption the user knows
  10695. // what they are doing.)
  10696. if (Result.isAddrLabelDiff())
  10697. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  10698. // Only allow casts of lvalues if they are lossless.
  10699. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  10700. }
  10701. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  10702. Result.getInt()), E);
  10703. }
  10704. case CK_PointerToIntegral: {
  10705. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  10706. LValue LV;
  10707. if (!EvaluatePointer(SubExpr, LV, Info))
  10708. return false;
  10709. if (LV.getLValueBase()) {
  10710. // Only allow based lvalue casts if they are lossless.
  10711. // FIXME: Allow a larger integer size than the pointer size, and allow
  10712. // narrowing back down to pointer width in subsequent integral casts.
  10713. // FIXME: Check integer type's active bits, not its type size.
  10714. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  10715. return Error(E);
  10716. LV.Designator.setInvalid();
  10717. LV.moveInto(Result);
  10718. return true;
  10719. }
  10720. APSInt AsInt;
  10721. APValue V;
  10722. LV.moveInto(V);
  10723. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  10724. llvm_unreachable("Can't cast this!");
  10725. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  10726. }
  10727. case CK_IntegralComplexToReal: {
  10728. ComplexValue C;
  10729. if (!EvaluateComplex(SubExpr, C, Info))
  10730. return false;
  10731. return Success(C.getComplexIntReal(), E);
  10732. }
  10733. case CK_FloatingToIntegral: {
  10734. APFloat F(0.0);
  10735. if (!EvaluateFloat(SubExpr, F, Info))
  10736. return false;
  10737. APSInt Value;
  10738. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  10739. return false;
  10740. return Success(Value, E);
  10741. }
  10742. }
  10743. llvm_unreachable("unknown cast resulting in integral value");
  10744. }
  10745. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10746. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10747. ComplexValue LV;
  10748. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10749. return false;
  10750. if (!LV.isComplexInt())
  10751. return Error(E);
  10752. return Success(LV.getComplexIntReal(), E);
  10753. }
  10754. return Visit(E->getSubExpr());
  10755. }
  10756. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  10757. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  10758. ComplexValue LV;
  10759. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  10760. return false;
  10761. if (!LV.isComplexInt())
  10762. return Error(E);
  10763. return Success(LV.getComplexIntImag(), E);
  10764. }
  10765. VisitIgnoredValue(E->getSubExpr());
  10766. return Success(0, E);
  10767. }
  10768. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  10769. return Success(E->getPackLength(), E);
  10770. }
  10771. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  10772. return Success(E->getValue(), E);
  10773. }
  10774. bool IntExprEvaluator::VisitConceptSpecializationExpr(
  10775. const ConceptSpecializationExpr *E) {
  10776. return Success(E->isSatisfied(), E);
  10777. }
  10778. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10779. switch (E->getOpcode()) {
  10780. default:
  10781. // Invalid unary operators
  10782. return Error(E);
  10783. case UO_Plus:
  10784. // The result is just the value.
  10785. return Visit(E->getSubExpr());
  10786. case UO_Minus: {
  10787. if (!Visit(E->getSubExpr())) return false;
  10788. if (!Result.isFixedPoint())
  10789. return Error(E);
  10790. bool Overflowed;
  10791. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  10792. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  10793. return false;
  10794. return Success(Negated, E);
  10795. }
  10796. case UO_LNot: {
  10797. bool bres;
  10798. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  10799. return false;
  10800. return Success(!bres, E);
  10801. }
  10802. }
  10803. }
  10804. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  10805. const Expr *SubExpr = E->getSubExpr();
  10806. QualType DestType = E->getType();
  10807. assert(DestType->isFixedPointType() &&
  10808. "Expected destination type to be a fixed point type");
  10809. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  10810. switch (E->getCastKind()) {
  10811. case CK_FixedPointCast: {
  10812. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  10813. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  10814. return false;
  10815. bool Overflowed;
  10816. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  10817. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  10818. return false;
  10819. return Success(Result, E);
  10820. }
  10821. case CK_IntegralToFixedPoint: {
  10822. APSInt Src;
  10823. if (!EvaluateInteger(SubExpr, Src, Info))
  10824. return false;
  10825. bool Overflowed;
  10826. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  10827. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  10828. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  10829. return false;
  10830. return Success(IntResult, E);
  10831. }
  10832. case CK_NoOp:
  10833. case CK_LValueToRValue:
  10834. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10835. default:
  10836. return Error(E);
  10837. }
  10838. }
  10839. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  10840. const Expr *LHS = E->getLHS();
  10841. const Expr *RHS = E->getRHS();
  10842. FixedPointSemantics ResultFXSema =
  10843. Info.Ctx.getFixedPointSemantics(E->getType());
  10844. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  10845. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  10846. return false;
  10847. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  10848. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  10849. return false;
  10850. switch (E->getOpcode()) {
  10851. case BO_Add: {
  10852. bool AddOverflow, ConversionOverflow;
  10853. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  10854. .convert(ResultFXSema, &ConversionOverflow);
  10855. if ((AddOverflow || ConversionOverflow) &&
  10856. !HandleOverflow(Info, E, Result, E->getType()))
  10857. return false;
  10858. return Success(Result, E);
  10859. }
  10860. default:
  10861. return false;
  10862. }
  10863. llvm_unreachable("Should've exited before this");
  10864. }
  10865. //===----------------------------------------------------------------------===//
  10866. // Float Evaluation
  10867. //===----------------------------------------------------------------------===//
  10868. namespace {
  10869. class FloatExprEvaluator
  10870. : public ExprEvaluatorBase<FloatExprEvaluator> {
  10871. APFloat &Result;
  10872. public:
  10873. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  10874. : ExprEvaluatorBaseTy(info), Result(result) {}
  10875. bool Success(const APValue &V, const Expr *e) {
  10876. Result = V.getFloat();
  10877. return true;
  10878. }
  10879. bool ZeroInitialization(const Expr *E) {
  10880. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  10881. return true;
  10882. }
  10883. bool VisitCallExpr(const CallExpr *E);
  10884. bool VisitUnaryOperator(const UnaryOperator *E);
  10885. bool VisitBinaryOperator(const BinaryOperator *E);
  10886. bool VisitFloatingLiteral(const FloatingLiteral *E);
  10887. bool VisitCastExpr(const CastExpr *E);
  10888. bool VisitUnaryReal(const UnaryOperator *E);
  10889. bool VisitUnaryImag(const UnaryOperator *E);
  10890. // FIXME: Missing: array subscript of vector, member of vector
  10891. };
  10892. } // end anonymous namespace
  10893. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  10894. assert(E->isRValue() && E->getType()->isRealFloatingType());
  10895. return FloatExprEvaluator(Info, Result).Visit(E);
  10896. }
  10897. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  10898. QualType ResultTy,
  10899. const Expr *Arg,
  10900. bool SNaN,
  10901. llvm::APFloat &Result) {
  10902. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  10903. if (!S) return false;
  10904. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  10905. llvm::APInt fill;
  10906. // Treat empty strings as if they were zero.
  10907. if (S->getString().empty())
  10908. fill = llvm::APInt(32, 0);
  10909. else if (S->getString().getAsInteger(0, fill))
  10910. return false;
  10911. if (Context.getTargetInfo().isNan2008()) {
  10912. if (SNaN)
  10913. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10914. else
  10915. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10916. } else {
  10917. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  10918. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  10919. // a different encoding to what became a standard in 2008, and for pre-
  10920. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  10921. // sNaN. This is now known as "legacy NaN" encoding.
  10922. if (SNaN)
  10923. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  10924. else
  10925. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  10926. }
  10927. return true;
  10928. }
  10929. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10930. switch (E->getBuiltinCallee()) {
  10931. default:
  10932. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10933. case Builtin::BI__builtin_huge_val:
  10934. case Builtin::BI__builtin_huge_valf:
  10935. case Builtin::BI__builtin_huge_vall:
  10936. case Builtin::BI__builtin_huge_valf128:
  10937. case Builtin::BI__builtin_inf:
  10938. case Builtin::BI__builtin_inff:
  10939. case Builtin::BI__builtin_infl:
  10940. case Builtin::BI__builtin_inff128: {
  10941. const llvm::fltSemantics &Sem =
  10942. Info.Ctx.getFloatTypeSemantics(E->getType());
  10943. Result = llvm::APFloat::getInf(Sem);
  10944. return true;
  10945. }
  10946. case Builtin::BI__builtin_nans:
  10947. case Builtin::BI__builtin_nansf:
  10948. case Builtin::BI__builtin_nansl:
  10949. case Builtin::BI__builtin_nansf128:
  10950. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10951. true, Result))
  10952. return Error(E);
  10953. return true;
  10954. case Builtin::BI__builtin_nan:
  10955. case Builtin::BI__builtin_nanf:
  10956. case Builtin::BI__builtin_nanl:
  10957. case Builtin::BI__builtin_nanf128:
  10958. // If this is __builtin_nan() turn this into a nan, otherwise we
  10959. // can't constant fold it.
  10960. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  10961. false, Result))
  10962. return Error(E);
  10963. return true;
  10964. case Builtin::BI__builtin_fabs:
  10965. case Builtin::BI__builtin_fabsf:
  10966. case Builtin::BI__builtin_fabsl:
  10967. case Builtin::BI__builtin_fabsf128:
  10968. if (!EvaluateFloat(E->getArg(0), Result, Info))
  10969. return false;
  10970. if (Result.isNegative())
  10971. Result.changeSign();
  10972. return true;
  10973. // FIXME: Builtin::BI__builtin_powi
  10974. // FIXME: Builtin::BI__builtin_powif
  10975. // FIXME: Builtin::BI__builtin_powil
  10976. case Builtin::BI__builtin_copysign:
  10977. case Builtin::BI__builtin_copysignf:
  10978. case Builtin::BI__builtin_copysignl:
  10979. case Builtin::BI__builtin_copysignf128: {
  10980. APFloat RHS(0.);
  10981. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  10982. !EvaluateFloat(E->getArg(1), RHS, Info))
  10983. return false;
  10984. Result.copySign(RHS);
  10985. return true;
  10986. }
  10987. }
  10988. }
  10989. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  10990. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  10991. ComplexValue CV;
  10992. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  10993. return false;
  10994. Result = CV.FloatReal;
  10995. return true;
  10996. }
  10997. return Visit(E->getSubExpr());
  10998. }
  10999. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  11000. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  11001. ComplexValue CV;
  11002. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  11003. return false;
  11004. Result = CV.FloatImag;
  11005. return true;
  11006. }
  11007. VisitIgnoredValue(E->getSubExpr());
  11008. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  11009. Result = llvm::APFloat::getZero(Sem);
  11010. return true;
  11011. }
  11012. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11013. switch (E->getOpcode()) {
  11014. default: return Error(E);
  11015. case UO_Plus:
  11016. return EvaluateFloat(E->getSubExpr(), Result, Info);
  11017. case UO_Minus:
  11018. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  11019. return false;
  11020. Result.changeSign();
  11021. return true;
  11022. }
  11023. }
  11024. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  11025. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  11026. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11027. APFloat RHS(0.0);
  11028. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  11029. if (!LHSOK && !Info.noteFailure())
  11030. return false;
  11031. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  11032. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  11033. }
  11034. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  11035. Result = E->getValue();
  11036. return true;
  11037. }
  11038. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11039. const Expr* SubExpr = E->getSubExpr();
  11040. switch (E->getCastKind()) {
  11041. default:
  11042. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11043. case CK_IntegralToFloating: {
  11044. APSInt IntResult;
  11045. return EvaluateInteger(SubExpr, IntResult, Info) &&
  11046. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  11047. E->getType(), Result);
  11048. }
  11049. case CK_FloatingCast: {
  11050. if (!Visit(SubExpr))
  11051. return false;
  11052. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  11053. Result);
  11054. }
  11055. case CK_FloatingComplexToReal: {
  11056. ComplexValue V;
  11057. if (!EvaluateComplex(SubExpr, V, Info))
  11058. return false;
  11059. Result = V.getComplexFloatReal();
  11060. return true;
  11061. }
  11062. }
  11063. }
  11064. //===----------------------------------------------------------------------===//
  11065. // Complex Evaluation (for float and integer)
  11066. //===----------------------------------------------------------------------===//
  11067. namespace {
  11068. class ComplexExprEvaluator
  11069. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  11070. ComplexValue &Result;
  11071. public:
  11072. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  11073. : ExprEvaluatorBaseTy(info), Result(Result) {}
  11074. bool Success(const APValue &V, const Expr *e) {
  11075. Result.setFrom(V);
  11076. return true;
  11077. }
  11078. bool ZeroInitialization(const Expr *E);
  11079. //===--------------------------------------------------------------------===//
  11080. // Visitor Methods
  11081. //===--------------------------------------------------------------------===//
  11082. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  11083. bool VisitCastExpr(const CastExpr *E);
  11084. bool VisitBinaryOperator(const BinaryOperator *E);
  11085. bool VisitUnaryOperator(const UnaryOperator *E);
  11086. bool VisitInitListExpr(const InitListExpr *E);
  11087. };
  11088. } // end anonymous namespace
  11089. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  11090. EvalInfo &Info) {
  11091. assert(E->isRValue() && E->getType()->isAnyComplexType());
  11092. return ComplexExprEvaluator(Info, Result).Visit(E);
  11093. }
  11094. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  11095. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  11096. if (ElemTy->isRealFloatingType()) {
  11097. Result.makeComplexFloat();
  11098. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  11099. Result.FloatReal = Zero;
  11100. Result.FloatImag = Zero;
  11101. } else {
  11102. Result.makeComplexInt();
  11103. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  11104. Result.IntReal = Zero;
  11105. Result.IntImag = Zero;
  11106. }
  11107. return true;
  11108. }
  11109. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  11110. const Expr* SubExpr = E->getSubExpr();
  11111. if (SubExpr->getType()->isRealFloatingType()) {
  11112. Result.makeComplexFloat();
  11113. APFloat &Imag = Result.FloatImag;
  11114. if (!EvaluateFloat(SubExpr, Imag, Info))
  11115. return false;
  11116. Result.FloatReal = APFloat(Imag.getSemantics());
  11117. return true;
  11118. } else {
  11119. assert(SubExpr->getType()->isIntegerType() &&
  11120. "Unexpected imaginary literal.");
  11121. Result.makeComplexInt();
  11122. APSInt &Imag = Result.IntImag;
  11123. if (!EvaluateInteger(SubExpr, Imag, Info))
  11124. return false;
  11125. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  11126. return true;
  11127. }
  11128. }
  11129. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11130. switch (E->getCastKind()) {
  11131. case CK_BitCast:
  11132. case CK_BaseToDerived:
  11133. case CK_DerivedToBase:
  11134. case CK_UncheckedDerivedToBase:
  11135. case CK_Dynamic:
  11136. case CK_ToUnion:
  11137. case CK_ArrayToPointerDecay:
  11138. case CK_FunctionToPointerDecay:
  11139. case CK_NullToPointer:
  11140. case CK_NullToMemberPointer:
  11141. case CK_BaseToDerivedMemberPointer:
  11142. case CK_DerivedToBaseMemberPointer:
  11143. case CK_MemberPointerToBoolean:
  11144. case CK_ReinterpretMemberPointer:
  11145. case CK_ConstructorConversion:
  11146. case CK_IntegralToPointer:
  11147. case CK_PointerToIntegral:
  11148. case CK_PointerToBoolean:
  11149. case CK_ToVoid:
  11150. case CK_VectorSplat:
  11151. case CK_IntegralCast:
  11152. case CK_BooleanToSignedIntegral:
  11153. case CK_IntegralToBoolean:
  11154. case CK_IntegralToFloating:
  11155. case CK_FloatingToIntegral:
  11156. case CK_FloatingToBoolean:
  11157. case CK_FloatingCast:
  11158. case CK_CPointerToObjCPointerCast:
  11159. case CK_BlockPointerToObjCPointerCast:
  11160. case CK_AnyPointerToBlockPointerCast:
  11161. case CK_ObjCObjectLValueCast:
  11162. case CK_FloatingComplexToReal:
  11163. case CK_FloatingComplexToBoolean:
  11164. case CK_IntegralComplexToReal:
  11165. case CK_IntegralComplexToBoolean:
  11166. case CK_ARCProduceObject:
  11167. case CK_ARCConsumeObject:
  11168. case CK_ARCReclaimReturnedObject:
  11169. case CK_ARCExtendBlockObject:
  11170. case CK_CopyAndAutoreleaseBlockObject:
  11171. case CK_BuiltinFnToFnPtr:
  11172. case CK_ZeroToOCLOpaqueType:
  11173. case CK_NonAtomicToAtomic:
  11174. case CK_AddressSpaceConversion:
  11175. case CK_IntToOCLSampler:
  11176. case CK_FixedPointCast:
  11177. case CK_FixedPointToBoolean:
  11178. case CK_FixedPointToIntegral:
  11179. case CK_IntegralToFixedPoint:
  11180. llvm_unreachable("invalid cast kind for complex value");
  11181. case CK_LValueToRValue:
  11182. case CK_AtomicToNonAtomic:
  11183. case CK_NoOp:
  11184. case CK_LValueToRValueBitCast:
  11185. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11186. case CK_Dependent:
  11187. case CK_LValueBitCast:
  11188. case CK_UserDefinedConversion:
  11189. return Error(E);
  11190. case CK_FloatingRealToComplex: {
  11191. APFloat &Real = Result.FloatReal;
  11192. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  11193. return false;
  11194. Result.makeComplexFloat();
  11195. Result.FloatImag = APFloat(Real.getSemantics());
  11196. return true;
  11197. }
  11198. case CK_FloatingComplexCast: {
  11199. if (!Visit(E->getSubExpr()))
  11200. return false;
  11201. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11202. QualType From
  11203. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11204. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  11205. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  11206. }
  11207. case CK_FloatingComplexToIntegralComplex: {
  11208. if (!Visit(E->getSubExpr()))
  11209. return false;
  11210. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11211. QualType From
  11212. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11213. Result.makeComplexInt();
  11214. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  11215. To, Result.IntReal) &&
  11216. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  11217. To, Result.IntImag);
  11218. }
  11219. case CK_IntegralRealToComplex: {
  11220. APSInt &Real = Result.IntReal;
  11221. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  11222. return false;
  11223. Result.makeComplexInt();
  11224. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  11225. return true;
  11226. }
  11227. case CK_IntegralComplexCast: {
  11228. if (!Visit(E->getSubExpr()))
  11229. return false;
  11230. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11231. QualType From
  11232. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11233. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  11234. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  11235. return true;
  11236. }
  11237. case CK_IntegralComplexToFloatingComplex: {
  11238. if (!Visit(E->getSubExpr()))
  11239. return false;
  11240. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  11241. QualType From
  11242. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  11243. Result.makeComplexFloat();
  11244. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  11245. To, Result.FloatReal) &&
  11246. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  11247. To, Result.FloatImag);
  11248. }
  11249. }
  11250. llvm_unreachable("unknown cast resulting in complex value");
  11251. }
  11252. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  11253. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  11254. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11255. // Track whether the LHS or RHS is real at the type system level. When this is
  11256. // the case we can simplify our evaluation strategy.
  11257. bool LHSReal = false, RHSReal = false;
  11258. bool LHSOK;
  11259. if (E->getLHS()->getType()->isRealFloatingType()) {
  11260. LHSReal = true;
  11261. APFloat &Real = Result.FloatReal;
  11262. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  11263. if (LHSOK) {
  11264. Result.makeComplexFloat();
  11265. Result.FloatImag = APFloat(Real.getSemantics());
  11266. }
  11267. } else {
  11268. LHSOK = Visit(E->getLHS());
  11269. }
  11270. if (!LHSOK && !Info.noteFailure())
  11271. return false;
  11272. ComplexValue RHS;
  11273. if (E->getRHS()->getType()->isRealFloatingType()) {
  11274. RHSReal = true;
  11275. APFloat &Real = RHS.FloatReal;
  11276. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  11277. return false;
  11278. RHS.makeComplexFloat();
  11279. RHS.FloatImag = APFloat(Real.getSemantics());
  11280. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  11281. return false;
  11282. assert(!(LHSReal && RHSReal) &&
  11283. "Cannot have both operands of a complex operation be real.");
  11284. switch (E->getOpcode()) {
  11285. default: return Error(E);
  11286. case BO_Add:
  11287. if (Result.isComplexFloat()) {
  11288. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  11289. APFloat::rmNearestTiesToEven);
  11290. if (LHSReal)
  11291. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  11292. else if (!RHSReal)
  11293. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  11294. APFloat::rmNearestTiesToEven);
  11295. } else {
  11296. Result.getComplexIntReal() += RHS.getComplexIntReal();
  11297. Result.getComplexIntImag() += RHS.getComplexIntImag();
  11298. }
  11299. break;
  11300. case BO_Sub:
  11301. if (Result.isComplexFloat()) {
  11302. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  11303. APFloat::rmNearestTiesToEven);
  11304. if (LHSReal) {
  11305. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  11306. Result.getComplexFloatImag().changeSign();
  11307. } else if (!RHSReal) {
  11308. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  11309. APFloat::rmNearestTiesToEven);
  11310. }
  11311. } else {
  11312. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  11313. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  11314. }
  11315. break;
  11316. case BO_Mul:
  11317. if (Result.isComplexFloat()) {
  11318. // This is an implementation of complex multiplication according to the
  11319. // constraints laid out in C11 Annex G. The implementation uses the
  11320. // following naming scheme:
  11321. // (a + ib) * (c + id)
  11322. ComplexValue LHS = Result;
  11323. APFloat &A = LHS.getComplexFloatReal();
  11324. APFloat &B = LHS.getComplexFloatImag();
  11325. APFloat &C = RHS.getComplexFloatReal();
  11326. APFloat &D = RHS.getComplexFloatImag();
  11327. APFloat &ResR = Result.getComplexFloatReal();
  11328. APFloat &ResI = Result.getComplexFloatImag();
  11329. if (LHSReal) {
  11330. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  11331. ResR = A * C;
  11332. ResI = A * D;
  11333. } else if (RHSReal) {
  11334. ResR = C * A;
  11335. ResI = C * B;
  11336. } else {
  11337. // In the fully general case, we need to handle NaNs and infinities
  11338. // robustly.
  11339. APFloat AC = A * C;
  11340. APFloat BD = B * D;
  11341. APFloat AD = A * D;
  11342. APFloat BC = B * C;
  11343. ResR = AC - BD;
  11344. ResI = AD + BC;
  11345. if (ResR.isNaN() && ResI.isNaN()) {
  11346. bool Recalc = false;
  11347. if (A.isInfinity() || B.isInfinity()) {
  11348. A = APFloat::copySign(
  11349. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11350. B = APFloat::copySign(
  11351. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11352. if (C.isNaN())
  11353. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11354. if (D.isNaN())
  11355. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11356. Recalc = true;
  11357. }
  11358. if (C.isInfinity() || D.isInfinity()) {
  11359. C = APFloat::copySign(
  11360. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11361. D = APFloat::copySign(
  11362. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11363. if (A.isNaN())
  11364. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11365. if (B.isNaN())
  11366. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11367. Recalc = true;
  11368. }
  11369. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  11370. AD.isInfinity() || BC.isInfinity())) {
  11371. if (A.isNaN())
  11372. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  11373. if (B.isNaN())
  11374. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  11375. if (C.isNaN())
  11376. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  11377. if (D.isNaN())
  11378. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  11379. Recalc = true;
  11380. }
  11381. if (Recalc) {
  11382. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  11383. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  11384. }
  11385. }
  11386. }
  11387. } else {
  11388. ComplexValue LHS = Result;
  11389. Result.getComplexIntReal() =
  11390. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  11391. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  11392. Result.getComplexIntImag() =
  11393. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  11394. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  11395. }
  11396. break;
  11397. case BO_Div:
  11398. if (Result.isComplexFloat()) {
  11399. // This is an implementation of complex division according to the
  11400. // constraints laid out in C11 Annex G. The implementation uses the
  11401. // following naming scheme:
  11402. // (a + ib) / (c + id)
  11403. ComplexValue LHS = Result;
  11404. APFloat &A = LHS.getComplexFloatReal();
  11405. APFloat &B = LHS.getComplexFloatImag();
  11406. APFloat &C = RHS.getComplexFloatReal();
  11407. APFloat &D = RHS.getComplexFloatImag();
  11408. APFloat &ResR = Result.getComplexFloatReal();
  11409. APFloat &ResI = Result.getComplexFloatImag();
  11410. if (RHSReal) {
  11411. ResR = A / C;
  11412. ResI = B / C;
  11413. } else {
  11414. if (LHSReal) {
  11415. // No real optimizations we can do here, stub out with zero.
  11416. B = APFloat::getZero(A.getSemantics());
  11417. }
  11418. int DenomLogB = 0;
  11419. APFloat MaxCD = maxnum(abs(C), abs(D));
  11420. if (MaxCD.isFinite()) {
  11421. DenomLogB = ilogb(MaxCD);
  11422. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  11423. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  11424. }
  11425. APFloat Denom = C * C + D * D;
  11426. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  11427. APFloat::rmNearestTiesToEven);
  11428. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  11429. APFloat::rmNearestTiesToEven);
  11430. if (ResR.isNaN() && ResI.isNaN()) {
  11431. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  11432. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  11433. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  11434. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  11435. D.isFinite()) {
  11436. A = APFloat::copySign(
  11437. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  11438. B = APFloat::copySign(
  11439. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  11440. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  11441. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  11442. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  11443. C = APFloat::copySign(
  11444. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  11445. D = APFloat::copySign(
  11446. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  11447. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  11448. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  11449. }
  11450. }
  11451. }
  11452. } else {
  11453. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  11454. return Error(E, diag::note_expr_divide_by_zero);
  11455. ComplexValue LHS = Result;
  11456. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11457. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  11458. Result.getComplexIntReal() =
  11459. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  11460. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  11461. Result.getComplexIntImag() =
  11462. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  11463. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  11464. }
  11465. break;
  11466. }
  11467. return true;
  11468. }
  11469. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11470. // Get the operand value into 'Result'.
  11471. if (!Visit(E->getSubExpr()))
  11472. return false;
  11473. switch (E->getOpcode()) {
  11474. default:
  11475. return Error(E);
  11476. case UO_Extension:
  11477. return true;
  11478. case UO_Plus:
  11479. // The result is always just the subexpr.
  11480. return true;
  11481. case UO_Minus:
  11482. if (Result.isComplexFloat()) {
  11483. Result.getComplexFloatReal().changeSign();
  11484. Result.getComplexFloatImag().changeSign();
  11485. }
  11486. else {
  11487. Result.getComplexIntReal() = -Result.getComplexIntReal();
  11488. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11489. }
  11490. return true;
  11491. case UO_Not:
  11492. if (Result.isComplexFloat())
  11493. Result.getComplexFloatImag().changeSign();
  11494. else
  11495. Result.getComplexIntImag() = -Result.getComplexIntImag();
  11496. return true;
  11497. }
  11498. }
  11499. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  11500. if (E->getNumInits() == 2) {
  11501. if (E->getType()->isComplexType()) {
  11502. Result.makeComplexFloat();
  11503. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  11504. return false;
  11505. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  11506. return false;
  11507. } else {
  11508. Result.makeComplexInt();
  11509. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  11510. return false;
  11511. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  11512. return false;
  11513. }
  11514. return true;
  11515. }
  11516. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  11517. }
  11518. //===----------------------------------------------------------------------===//
  11519. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  11520. // implicit conversion.
  11521. //===----------------------------------------------------------------------===//
  11522. namespace {
  11523. class AtomicExprEvaluator :
  11524. public ExprEvaluatorBase<AtomicExprEvaluator> {
  11525. const LValue *This;
  11526. APValue &Result;
  11527. public:
  11528. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  11529. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  11530. bool Success(const APValue &V, const Expr *E) {
  11531. Result = V;
  11532. return true;
  11533. }
  11534. bool ZeroInitialization(const Expr *E) {
  11535. ImplicitValueInitExpr VIE(
  11536. E->getType()->castAs<AtomicType>()->getValueType());
  11537. // For atomic-qualified class (and array) types in C++, initialize the
  11538. // _Atomic-wrapped subobject directly, in-place.
  11539. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  11540. : Evaluate(Result, Info, &VIE);
  11541. }
  11542. bool VisitCastExpr(const CastExpr *E) {
  11543. switch (E->getCastKind()) {
  11544. default:
  11545. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11546. case CK_NonAtomicToAtomic:
  11547. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  11548. : Evaluate(Result, Info, E->getSubExpr());
  11549. }
  11550. }
  11551. };
  11552. } // end anonymous namespace
  11553. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  11554. EvalInfo &Info) {
  11555. assert(E->isRValue() && E->getType()->isAtomicType());
  11556. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  11557. }
  11558. //===----------------------------------------------------------------------===//
  11559. // Void expression evaluation, primarily for a cast to void on the LHS of a
  11560. // comma operator
  11561. //===----------------------------------------------------------------------===//
  11562. namespace {
  11563. class VoidExprEvaluator
  11564. : public ExprEvaluatorBase<VoidExprEvaluator> {
  11565. public:
  11566. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  11567. bool Success(const APValue &V, const Expr *e) { return true; }
  11568. bool ZeroInitialization(const Expr *E) { return true; }
  11569. bool VisitCastExpr(const CastExpr *E) {
  11570. switch (E->getCastKind()) {
  11571. default:
  11572. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11573. case CK_ToVoid:
  11574. VisitIgnoredValue(E->getSubExpr());
  11575. return true;
  11576. }
  11577. }
  11578. bool VisitCallExpr(const CallExpr *E) {
  11579. switch (E->getBuiltinCallee()) {
  11580. case Builtin::BI__assume:
  11581. case Builtin::BI__builtin_assume:
  11582. // The argument is not evaluated!
  11583. return true;
  11584. case Builtin::BI__builtin_operator_delete:
  11585. return HandleOperatorDeleteCall(Info, E);
  11586. default:
  11587. break;
  11588. }
  11589. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  11590. }
  11591. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  11592. };
  11593. } // end anonymous namespace
  11594. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  11595. // We cannot speculatively evaluate a delete expression.
  11596. if (Info.SpeculativeEvaluationDepth)
  11597. return false;
  11598. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  11599. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  11600. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  11601. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  11602. return false;
  11603. }
  11604. const Expr *Arg = E->getArgument();
  11605. LValue Pointer;
  11606. if (!EvaluatePointer(Arg, Pointer, Info))
  11607. return false;
  11608. if (Pointer.Designator.Invalid)
  11609. return false;
  11610. // Deleting a null pointer has no effect.
  11611. if (Pointer.isNullPointer()) {
  11612. // This is the only case where we need to produce an extension warning:
  11613. // the only other way we can succeed is if we find a dynamic allocation,
  11614. // and we will have warned when we allocated it in that case.
  11615. if (!Info.getLangOpts().CPlusPlus2a)
  11616. Info.CCEDiag(E, diag::note_constexpr_new);
  11617. return true;
  11618. }
  11619. Optional<DynAlloc *> Alloc = CheckDeleteKind(
  11620. Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
  11621. if (!Alloc)
  11622. return false;
  11623. QualType AllocType = Pointer.Base.getDynamicAllocType();
  11624. // For the non-array case, the designator must be empty if the static type
  11625. // does not have a virtual destructor.
  11626. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  11627. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  11628. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  11629. << Arg->getType()->getPointeeType() << AllocType;
  11630. return false;
  11631. }
  11632. // For a class type with a virtual destructor, the selected operator delete
  11633. // is the one looked up when building the destructor.
  11634. if (!E->isArrayForm() && !E->isGlobalDelete()) {
  11635. const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
  11636. if (VirtualDelete &&
  11637. !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
  11638. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  11639. << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
  11640. return false;
  11641. }
  11642. }
  11643. if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
  11644. (*Alloc)->Value, AllocType))
  11645. return false;
  11646. if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
  11647. // The element was already erased. This means the destructor call also
  11648. // deleted the object.
  11649. // FIXME: This probably results in undefined behavior before we get this
  11650. // far, and should be diagnosed elsewhere first.
  11651. Info.FFDiag(E, diag::note_constexpr_double_delete);
  11652. return false;
  11653. }
  11654. return true;
  11655. }
  11656. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  11657. assert(E->isRValue() && E->getType()->isVoidType());
  11658. return VoidExprEvaluator(Info).Visit(E);
  11659. }
  11660. //===----------------------------------------------------------------------===//
  11661. // Top level Expr::EvaluateAsRValue method.
  11662. //===----------------------------------------------------------------------===//
  11663. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  11664. // In C, function designators are not lvalues, but we evaluate them as if they
  11665. // are.
  11666. QualType T = E->getType();
  11667. if (E->isGLValue() || T->isFunctionType()) {
  11668. LValue LV;
  11669. if (!EvaluateLValue(E, LV, Info))
  11670. return false;
  11671. LV.moveInto(Result);
  11672. } else if (T->isVectorType()) {
  11673. if (!EvaluateVector(E, Result, Info))
  11674. return false;
  11675. } else if (T->isIntegralOrEnumerationType()) {
  11676. if (!IntExprEvaluator(Info, Result).Visit(E))
  11677. return false;
  11678. } else if (T->hasPointerRepresentation()) {
  11679. LValue LV;
  11680. if (!EvaluatePointer(E, LV, Info))
  11681. return false;
  11682. LV.moveInto(Result);
  11683. } else if (T->isRealFloatingType()) {
  11684. llvm::APFloat F(0.0);
  11685. if (!EvaluateFloat(E, F, Info))
  11686. return false;
  11687. Result = APValue(F);
  11688. } else if (T->isAnyComplexType()) {
  11689. ComplexValue C;
  11690. if (!EvaluateComplex(E, C, Info))
  11691. return false;
  11692. C.moveInto(Result);
  11693. } else if (T->isFixedPointType()) {
  11694. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  11695. } else if (T->isMemberPointerType()) {
  11696. MemberPtr P;
  11697. if (!EvaluateMemberPointer(E, P, Info))
  11698. return false;
  11699. P.moveInto(Result);
  11700. return true;
  11701. } else if (T->isArrayType()) {
  11702. LValue LV;
  11703. APValue &Value =
  11704. Info.CurrentCall->createTemporary(E, T, false, LV);
  11705. if (!EvaluateArray(E, LV, Value, Info))
  11706. return false;
  11707. Result = Value;
  11708. } else if (T->isRecordType()) {
  11709. LValue LV;
  11710. APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
  11711. if (!EvaluateRecord(E, LV, Value, Info))
  11712. return false;
  11713. Result = Value;
  11714. } else if (T->isVoidType()) {
  11715. if (!Info.getLangOpts().CPlusPlus11)
  11716. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  11717. << E->getType();
  11718. if (!EvaluateVoid(E, Info))
  11719. return false;
  11720. } else if (T->isAtomicType()) {
  11721. QualType Unqual = T.getAtomicUnqualifiedType();
  11722. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  11723. LValue LV;
  11724. APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
  11725. if (!EvaluateAtomic(E, &LV, Value, Info))
  11726. return false;
  11727. } else {
  11728. if (!EvaluateAtomic(E, nullptr, Result, Info))
  11729. return false;
  11730. }
  11731. } else if (Info.getLangOpts().CPlusPlus11) {
  11732. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  11733. return false;
  11734. } else {
  11735. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11736. return false;
  11737. }
  11738. return true;
  11739. }
  11740. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  11741. /// cases, the in-place evaluation is essential, since later initializers for
  11742. /// an object can indirectly refer to subobjects which were initialized earlier.
  11743. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  11744. const Expr *E, bool AllowNonLiteralTypes) {
  11745. assert(!E->isValueDependent());
  11746. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  11747. return false;
  11748. if (E->isRValue()) {
  11749. // Evaluate arrays and record types in-place, so that later initializers can
  11750. // refer to earlier-initialized members of the object.
  11751. QualType T = E->getType();
  11752. if (T->isArrayType())
  11753. return EvaluateArray(E, This, Result, Info);
  11754. else if (T->isRecordType())
  11755. return EvaluateRecord(E, This, Result, Info);
  11756. else if (T->isAtomicType()) {
  11757. QualType Unqual = T.getAtomicUnqualifiedType();
  11758. if (Unqual->isArrayType() || Unqual->isRecordType())
  11759. return EvaluateAtomic(E, &This, Result, Info);
  11760. }
  11761. }
  11762. // For any other type, in-place evaluation is unimportant.
  11763. return Evaluate(Result, Info, E);
  11764. }
  11765. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  11766. /// lvalue-to-rvalue cast if it is an lvalue.
  11767. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  11768. if (Info.EnableNewConstInterp) {
  11769. auto &InterpCtx = Info.Ctx.getInterpContext();
  11770. switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
  11771. case interp::InterpResult::Success:
  11772. return true;
  11773. case interp::InterpResult::Fail:
  11774. return false;
  11775. case interp::InterpResult::Bail:
  11776. break;
  11777. }
  11778. }
  11779. if (E->getType().isNull())
  11780. return false;
  11781. if (!CheckLiteralType(Info, E))
  11782. return false;
  11783. if (!::Evaluate(Result, Info, E))
  11784. return false;
  11785. if (E->isGLValue()) {
  11786. LValue LV;
  11787. LV.setFrom(Info.Ctx, Result);
  11788. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11789. return false;
  11790. }
  11791. // Check this core constant expression is a constant expression.
  11792. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
  11793. CheckMemoryLeaks(Info);
  11794. }
  11795. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  11796. const ASTContext &Ctx, bool &IsConst) {
  11797. // Fast-path evaluations of integer literals, since we sometimes see files
  11798. // containing vast quantities of these.
  11799. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  11800. Result.Val = APValue(APSInt(L->getValue(),
  11801. L->getType()->isUnsignedIntegerType()));
  11802. IsConst = true;
  11803. return true;
  11804. }
  11805. // This case should be rare, but we need to check it before we check on
  11806. // the type below.
  11807. if (Exp->getType().isNull()) {
  11808. IsConst = false;
  11809. return true;
  11810. }
  11811. // FIXME: Evaluating values of large array and record types can cause
  11812. // performance problems. Only do so in C++11 for now.
  11813. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  11814. Exp->getType()->isRecordType()) &&
  11815. !Ctx.getLangOpts().CPlusPlus11) {
  11816. IsConst = false;
  11817. return true;
  11818. }
  11819. return false;
  11820. }
  11821. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  11822. Expr::SideEffectsKind SEK) {
  11823. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  11824. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  11825. }
  11826. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  11827. const ASTContext &Ctx, EvalInfo &Info) {
  11828. bool IsConst;
  11829. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  11830. return IsConst;
  11831. return EvaluateAsRValue(Info, E, Result.Val);
  11832. }
  11833. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  11834. const ASTContext &Ctx,
  11835. Expr::SideEffectsKind AllowSideEffects,
  11836. EvalInfo &Info) {
  11837. if (!E->getType()->isIntegralOrEnumerationType())
  11838. return false;
  11839. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  11840. !ExprResult.Val.isInt() ||
  11841. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11842. return false;
  11843. return true;
  11844. }
  11845. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  11846. const ASTContext &Ctx,
  11847. Expr::SideEffectsKind AllowSideEffects,
  11848. EvalInfo &Info) {
  11849. if (!E->getType()->isFixedPointType())
  11850. return false;
  11851. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  11852. return false;
  11853. if (!ExprResult.Val.isFixedPoint() ||
  11854. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11855. return false;
  11856. return true;
  11857. }
  11858. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  11859. /// any crazy technique (that has nothing to do with language standards) that
  11860. /// we want to. If this function returns true, it returns the folded constant
  11861. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  11862. /// will be applied to the result.
  11863. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  11864. bool InConstantContext) const {
  11865. assert(!isValueDependent() &&
  11866. "Expression evaluator can't be called on a dependent expression.");
  11867. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11868. Info.InConstantContext = InConstantContext;
  11869. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  11870. }
  11871. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  11872. bool InConstantContext) const {
  11873. assert(!isValueDependent() &&
  11874. "Expression evaluator can't be called on a dependent expression.");
  11875. EvalResult Scratch;
  11876. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  11877. HandleConversionToBool(Scratch.Val, Result);
  11878. }
  11879. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  11880. SideEffectsKind AllowSideEffects,
  11881. bool InConstantContext) const {
  11882. assert(!isValueDependent() &&
  11883. "Expression evaluator can't be called on a dependent expression.");
  11884. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11885. Info.InConstantContext = InConstantContext;
  11886. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  11887. }
  11888. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  11889. SideEffectsKind AllowSideEffects,
  11890. bool InConstantContext) const {
  11891. assert(!isValueDependent() &&
  11892. "Expression evaluator can't be called on a dependent expression.");
  11893. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  11894. Info.InConstantContext = InConstantContext;
  11895. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  11896. }
  11897. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  11898. SideEffectsKind AllowSideEffects,
  11899. bool InConstantContext) const {
  11900. assert(!isValueDependent() &&
  11901. "Expression evaluator can't be called on a dependent expression.");
  11902. if (!getType()->isRealFloatingType())
  11903. return false;
  11904. EvalResult ExprResult;
  11905. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  11906. !ExprResult.Val.isFloat() ||
  11907. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  11908. return false;
  11909. Result = ExprResult.Val.getFloat();
  11910. return true;
  11911. }
  11912. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  11913. bool InConstantContext) const {
  11914. assert(!isValueDependent() &&
  11915. "Expression evaluator can't be called on a dependent expression.");
  11916. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  11917. Info.InConstantContext = InConstantContext;
  11918. LValue LV;
  11919. CheckedTemporaries CheckedTemps;
  11920. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  11921. Result.HasSideEffects ||
  11922. !CheckLValueConstantExpression(Info, getExprLoc(),
  11923. Ctx.getLValueReferenceType(getType()), LV,
  11924. Expr::EvaluateForCodeGen, CheckedTemps))
  11925. return false;
  11926. LV.moveInto(Result.Val);
  11927. return true;
  11928. }
  11929. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  11930. const ASTContext &Ctx) const {
  11931. assert(!isValueDependent() &&
  11932. "Expression evaluator can't be called on a dependent expression.");
  11933. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  11934. EvalInfo Info(Ctx, Result, EM);
  11935. Info.InConstantContext = true;
  11936. if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
  11937. return false;
  11938. if (!Info.discardCleanups())
  11939. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11940. return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
  11941. Result.Val, Usage) &&
  11942. CheckMemoryLeaks(Info);
  11943. }
  11944. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  11945. const VarDecl *VD,
  11946. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  11947. assert(!isValueDependent() &&
  11948. "Expression evaluator can't be called on a dependent expression.");
  11949. // FIXME: Evaluating initializers for large array and record types can cause
  11950. // performance problems. Only do so in C++11 for now.
  11951. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  11952. !Ctx.getLangOpts().CPlusPlus11)
  11953. return false;
  11954. Expr::EvalStatus EStatus;
  11955. EStatus.Diag = &Notes;
  11956. EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
  11957. ? EvalInfo::EM_ConstantExpression
  11958. : EvalInfo::EM_ConstantFold);
  11959. Info.setEvaluatingDecl(VD, Value);
  11960. Info.InConstantContext = true;
  11961. SourceLocation DeclLoc = VD->getLocation();
  11962. QualType DeclTy = VD->getType();
  11963. if (Info.EnableNewConstInterp) {
  11964. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  11965. switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
  11966. case interp::InterpResult::Fail:
  11967. // Bail out if an error was encountered.
  11968. return false;
  11969. case interp::InterpResult::Success:
  11970. // Evaluation succeeded and value was set.
  11971. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
  11972. case interp::InterpResult::Bail:
  11973. // Evaluate the value again for the tree evaluator to use.
  11974. break;
  11975. }
  11976. }
  11977. LValue LVal;
  11978. LVal.set(VD);
  11979. // C++11 [basic.start.init]p2:
  11980. // Variables with static storage duration or thread storage duration shall be
  11981. // zero-initialized before any other initialization takes place.
  11982. // This behavior is not present in C.
  11983. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  11984. !DeclTy->isReferenceType()) {
  11985. ImplicitValueInitExpr VIE(DeclTy);
  11986. if (!EvaluateInPlace(Value, Info, LVal, &VIE,
  11987. /*AllowNonLiteralTypes=*/true))
  11988. return false;
  11989. }
  11990. if (!EvaluateInPlace(Value, Info, LVal, this,
  11991. /*AllowNonLiteralTypes=*/true) ||
  11992. EStatus.HasSideEffects)
  11993. return false;
  11994. // At this point, any lifetime-extended temporaries are completely
  11995. // initialized.
  11996. Info.performLifetimeExtension();
  11997. if (!Info.discardCleanups())
  11998. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  11999. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
  12000. CheckMemoryLeaks(Info);
  12001. }
  12002. bool VarDecl::evaluateDestruction(
  12003. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  12004. assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
  12005. "cannot evaluate destruction of non-constant-initialized variable");
  12006. Expr::EvalStatus EStatus;
  12007. EStatus.Diag = &Notes;
  12008. // Make a copy of the value for the destructor to mutate.
  12009. APValue DestroyedValue = *getEvaluatedValue();
  12010. EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
  12011. Info.setEvaluatingDecl(this, DestroyedValue,
  12012. EvalInfo::EvaluatingDeclKind::Dtor);
  12013. Info.InConstantContext = true;
  12014. SourceLocation DeclLoc = getLocation();
  12015. QualType DeclTy = getType();
  12016. LValue LVal;
  12017. LVal.set(this);
  12018. // FIXME: Consider storing whether this variable has constant destruction in
  12019. // the EvaluatedStmt so that CodeGen can query it.
  12020. if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
  12021. EStatus.HasSideEffects)
  12022. return false;
  12023. if (!Info.discardCleanups())
  12024. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  12025. ensureEvaluatedStmt()->HasConstantDestruction = true;
  12026. return true;
  12027. }
  12028. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  12029. /// constant folded, but discard the result.
  12030. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  12031. assert(!isValueDependent() &&
  12032. "Expression evaluator can't be called on a dependent expression.");
  12033. EvalResult Result;
  12034. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  12035. !hasUnacceptableSideEffect(Result, SEK);
  12036. }
  12037. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  12038. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  12039. assert(!isValueDependent() &&
  12040. "Expression evaluator can't be called on a dependent expression.");
  12041. EvalResult EVResult;
  12042. EVResult.Diag = Diag;
  12043. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  12044. Info.InConstantContext = true;
  12045. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  12046. (void)Result;
  12047. assert(Result && "Could not evaluate expression");
  12048. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  12049. return EVResult.Val.getInt();
  12050. }
  12051. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  12052. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  12053. assert(!isValueDependent() &&
  12054. "Expression evaluator can't be called on a dependent expression.");
  12055. EvalResult EVResult;
  12056. EVResult.Diag = Diag;
  12057. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  12058. Info.InConstantContext = true;
  12059. Info.CheckingForUndefinedBehavior = true;
  12060. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  12061. (void)Result;
  12062. assert(Result && "Could not evaluate expression");
  12063. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  12064. return EVResult.Val.getInt();
  12065. }
  12066. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  12067. assert(!isValueDependent() &&
  12068. "Expression evaluator can't be called on a dependent expression.");
  12069. bool IsConst;
  12070. EvalResult EVResult;
  12071. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  12072. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  12073. Info.CheckingForUndefinedBehavior = true;
  12074. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  12075. }
  12076. }
  12077. bool Expr::EvalResult::isGlobalLValue() const {
  12078. assert(Val.isLValue());
  12079. return IsGlobalLValue(Val.getLValueBase());
  12080. }
  12081. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  12082. /// an integer constant expression.
  12083. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  12084. /// comma, etc
  12085. // CheckICE - This function does the fundamental ICE checking: the returned
  12086. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  12087. // and a (possibly null) SourceLocation indicating the location of the problem.
  12088. //
  12089. // Note that to reduce code duplication, this helper does no evaluation
  12090. // itself; the caller checks whether the expression is evaluatable, and
  12091. // in the rare cases where CheckICE actually cares about the evaluated
  12092. // value, it calls into Evaluate.
  12093. namespace {
  12094. enum ICEKind {
  12095. /// This expression is an ICE.
  12096. IK_ICE,
  12097. /// This expression is not an ICE, but if it isn't evaluated, it's
  12098. /// a legal subexpression for an ICE. This return value is used to handle
  12099. /// the comma operator in C99 mode, and non-constant subexpressions.
  12100. IK_ICEIfUnevaluated,
  12101. /// This expression is not an ICE, and is not a legal subexpression for one.
  12102. IK_NotICE
  12103. };
  12104. struct ICEDiag {
  12105. ICEKind Kind;
  12106. SourceLocation Loc;
  12107. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  12108. };
  12109. }
  12110. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  12111. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  12112. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  12113. Expr::EvalResult EVResult;
  12114. Expr::EvalStatus Status;
  12115. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12116. Info.InConstantContext = true;
  12117. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  12118. !EVResult.Val.isInt())
  12119. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12120. return NoDiag();
  12121. }
  12122. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  12123. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  12124. if (!E->getType()->isIntegralOrEnumerationType())
  12125. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12126. switch (E->getStmtClass()) {
  12127. #define ABSTRACT_STMT(Node)
  12128. #define STMT(Node, Base) case Expr::Node##Class:
  12129. #define EXPR(Node, Base)
  12130. #include "clang/AST/StmtNodes.inc"
  12131. case Expr::PredefinedExprClass:
  12132. case Expr::FloatingLiteralClass:
  12133. case Expr::ImaginaryLiteralClass:
  12134. case Expr::StringLiteralClass:
  12135. case Expr::ArraySubscriptExprClass:
  12136. case Expr::OMPArraySectionExprClass:
  12137. case Expr::MemberExprClass:
  12138. case Expr::CompoundAssignOperatorClass:
  12139. case Expr::CompoundLiteralExprClass:
  12140. case Expr::ExtVectorElementExprClass:
  12141. case Expr::DesignatedInitExprClass:
  12142. case Expr::ArrayInitLoopExprClass:
  12143. case Expr::ArrayInitIndexExprClass:
  12144. case Expr::NoInitExprClass:
  12145. case Expr::DesignatedInitUpdateExprClass:
  12146. case Expr::ImplicitValueInitExprClass:
  12147. case Expr::ParenListExprClass:
  12148. case Expr::VAArgExprClass:
  12149. case Expr::AddrLabelExprClass:
  12150. case Expr::StmtExprClass:
  12151. case Expr::CXXMemberCallExprClass:
  12152. case Expr::CUDAKernelCallExprClass:
  12153. case Expr::CXXDynamicCastExprClass:
  12154. case Expr::CXXTypeidExprClass:
  12155. case Expr::CXXUuidofExprClass:
  12156. case Expr::MSPropertyRefExprClass:
  12157. case Expr::MSPropertySubscriptExprClass:
  12158. case Expr::CXXNullPtrLiteralExprClass:
  12159. case Expr::UserDefinedLiteralClass:
  12160. case Expr::CXXThisExprClass:
  12161. case Expr::CXXThrowExprClass:
  12162. case Expr::CXXNewExprClass:
  12163. case Expr::CXXDeleteExprClass:
  12164. case Expr::CXXPseudoDestructorExprClass:
  12165. case Expr::UnresolvedLookupExprClass:
  12166. case Expr::TypoExprClass:
  12167. case Expr::DependentScopeDeclRefExprClass:
  12168. case Expr::CXXConstructExprClass:
  12169. case Expr::CXXInheritedCtorInitExprClass:
  12170. case Expr::CXXStdInitializerListExprClass:
  12171. case Expr::CXXBindTemporaryExprClass:
  12172. case Expr::ExprWithCleanupsClass:
  12173. case Expr::CXXTemporaryObjectExprClass:
  12174. case Expr::CXXUnresolvedConstructExprClass:
  12175. case Expr::CXXDependentScopeMemberExprClass:
  12176. case Expr::UnresolvedMemberExprClass:
  12177. case Expr::ObjCStringLiteralClass:
  12178. case Expr::ObjCBoxedExprClass:
  12179. case Expr::ObjCArrayLiteralClass:
  12180. case Expr::ObjCDictionaryLiteralClass:
  12181. case Expr::ObjCEncodeExprClass:
  12182. case Expr::ObjCMessageExprClass:
  12183. case Expr::ObjCSelectorExprClass:
  12184. case Expr::ObjCProtocolExprClass:
  12185. case Expr::ObjCIvarRefExprClass:
  12186. case Expr::ObjCPropertyRefExprClass:
  12187. case Expr::ObjCSubscriptRefExprClass:
  12188. case Expr::ObjCIsaExprClass:
  12189. case Expr::ObjCAvailabilityCheckExprClass:
  12190. case Expr::ShuffleVectorExprClass:
  12191. case Expr::ConvertVectorExprClass:
  12192. case Expr::BlockExprClass:
  12193. case Expr::NoStmtClass:
  12194. case Expr::OpaqueValueExprClass:
  12195. case Expr::PackExpansionExprClass:
  12196. case Expr::SubstNonTypeTemplateParmPackExprClass:
  12197. case Expr::FunctionParmPackExprClass:
  12198. case Expr::AsTypeExprClass:
  12199. case Expr::ObjCIndirectCopyRestoreExprClass:
  12200. case Expr::MaterializeTemporaryExprClass:
  12201. case Expr::PseudoObjectExprClass:
  12202. case Expr::AtomicExprClass:
  12203. case Expr::LambdaExprClass:
  12204. case Expr::CXXFoldExprClass:
  12205. case Expr::CoawaitExprClass:
  12206. case Expr::DependentCoawaitExprClass:
  12207. case Expr::CoyieldExprClass:
  12208. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12209. case Expr::InitListExprClass: {
  12210. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  12211. // form "T x = { a };" is equivalent to "T x = a;".
  12212. // Unless we're initializing a reference, T is a scalar as it is known to be
  12213. // of integral or enumeration type.
  12214. if (E->isRValue())
  12215. if (cast<InitListExpr>(E)->getNumInits() == 1)
  12216. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  12217. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12218. }
  12219. case Expr::SizeOfPackExprClass:
  12220. case Expr::GNUNullExprClass:
  12221. case Expr::SourceLocExprClass:
  12222. return NoDiag();
  12223. case Expr::SubstNonTypeTemplateParmExprClass:
  12224. return
  12225. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  12226. case Expr::ConstantExprClass:
  12227. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  12228. case Expr::ParenExprClass:
  12229. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  12230. case Expr::GenericSelectionExprClass:
  12231. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  12232. case Expr::IntegerLiteralClass:
  12233. case Expr::FixedPointLiteralClass:
  12234. case Expr::CharacterLiteralClass:
  12235. case Expr::ObjCBoolLiteralExprClass:
  12236. case Expr::CXXBoolLiteralExprClass:
  12237. case Expr::CXXScalarValueInitExprClass:
  12238. case Expr::TypeTraitExprClass:
  12239. case Expr::ConceptSpecializationExprClass:
  12240. case Expr::ArrayTypeTraitExprClass:
  12241. case Expr::ExpressionTraitExprClass:
  12242. case Expr::CXXNoexceptExprClass:
  12243. return NoDiag();
  12244. case Expr::CallExprClass:
  12245. case Expr::CXXOperatorCallExprClass: {
  12246. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  12247. // constant expressions, but they can never be ICEs because an ICE cannot
  12248. // contain an operand of (pointer to) function type.
  12249. const CallExpr *CE = cast<CallExpr>(E);
  12250. if (CE->getBuiltinCallee())
  12251. return CheckEvalInICE(E, Ctx);
  12252. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12253. }
  12254. case Expr::CXXRewrittenBinaryOperatorClass:
  12255. return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
  12256. Ctx);
  12257. case Expr::DeclRefExprClass: {
  12258. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  12259. return NoDiag();
  12260. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  12261. if (Ctx.getLangOpts().CPlusPlus &&
  12262. D && IsConstNonVolatile(D->getType())) {
  12263. // Parameter variables are never constants. Without this check,
  12264. // getAnyInitializer() can find a default argument, which leads
  12265. // to chaos.
  12266. if (isa<ParmVarDecl>(D))
  12267. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12268. // C++ 7.1.5.1p2
  12269. // A variable of non-volatile const-qualified integral or enumeration
  12270. // type initialized by an ICE can be used in ICEs.
  12271. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  12272. if (!Dcl->getType()->isIntegralOrEnumerationType())
  12273. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12274. const VarDecl *VD;
  12275. // Look for a declaration of this variable that has an initializer, and
  12276. // check whether it is an ICE.
  12277. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  12278. return NoDiag();
  12279. else
  12280. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  12281. }
  12282. }
  12283. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12284. }
  12285. case Expr::UnaryOperatorClass: {
  12286. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  12287. switch (Exp->getOpcode()) {
  12288. case UO_PostInc:
  12289. case UO_PostDec:
  12290. case UO_PreInc:
  12291. case UO_PreDec:
  12292. case UO_AddrOf:
  12293. case UO_Deref:
  12294. case UO_Coawait:
  12295. // C99 6.6/3 allows increment and decrement within unevaluated
  12296. // subexpressions of constant expressions, but they can never be ICEs
  12297. // because an ICE cannot contain an lvalue operand.
  12298. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12299. case UO_Extension:
  12300. case UO_LNot:
  12301. case UO_Plus:
  12302. case UO_Minus:
  12303. case UO_Not:
  12304. case UO_Real:
  12305. case UO_Imag:
  12306. return CheckICE(Exp->getSubExpr(), Ctx);
  12307. }
  12308. llvm_unreachable("invalid unary operator class");
  12309. }
  12310. case Expr::OffsetOfExprClass: {
  12311. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  12312. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  12313. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  12314. // compliance: we should warn earlier for offsetof expressions with
  12315. // array subscripts that aren't ICEs, and if the array subscripts
  12316. // are ICEs, the value of the offsetof must be an integer constant.
  12317. return CheckEvalInICE(E, Ctx);
  12318. }
  12319. case Expr::UnaryExprOrTypeTraitExprClass: {
  12320. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  12321. if ((Exp->getKind() == UETT_SizeOf) &&
  12322. Exp->getTypeOfArgument()->isVariableArrayType())
  12323. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12324. return NoDiag();
  12325. }
  12326. case Expr::BinaryOperatorClass: {
  12327. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  12328. switch (Exp->getOpcode()) {
  12329. case BO_PtrMemD:
  12330. case BO_PtrMemI:
  12331. case BO_Assign:
  12332. case BO_MulAssign:
  12333. case BO_DivAssign:
  12334. case BO_RemAssign:
  12335. case BO_AddAssign:
  12336. case BO_SubAssign:
  12337. case BO_ShlAssign:
  12338. case BO_ShrAssign:
  12339. case BO_AndAssign:
  12340. case BO_XorAssign:
  12341. case BO_OrAssign:
  12342. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  12343. // constant expressions, but they can never be ICEs because an ICE cannot
  12344. // contain an lvalue operand.
  12345. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12346. case BO_Mul:
  12347. case BO_Div:
  12348. case BO_Rem:
  12349. case BO_Add:
  12350. case BO_Sub:
  12351. case BO_Shl:
  12352. case BO_Shr:
  12353. case BO_LT:
  12354. case BO_GT:
  12355. case BO_LE:
  12356. case BO_GE:
  12357. case BO_EQ:
  12358. case BO_NE:
  12359. case BO_And:
  12360. case BO_Xor:
  12361. case BO_Or:
  12362. case BO_Comma:
  12363. case BO_Cmp: {
  12364. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12365. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12366. if (Exp->getOpcode() == BO_Div ||
  12367. Exp->getOpcode() == BO_Rem) {
  12368. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  12369. // we don't evaluate one.
  12370. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  12371. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  12372. if (REval == 0)
  12373. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12374. if (REval.isSigned() && REval.isAllOnesValue()) {
  12375. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  12376. if (LEval.isMinSignedValue())
  12377. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12378. }
  12379. }
  12380. }
  12381. if (Exp->getOpcode() == BO_Comma) {
  12382. if (Ctx.getLangOpts().C99) {
  12383. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  12384. // if it isn't evaluated.
  12385. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  12386. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  12387. } else {
  12388. // In both C89 and C++, commas in ICEs are illegal.
  12389. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12390. }
  12391. }
  12392. return Worst(LHSResult, RHSResult);
  12393. }
  12394. case BO_LAnd:
  12395. case BO_LOr: {
  12396. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  12397. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  12398. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  12399. // Rare case where the RHS has a comma "side-effect"; we need
  12400. // to actually check the condition to see whether the side
  12401. // with the comma is evaluated.
  12402. if ((Exp->getOpcode() == BO_LAnd) !=
  12403. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  12404. return RHSResult;
  12405. return NoDiag();
  12406. }
  12407. return Worst(LHSResult, RHSResult);
  12408. }
  12409. }
  12410. llvm_unreachable("invalid binary operator kind");
  12411. }
  12412. case Expr::ImplicitCastExprClass:
  12413. case Expr::CStyleCastExprClass:
  12414. case Expr::CXXFunctionalCastExprClass:
  12415. case Expr::CXXStaticCastExprClass:
  12416. case Expr::CXXReinterpretCastExprClass:
  12417. case Expr::CXXConstCastExprClass:
  12418. case Expr::ObjCBridgedCastExprClass: {
  12419. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  12420. if (isa<ExplicitCastExpr>(E)) {
  12421. if (const FloatingLiteral *FL
  12422. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  12423. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  12424. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  12425. APSInt IgnoredVal(DestWidth, !DestSigned);
  12426. bool Ignored;
  12427. // If the value does not fit in the destination type, the behavior is
  12428. // undefined, so we are not required to treat it as a constant
  12429. // expression.
  12430. if (FL->getValue().convertToInteger(IgnoredVal,
  12431. llvm::APFloat::rmTowardZero,
  12432. &Ignored) & APFloat::opInvalidOp)
  12433. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12434. return NoDiag();
  12435. }
  12436. }
  12437. switch (cast<CastExpr>(E)->getCastKind()) {
  12438. case CK_LValueToRValue:
  12439. case CK_AtomicToNonAtomic:
  12440. case CK_NonAtomicToAtomic:
  12441. case CK_NoOp:
  12442. case CK_IntegralToBoolean:
  12443. case CK_IntegralCast:
  12444. return CheckICE(SubExpr, Ctx);
  12445. default:
  12446. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12447. }
  12448. }
  12449. case Expr::BinaryConditionalOperatorClass: {
  12450. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  12451. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  12452. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  12453. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12454. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  12455. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  12456. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  12457. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  12458. return FalseResult;
  12459. }
  12460. case Expr::ConditionalOperatorClass: {
  12461. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  12462. // If the condition (ignoring parens) is a __builtin_constant_p call,
  12463. // then only the true side is actually considered in an integer constant
  12464. // expression, and it is fully evaluated. This is an important GNU
  12465. // extension. See GCC PR38377 for discussion.
  12466. if (const CallExpr *CallCE
  12467. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  12468. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  12469. return CheckEvalInICE(E, Ctx);
  12470. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  12471. if (CondResult.Kind == IK_NotICE)
  12472. return CondResult;
  12473. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  12474. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  12475. if (TrueResult.Kind == IK_NotICE)
  12476. return TrueResult;
  12477. if (FalseResult.Kind == IK_NotICE)
  12478. return FalseResult;
  12479. if (CondResult.Kind == IK_ICEIfUnevaluated)
  12480. return CondResult;
  12481. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  12482. return NoDiag();
  12483. // Rare case where the diagnostics depend on which side is evaluated
  12484. // Note that if we get here, CondResult is 0, and at least one of
  12485. // TrueResult and FalseResult is non-zero.
  12486. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  12487. return FalseResult;
  12488. return TrueResult;
  12489. }
  12490. case Expr::CXXDefaultArgExprClass:
  12491. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  12492. case Expr::CXXDefaultInitExprClass:
  12493. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  12494. case Expr::ChooseExprClass: {
  12495. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  12496. }
  12497. case Expr::BuiltinBitCastExprClass: {
  12498. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  12499. return ICEDiag(IK_NotICE, E->getBeginLoc());
  12500. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  12501. }
  12502. }
  12503. llvm_unreachable("Invalid StmtClass!");
  12504. }
  12505. /// Evaluate an expression as a C++11 integral constant expression.
  12506. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  12507. const Expr *E,
  12508. llvm::APSInt *Value,
  12509. SourceLocation *Loc) {
  12510. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12511. if (Loc) *Loc = E->getExprLoc();
  12512. return false;
  12513. }
  12514. APValue Result;
  12515. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  12516. return false;
  12517. if (!Result.isInt()) {
  12518. if (Loc) *Loc = E->getExprLoc();
  12519. return false;
  12520. }
  12521. if (Value) *Value = Result.getInt();
  12522. return true;
  12523. }
  12524. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  12525. SourceLocation *Loc) const {
  12526. assert(!isValueDependent() &&
  12527. "Expression evaluator can't be called on a dependent expression.");
  12528. if (Ctx.getLangOpts().CPlusPlus11)
  12529. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  12530. ICEDiag D = CheckICE(this, Ctx);
  12531. if (D.Kind != IK_ICE) {
  12532. if (Loc) *Loc = D.Loc;
  12533. return false;
  12534. }
  12535. return true;
  12536. }
  12537. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  12538. SourceLocation *Loc, bool isEvaluated) const {
  12539. assert(!isValueDependent() &&
  12540. "Expression evaluator can't be called on a dependent expression.");
  12541. if (Ctx.getLangOpts().CPlusPlus11)
  12542. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  12543. if (!isIntegerConstantExpr(Ctx, Loc))
  12544. return false;
  12545. // The only possible side-effects here are due to UB discovered in the
  12546. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  12547. // required to treat the expression as an ICE, so we produce the folded
  12548. // value.
  12549. EvalResult ExprResult;
  12550. Expr::EvalStatus Status;
  12551. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  12552. Info.InConstantContext = true;
  12553. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  12554. llvm_unreachable("ICE cannot be evaluated!");
  12555. Value = ExprResult.Val.getInt();
  12556. return true;
  12557. }
  12558. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  12559. assert(!isValueDependent() &&
  12560. "Expression evaluator can't be called on a dependent expression.");
  12561. return CheckICE(this, Ctx).Kind == IK_ICE;
  12562. }
  12563. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  12564. SourceLocation *Loc) const {
  12565. assert(!isValueDependent() &&
  12566. "Expression evaluator can't be called on a dependent expression.");
  12567. // We support this checking in C++98 mode in order to diagnose compatibility
  12568. // issues.
  12569. assert(Ctx.getLangOpts().CPlusPlus);
  12570. // Build evaluation settings.
  12571. Expr::EvalStatus Status;
  12572. SmallVector<PartialDiagnosticAt, 8> Diags;
  12573. Status.Diag = &Diags;
  12574. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  12575. APValue Scratch;
  12576. bool IsConstExpr =
  12577. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  12578. // FIXME: We don't produce a diagnostic for this, but the callers that
  12579. // call us on arbitrary full-expressions should generally not care.
  12580. Info.discardCleanups() && !Status.HasSideEffects;
  12581. if (!Diags.empty()) {
  12582. IsConstExpr = false;
  12583. if (Loc) *Loc = Diags[0].first;
  12584. } else if (!IsConstExpr) {
  12585. // FIXME: This shouldn't happen.
  12586. if (Loc) *Loc = getExprLoc();
  12587. }
  12588. return IsConstExpr;
  12589. }
  12590. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  12591. const FunctionDecl *Callee,
  12592. ArrayRef<const Expr*> Args,
  12593. const Expr *This) const {
  12594. assert(!isValueDependent() &&
  12595. "Expression evaluator can't be called on a dependent expression.");
  12596. Expr::EvalStatus Status;
  12597. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  12598. Info.InConstantContext = true;
  12599. LValue ThisVal;
  12600. const LValue *ThisPtr = nullptr;
  12601. if (This) {
  12602. #ifndef NDEBUG
  12603. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  12604. assert(MD && "Don't provide `this` for non-methods.");
  12605. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  12606. #endif
  12607. if (EvaluateObjectArgument(Info, This, ThisVal))
  12608. ThisPtr = &ThisVal;
  12609. if (Info.EvalStatus.HasSideEffects)
  12610. return false;
  12611. }
  12612. ArgVector ArgValues(Args.size());
  12613. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  12614. I != E; ++I) {
  12615. if ((*I)->isValueDependent() ||
  12616. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  12617. // If evaluation fails, throw away the argument entirely.
  12618. ArgValues[I - Args.begin()] = APValue();
  12619. if (Info.EvalStatus.HasSideEffects)
  12620. return false;
  12621. }
  12622. // Build fake call to Callee.
  12623. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  12624. ArgValues.data());
  12625. return Evaluate(Value, Info, this) && Info.discardCleanups() &&
  12626. !Info.EvalStatus.HasSideEffects;
  12627. }
  12628. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  12629. SmallVectorImpl<
  12630. PartialDiagnosticAt> &Diags) {
  12631. // FIXME: It would be useful to check constexpr function templates, but at the
  12632. // moment the constant expression evaluator cannot cope with the non-rigorous
  12633. // ASTs which we build for dependent expressions.
  12634. if (FD->isDependentContext())
  12635. return true;
  12636. Expr::EvalStatus Status;
  12637. Status.Diag = &Diags;
  12638. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  12639. Info.InConstantContext = true;
  12640. Info.CheckingPotentialConstantExpression = true;
  12641. // The constexpr VM attempts to compile all methods to bytecode here.
  12642. if (Info.EnableNewConstInterp) {
  12643. auto &InterpCtx = Info.Ctx.getInterpContext();
  12644. switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
  12645. case interp::InterpResult::Success:
  12646. case interp::InterpResult::Fail:
  12647. return Diags.empty();
  12648. case interp::InterpResult::Bail:
  12649. break;
  12650. }
  12651. }
  12652. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  12653. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  12654. // Fabricate an arbitrary expression on the stack and pretend that it
  12655. // is a temporary being used as the 'this' pointer.
  12656. LValue This;
  12657. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  12658. This.set({&VIE, Info.CurrentCall->Index});
  12659. ArrayRef<const Expr*> Args;
  12660. APValue Scratch;
  12661. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  12662. // Evaluate the call as a constant initializer, to allow the construction
  12663. // of objects of non-literal types.
  12664. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  12665. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  12666. } else {
  12667. SourceLocation Loc = FD->getLocation();
  12668. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  12669. Args, FD->getBody(), Info, Scratch, nullptr);
  12670. }
  12671. return Diags.empty();
  12672. }
  12673. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  12674. const FunctionDecl *FD,
  12675. SmallVectorImpl<
  12676. PartialDiagnosticAt> &Diags) {
  12677. assert(!E->isValueDependent() &&
  12678. "Expression evaluator can't be called on a dependent expression.");
  12679. Expr::EvalStatus Status;
  12680. Status.Diag = &Diags;
  12681. EvalInfo Info(FD->getASTContext(), Status,
  12682. EvalInfo::EM_ConstantExpressionUnevaluated);
  12683. Info.InConstantContext = true;
  12684. Info.CheckingPotentialConstantExpression = true;
  12685. // Fabricate a call stack frame to give the arguments a plausible cover story.
  12686. ArrayRef<const Expr*> Args;
  12687. ArgVector ArgValues(0);
  12688. bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
  12689. (void)Success;
  12690. assert(Success &&
  12691. "Failed to set up arguments for potential constant evaluation");
  12692. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  12693. APValue ResultScratch;
  12694. Evaluate(ResultScratch, Info, E);
  12695. return Diags.empty();
  12696. }
  12697. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  12698. unsigned Type) const {
  12699. if (!getType()->isPointerType())
  12700. return false;
  12701. Expr::EvalStatus Status;
  12702. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  12703. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  12704. }