ExprConstant.cpp 568 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920
  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 "Interp/Context.h"
  35. #include "Interp/Frame.h"
  36. #include "Interp/State.h"
  37. #include "clang/AST/APValue.h"
  38. #include "clang/AST/ASTContext.h"
  39. #include "clang/AST/ASTDiagnostic.h"
  40. #include "clang/AST/ASTLambda.h"
  41. #include "clang/AST/Attr.h"
  42. #include "clang/AST/CXXInheritance.h"
  43. #include "clang/AST/CharUnits.h"
  44. #include "clang/AST/CurrentSourceLocExprScope.h"
  45. #include "clang/AST/Expr.h"
  46. #include "clang/AST/OSLog.h"
  47. #include "clang/AST/OptionalDiagnostic.h"
  48. #include "clang/AST/RecordLayout.h"
  49. #include "clang/AST/StmtVisitor.h"
  50. #include "clang/AST/TypeLoc.h"
  51. #include "clang/Basic/Builtins.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "llvm/ADT/APFixedPoint.h"
  54. #include "llvm/ADT/Optional.h"
  55. #include "llvm/ADT/SmallBitVector.h"
  56. #include "llvm/Support/Debug.h"
  57. #include "llvm/Support/SaveAndRestore.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include <cstring>
  60. #include <functional>
  61. #define DEBUG_TYPE "exprconstant"
  62. using namespace clang;
  63. using llvm::APFixedPoint;
  64. using llvm::APInt;
  65. using llvm::APSInt;
  66. using llvm::APFloat;
  67. using llvm::FixedPointSemantics;
  68. using llvm::Optional;
  69. namespace {
  70. struct LValue;
  71. class CallStackFrame;
  72. class EvalInfo;
  73. using SourceLocExprScopeGuard =
  74. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  75. static QualType getType(APValue::LValueBase B) {
  76. return B.getType();
  77. }
  78. /// Get an LValue path entry, which is known to not be an array index, as a
  79. /// field declaration.
  80. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  81. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  82. }
  83. /// Get an LValue path entry, which is known to not be an array index, as a
  84. /// base class declaration.
  85. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  86. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  87. }
  88. /// Determine whether this LValue path entry for a base class names a virtual
  89. /// base class.
  90. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  91. return E.getAsBaseOrMember().getInt();
  92. }
  93. /// Given an expression, determine the type used to store the result of
  94. /// evaluating that expression.
  95. static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
  96. if (E->isPRValue())
  97. return E->getType();
  98. return Ctx.getLValueReferenceType(E->getType());
  99. }
  100. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  101. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  102. if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
  103. return DirectCallee->getAttr<AllocSizeAttr>();
  104. if (const Decl *IndirectCallee = CE->getCalleeDecl())
  105. return IndirectCallee->getAttr<AllocSizeAttr>();
  106. return nullptr;
  107. }
  108. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  109. /// This will look through a single cast.
  110. ///
  111. /// Returns null if we couldn't unwrap a function with alloc_size.
  112. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  113. if (!E->getType()->isPointerType())
  114. return nullptr;
  115. E = E->IgnoreParens();
  116. // If we're doing a variable assignment from e.g. malloc(N), there will
  117. // probably be a cast of some kind. In exotic cases, we might also see a
  118. // top-level ExprWithCleanups. Ignore them either way.
  119. if (const auto *FE = dyn_cast<FullExpr>(E))
  120. E = FE->getSubExpr()->IgnoreParens();
  121. if (const auto *Cast = dyn_cast<CastExpr>(E))
  122. E = Cast->getSubExpr()->IgnoreParens();
  123. if (const auto *CE = dyn_cast<CallExpr>(E))
  124. return getAllocSizeAttr(CE) ? CE : nullptr;
  125. return nullptr;
  126. }
  127. /// Determines whether or not the given Base contains a call to a function
  128. /// with the alloc_size attribute.
  129. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  130. const auto *E = Base.dyn_cast<const Expr *>();
  131. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  132. }
  133. /// Determines whether the given kind of constant expression is only ever
  134. /// used for name mangling. If so, it's permitted to reference things that we
  135. /// can't generate code for (in particular, dllimported functions).
  136. static bool isForManglingOnly(ConstantExprKind Kind) {
  137. switch (Kind) {
  138. case ConstantExprKind::Normal:
  139. case ConstantExprKind::ClassTemplateArgument:
  140. case ConstantExprKind::ImmediateInvocation:
  141. // Note that non-type template arguments of class type are emitted as
  142. // template parameter objects.
  143. return false;
  144. case ConstantExprKind::NonClassTemplateArgument:
  145. return true;
  146. }
  147. llvm_unreachable("unknown ConstantExprKind");
  148. }
  149. static bool isTemplateArgument(ConstantExprKind Kind) {
  150. switch (Kind) {
  151. case ConstantExprKind::Normal:
  152. case ConstantExprKind::ImmediateInvocation:
  153. return false;
  154. case ConstantExprKind::ClassTemplateArgument:
  155. case ConstantExprKind::NonClassTemplateArgument:
  156. return true;
  157. }
  158. llvm_unreachable("unknown ConstantExprKind");
  159. }
  160. /// The bound to claim that an array of unknown bound has.
  161. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  162. /// to an arbitrary value that's likely to loudly break things if it's used.
  163. static const uint64_t AssumedSizeForUnsizedArray =
  164. std::numeric_limits<uint64_t>::max() / 2;
  165. /// Determines if an LValue with the given LValueBase will have an unsized
  166. /// array in its designator.
  167. /// Find the path length and type of the most-derived subobject in the given
  168. /// path, and find the size of the containing array, if any.
  169. static unsigned
  170. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  171. ArrayRef<APValue::LValuePathEntry> Path,
  172. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  173. bool &FirstEntryIsUnsizedArray) {
  174. // This only accepts LValueBases from APValues, and APValues don't support
  175. // arrays that lack size info.
  176. assert(!isBaseAnAllocSizeCall(Base) &&
  177. "Unsized arrays shouldn't appear here");
  178. unsigned MostDerivedLength = 0;
  179. Type = getType(Base);
  180. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  181. if (Type->isArrayType()) {
  182. const ArrayType *AT = Ctx.getAsArrayType(Type);
  183. Type = AT->getElementType();
  184. MostDerivedLength = I + 1;
  185. IsArray = true;
  186. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  187. ArraySize = CAT->getSize().getZExtValue();
  188. } else {
  189. assert(I == 0 && "unexpected unsized array designator");
  190. FirstEntryIsUnsizedArray = true;
  191. ArraySize = AssumedSizeForUnsizedArray;
  192. }
  193. } else if (Type->isAnyComplexType()) {
  194. const ComplexType *CT = Type->castAs<ComplexType>();
  195. Type = CT->getElementType();
  196. ArraySize = 2;
  197. MostDerivedLength = I + 1;
  198. IsArray = true;
  199. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  200. Type = FD->getType();
  201. ArraySize = 0;
  202. MostDerivedLength = I + 1;
  203. IsArray = false;
  204. } else {
  205. // Path[I] describes a base class.
  206. ArraySize = 0;
  207. IsArray = false;
  208. }
  209. }
  210. return MostDerivedLength;
  211. }
  212. /// A path from a glvalue to a subobject of that glvalue.
  213. struct SubobjectDesignator {
  214. /// True if the subobject was named in a manner not supported by C++11. Such
  215. /// lvalues can still be folded, but they are not core constant expressions
  216. /// and we cannot perform lvalue-to-rvalue conversions on them.
  217. unsigned Invalid : 1;
  218. /// Is this a pointer one past the end of an object?
  219. unsigned IsOnePastTheEnd : 1;
  220. /// Indicator of whether the first entry is an unsized array.
  221. unsigned FirstEntryIsAnUnsizedArray : 1;
  222. /// Indicator of whether the most-derived object is an array element.
  223. unsigned MostDerivedIsArrayElement : 1;
  224. /// The length of the path to the most-derived object of which this is a
  225. /// subobject.
  226. unsigned MostDerivedPathLength : 28;
  227. /// The size of the array of which the most-derived object is an element.
  228. /// This will always be 0 if the most-derived object is not an array
  229. /// element. 0 is not an indicator of whether or not the most-derived object
  230. /// is an array, however, because 0-length arrays are allowed.
  231. ///
  232. /// If the current array is an unsized array, the value of this is
  233. /// undefined.
  234. uint64_t MostDerivedArraySize;
  235. /// The type of the most derived object referred to by this address.
  236. QualType MostDerivedType;
  237. typedef APValue::LValuePathEntry PathEntry;
  238. /// The entries on the path from the glvalue to the designated subobject.
  239. SmallVector<PathEntry, 8> Entries;
  240. SubobjectDesignator() : Invalid(true) {}
  241. explicit SubobjectDesignator(QualType T)
  242. : Invalid(false), IsOnePastTheEnd(false),
  243. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  244. MostDerivedPathLength(0), MostDerivedArraySize(0),
  245. MostDerivedType(T) {}
  246. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  247. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  248. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  249. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  250. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  251. if (!Invalid) {
  252. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  253. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  254. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  255. if (V.getLValueBase()) {
  256. bool IsArray = false;
  257. bool FirstIsUnsizedArray = false;
  258. MostDerivedPathLength = findMostDerivedSubobject(
  259. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  260. MostDerivedType, IsArray, FirstIsUnsizedArray);
  261. MostDerivedIsArrayElement = IsArray;
  262. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  263. }
  264. }
  265. }
  266. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  267. unsigned NewLength) {
  268. if (Invalid)
  269. return;
  270. assert(Base && "cannot truncate path for null pointer");
  271. assert(NewLength <= Entries.size() && "not a truncation");
  272. if (NewLength == Entries.size())
  273. return;
  274. Entries.resize(NewLength);
  275. bool IsArray = false;
  276. bool FirstIsUnsizedArray = false;
  277. MostDerivedPathLength = findMostDerivedSubobject(
  278. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  279. FirstIsUnsizedArray);
  280. MostDerivedIsArrayElement = IsArray;
  281. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  282. }
  283. void setInvalid() {
  284. Invalid = true;
  285. Entries.clear();
  286. }
  287. /// Determine whether the most derived subobject is an array without a
  288. /// known bound.
  289. bool isMostDerivedAnUnsizedArray() const {
  290. assert(!Invalid && "Calling this makes no sense on invalid designators");
  291. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  292. }
  293. /// Determine what the most derived array's size is. Results in an assertion
  294. /// failure if the most derived array lacks a size.
  295. uint64_t getMostDerivedArraySize() const {
  296. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  297. return MostDerivedArraySize;
  298. }
  299. /// Determine whether this is a one-past-the-end pointer.
  300. bool isOnePastTheEnd() const {
  301. assert(!Invalid);
  302. if (IsOnePastTheEnd)
  303. return true;
  304. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  305. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  306. MostDerivedArraySize)
  307. return true;
  308. return false;
  309. }
  310. /// Get the range of valid index adjustments in the form
  311. /// {maximum value that can be subtracted from this pointer,
  312. /// maximum value that can be added to this pointer}
  313. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  314. if (Invalid || isMostDerivedAnUnsizedArray())
  315. return {0, 0};
  316. // [expr.add]p4: For the purposes of these operators, a pointer to a
  317. // nonarray object behaves the same as a pointer to the first element of
  318. // an array of length one with the type of the object as its element type.
  319. bool IsArray = MostDerivedPathLength == Entries.size() &&
  320. MostDerivedIsArrayElement;
  321. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  322. : (uint64_t)IsOnePastTheEnd;
  323. uint64_t ArraySize =
  324. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  325. return {ArrayIndex, ArraySize - ArrayIndex};
  326. }
  327. /// Check that this refers to a valid subobject.
  328. bool isValidSubobject() const {
  329. if (Invalid)
  330. return false;
  331. return !isOnePastTheEnd();
  332. }
  333. /// Check that this refers to a valid subobject, and if not, produce a
  334. /// relevant diagnostic and set the designator as invalid.
  335. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  336. /// Get the type of the designated object.
  337. QualType getType(ASTContext &Ctx) const {
  338. assert(!Invalid && "invalid designator has no subobject type");
  339. return MostDerivedPathLength == Entries.size()
  340. ? MostDerivedType
  341. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  342. }
  343. /// Update this designator to refer to the first element within this array.
  344. void addArrayUnchecked(const ConstantArrayType *CAT) {
  345. Entries.push_back(PathEntry::ArrayIndex(0));
  346. // This is a most-derived object.
  347. MostDerivedType = CAT->getElementType();
  348. MostDerivedIsArrayElement = true;
  349. MostDerivedArraySize = CAT->getSize().getZExtValue();
  350. MostDerivedPathLength = Entries.size();
  351. }
  352. /// Update this designator to refer to the first element within the array of
  353. /// elements of type T. This is an array of unknown size.
  354. void addUnsizedArrayUnchecked(QualType ElemTy) {
  355. Entries.push_back(PathEntry::ArrayIndex(0));
  356. MostDerivedType = ElemTy;
  357. MostDerivedIsArrayElement = true;
  358. // The value in MostDerivedArraySize is undefined in this case. So, set it
  359. // to an arbitrary value that's likely to loudly break things if it's
  360. // used.
  361. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  362. MostDerivedPathLength = Entries.size();
  363. }
  364. /// Update this designator to refer to the given base or member of this
  365. /// object.
  366. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  367. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  368. // If this isn't a base class, it's a new most-derived object.
  369. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  370. MostDerivedType = FD->getType();
  371. MostDerivedIsArrayElement = false;
  372. MostDerivedArraySize = 0;
  373. MostDerivedPathLength = Entries.size();
  374. }
  375. }
  376. /// Update this designator to refer to the given complex component.
  377. void addComplexUnchecked(QualType EltTy, bool Imag) {
  378. Entries.push_back(PathEntry::ArrayIndex(Imag));
  379. // This is technically a most-derived object, though in practice this
  380. // is unlikely to matter.
  381. MostDerivedType = EltTy;
  382. MostDerivedIsArrayElement = true;
  383. MostDerivedArraySize = 2;
  384. MostDerivedPathLength = Entries.size();
  385. }
  386. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  387. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  388. const APSInt &N);
  389. /// Add N to the address of this subobject.
  390. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  391. if (Invalid || !N) return;
  392. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  393. if (isMostDerivedAnUnsizedArray()) {
  394. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  395. // Can't verify -- trust that the user is doing the right thing (or if
  396. // not, trust that the caller will catch the bad behavior).
  397. // FIXME: Should we reject if this overflows, at least?
  398. Entries.back() = PathEntry::ArrayIndex(
  399. Entries.back().getAsArrayIndex() + TruncatedN);
  400. return;
  401. }
  402. // [expr.add]p4: For the purposes of these operators, a pointer to a
  403. // nonarray object behaves the same as a pointer to the first element of
  404. // an array of length one with the type of the object as its element type.
  405. bool IsArray = MostDerivedPathLength == Entries.size() &&
  406. MostDerivedIsArrayElement;
  407. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  408. : (uint64_t)IsOnePastTheEnd;
  409. uint64_t ArraySize =
  410. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  411. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  412. // Calculate the actual index in a wide enough type, so we can include
  413. // it in the note.
  414. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  415. (llvm::APInt&)N += ArrayIndex;
  416. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  417. diagnosePointerArithmetic(Info, E, N);
  418. setInvalid();
  419. return;
  420. }
  421. ArrayIndex += TruncatedN;
  422. assert(ArrayIndex <= ArraySize &&
  423. "bounds check succeeded for out-of-bounds index");
  424. if (IsArray)
  425. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  426. else
  427. IsOnePastTheEnd = (ArrayIndex != 0);
  428. }
  429. };
  430. /// A scope at the end of which an object can need to be destroyed.
  431. enum class ScopeKind {
  432. Block,
  433. FullExpression,
  434. Call
  435. };
  436. /// A reference to a particular call and its arguments.
  437. struct CallRef {
  438. CallRef() : OrigCallee(), CallIndex(0), Version() {}
  439. CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
  440. : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
  441. explicit operator bool() const { return OrigCallee; }
  442. /// Get the parameter that the caller initialized, corresponding to the
  443. /// given parameter in the callee.
  444. const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
  445. return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
  446. : PVD;
  447. }
  448. /// The callee at the point where the arguments were evaluated. This might
  449. /// be different from the actual callee (a different redeclaration, or a
  450. /// virtual override), but this function's parameters are the ones that
  451. /// appear in the parameter map.
  452. const FunctionDecl *OrigCallee;
  453. /// The call index of the frame that holds the argument values.
  454. unsigned CallIndex;
  455. /// The version of the parameters corresponding to this call.
  456. unsigned Version;
  457. };
  458. /// A stack frame in the constexpr call stack.
  459. class CallStackFrame : public interp::Frame {
  460. public:
  461. EvalInfo &Info;
  462. /// Parent - The caller of this stack frame.
  463. CallStackFrame *Caller;
  464. /// Callee - The function which was called.
  465. const FunctionDecl *Callee;
  466. /// This - The binding for the this pointer in this call, if any.
  467. const LValue *This;
  468. /// Information on how to find the arguments to this call. Our arguments
  469. /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
  470. /// key and this value as the version.
  471. CallRef Arguments;
  472. /// Source location information about the default argument or default
  473. /// initializer expression we're evaluating, if any.
  474. CurrentSourceLocExprScope CurSourceLocExprScope;
  475. // Note that we intentionally use std::map here so that references to
  476. // values are stable.
  477. typedef std::pair<const void *, unsigned> MapKeyTy;
  478. typedef std::map<MapKeyTy, APValue> MapTy;
  479. /// Temporaries - Temporary lvalues materialized within this stack frame.
  480. MapTy Temporaries;
  481. /// CallLoc - The location of the call expression for this call.
  482. SourceLocation CallLoc;
  483. /// Index - The call index of this call.
  484. unsigned Index;
  485. /// The stack of integers for tracking version numbers for temporaries.
  486. SmallVector<unsigned, 2> TempVersionStack = {1};
  487. unsigned CurTempVersion = TempVersionStack.back();
  488. unsigned getTempVersion() const { return TempVersionStack.back(); }
  489. void pushTempVersion() {
  490. TempVersionStack.push_back(++CurTempVersion);
  491. }
  492. void popTempVersion() {
  493. TempVersionStack.pop_back();
  494. }
  495. CallRef createCall(const FunctionDecl *Callee) {
  496. return {Callee, Index, ++CurTempVersion};
  497. }
  498. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  499. // on the overall stack usage of deeply-recursing constexpr evaluations.
  500. // (We should cache this map rather than recomputing it repeatedly.)
  501. // But let's try this and see how it goes; we can look into caching the map
  502. // as a later change.
  503. /// LambdaCaptureFields - Mapping from captured variables/this to
  504. /// corresponding data members in the closure class.
  505. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  506. FieldDecl *LambdaThisCaptureField;
  507. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  508. const FunctionDecl *Callee, const LValue *This,
  509. CallRef Arguments);
  510. ~CallStackFrame();
  511. // Return the temporary for Key whose version number is Version.
  512. APValue *getTemporary(const void *Key, unsigned Version) {
  513. MapKeyTy KV(Key, Version);
  514. auto LB = Temporaries.lower_bound(KV);
  515. if (LB != Temporaries.end() && LB->first == KV)
  516. return &LB->second;
  517. // Pair (Key,Version) wasn't found in the map. Check that no elements
  518. // in the map have 'Key' as their key.
  519. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  520. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  521. "Element with key 'Key' found in map");
  522. return nullptr;
  523. }
  524. // Return the current temporary for Key in the map.
  525. APValue *getCurrentTemporary(const void *Key) {
  526. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  527. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  528. return &std::prev(UB)->second;
  529. return nullptr;
  530. }
  531. // Return the version number of the current temporary for Key.
  532. unsigned getCurrentTemporaryVersion(const void *Key) const {
  533. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  534. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  535. return std::prev(UB)->first.second;
  536. return 0;
  537. }
  538. /// Allocate storage for an object of type T in this stack frame.
  539. /// Populates LV with a handle to the created object. Key identifies
  540. /// the temporary within the stack frame, and must not be reused without
  541. /// bumping the temporary version number.
  542. template<typename KeyT>
  543. APValue &createTemporary(const KeyT *Key, QualType T,
  544. ScopeKind Scope, LValue &LV);
  545. /// Allocate storage for a parameter of a function call made in this frame.
  546. APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
  547. void describe(llvm::raw_ostream &OS) override;
  548. Frame *getCaller() const override { return Caller; }
  549. SourceLocation getCallLocation() const override { return CallLoc; }
  550. const FunctionDecl *getCallee() const override { return Callee; }
  551. bool isStdFunction() const {
  552. for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
  553. if (DC->isStdNamespace())
  554. return true;
  555. return false;
  556. }
  557. private:
  558. APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
  559. ScopeKind Scope);
  560. };
  561. /// Temporarily override 'this'.
  562. class ThisOverrideRAII {
  563. public:
  564. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  565. : Frame(Frame), OldThis(Frame.This) {
  566. if (Enable)
  567. Frame.This = NewThis;
  568. }
  569. ~ThisOverrideRAII() {
  570. Frame.This = OldThis;
  571. }
  572. private:
  573. CallStackFrame &Frame;
  574. const LValue *OldThis;
  575. };
  576. }
  577. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  578. const LValue &This, QualType ThisType);
  579. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  580. APValue::LValueBase LVBase, APValue &Value,
  581. QualType T);
  582. namespace {
  583. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  584. class Cleanup {
  585. llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
  586. APValue::LValueBase Base;
  587. QualType T;
  588. public:
  589. Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
  590. ScopeKind Scope)
  591. : Value(Val, Scope), Base(Base), T(T) {}
  592. /// Determine whether this cleanup should be performed at the end of the
  593. /// given kind of scope.
  594. bool isDestroyedAtEndOf(ScopeKind K) const {
  595. return (int)Value.getInt() >= (int)K;
  596. }
  597. bool endLifetime(EvalInfo &Info, bool RunDestructors) {
  598. if (RunDestructors) {
  599. SourceLocation Loc;
  600. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  601. Loc = VD->getLocation();
  602. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  603. Loc = E->getExprLoc();
  604. return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
  605. }
  606. *Value.getPointer() = APValue();
  607. return true;
  608. }
  609. bool hasSideEffect() {
  610. return T.isDestructedType();
  611. }
  612. };
  613. /// A reference to an object whose construction we are currently evaluating.
  614. struct ObjectUnderConstruction {
  615. APValue::LValueBase Base;
  616. ArrayRef<APValue::LValuePathEntry> Path;
  617. friend bool operator==(const ObjectUnderConstruction &LHS,
  618. const ObjectUnderConstruction &RHS) {
  619. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  620. }
  621. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  622. return llvm::hash_combine(Obj.Base, Obj.Path);
  623. }
  624. };
  625. enum class ConstructionPhase {
  626. None,
  627. Bases,
  628. AfterBases,
  629. AfterFields,
  630. Destroying,
  631. DestroyingBases
  632. };
  633. }
  634. namespace llvm {
  635. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  636. using Base = DenseMapInfo<APValue::LValueBase>;
  637. static ObjectUnderConstruction getEmptyKey() {
  638. return {Base::getEmptyKey(), {}}; }
  639. static ObjectUnderConstruction getTombstoneKey() {
  640. return {Base::getTombstoneKey(), {}};
  641. }
  642. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  643. return hash_value(Object);
  644. }
  645. static bool isEqual(const ObjectUnderConstruction &LHS,
  646. const ObjectUnderConstruction &RHS) {
  647. return LHS == RHS;
  648. }
  649. };
  650. }
  651. namespace {
  652. /// A dynamically-allocated heap object.
  653. struct DynAlloc {
  654. /// The value of this heap-allocated object.
  655. APValue Value;
  656. /// The allocating expression; used for diagnostics. Either a CXXNewExpr
  657. /// or a CallExpr (the latter is for direct calls to operator new inside
  658. /// std::allocator<T>::allocate).
  659. const Expr *AllocExpr = nullptr;
  660. enum Kind {
  661. New,
  662. ArrayNew,
  663. StdAllocator
  664. };
  665. /// Get the kind of the allocation. This must match between allocation
  666. /// and deallocation.
  667. Kind getKind() const {
  668. if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
  669. return NE->isArray() ? ArrayNew : New;
  670. assert(isa<CallExpr>(AllocExpr));
  671. return StdAllocator;
  672. }
  673. };
  674. struct DynAllocOrder {
  675. bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
  676. return L.getIndex() < R.getIndex();
  677. }
  678. };
  679. /// EvalInfo - This is a private struct used by the evaluator to capture
  680. /// information about a subexpression as it is folded. It retains information
  681. /// about the AST context, but also maintains information about the folded
  682. /// expression.
  683. ///
  684. /// If an expression could be evaluated, it is still possible it is not a C
  685. /// "integer constant expression" or constant expression. If not, this struct
  686. /// captures information about how and why not.
  687. ///
  688. /// One bit of information passed *into* the request for constant folding
  689. /// indicates whether the subexpression is "evaluated" or not according to C
  690. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  691. /// evaluate the expression regardless of what the RHS is, but C only allows
  692. /// certain things in certain situations.
  693. class EvalInfo : public interp::State {
  694. public:
  695. ASTContext &Ctx;
  696. /// EvalStatus - Contains information about the evaluation.
  697. Expr::EvalStatus &EvalStatus;
  698. /// CurrentCall - The top of the constexpr call stack.
  699. CallStackFrame *CurrentCall;
  700. /// CallStackDepth - The number of calls in the call stack right now.
  701. unsigned CallStackDepth;
  702. /// NextCallIndex - The next call index to assign.
  703. unsigned NextCallIndex;
  704. /// StepsLeft - The remaining number of evaluation steps we're permitted
  705. /// to perform. This is essentially a limit for the number of statements
  706. /// we will evaluate.
  707. unsigned StepsLeft;
  708. /// Enable the experimental new constant interpreter. If an expression is
  709. /// not supported by the interpreter, an error is triggered.
  710. bool EnableNewConstInterp;
  711. /// BottomFrame - The frame in which evaluation started. This must be
  712. /// initialized after CurrentCall and CallStackDepth.
  713. CallStackFrame BottomFrame;
  714. /// A stack of values whose lifetimes end at the end of some surrounding
  715. /// evaluation frame.
  716. llvm::SmallVector<Cleanup, 16> CleanupStack;
  717. /// EvaluatingDecl - This is the declaration whose initializer is being
  718. /// evaluated, if any.
  719. APValue::LValueBase EvaluatingDecl;
  720. enum class EvaluatingDeclKind {
  721. None,
  722. /// We're evaluating the construction of EvaluatingDecl.
  723. Ctor,
  724. /// We're evaluating the destruction of EvaluatingDecl.
  725. Dtor,
  726. };
  727. EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
  728. /// EvaluatingDeclValue - This is the value being constructed for the
  729. /// declaration whose initializer is being evaluated, if any.
  730. APValue *EvaluatingDeclValue;
  731. /// Set of objects that are currently being constructed.
  732. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  733. ObjectsUnderConstruction;
  734. /// Current heap allocations, along with the location where each was
  735. /// allocated. We use std::map here because we need stable addresses
  736. /// for the stored APValues.
  737. std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
  738. /// The number of heap allocations performed so far in this evaluation.
  739. unsigned NumHeapAllocs = 0;
  740. struct EvaluatingConstructorRAII {
  741. EvalInfo &EI;
  742. ObjectUnderConstruction Object;
  743. bool DidInsert;
  744. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  745. bool HasBases)
  746. : EI(EI), Object(Object) {
  747. DidInsert =
  748. EI.ObjectsUnderConstruction
  749. .insert({Object, HasBases ? ConstructionPhase::Bases
  750. : ConstructionPhase::AfterBases})
  751. .second;
  752. }
  753. void finishedConstructingBases() {
  754. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  755. }
  756. void finishedConstructingFields() {
  757. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
  758. }
  759. ~EvaluatingConstructorRAII() {
  760. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  761. }
  762. };
  763. struct EvaluatingDestructorRAII {
  764. EvalInfo &EI;
  765. ObjectUnderConstruction Object;
  766. bool DidInsert;
  767. EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
  768. : EI(EI), Object(Object) {
  769. DidInsert = EI.ObjectsUnderConstruction
  770. .insert({Object, ConstructionPhase::Destroying})
  771. .second;
  772. }
  773. void startedDestroyingBases() {
  774. EI.ObjectsUnderConstruction[Object] =
  775. ConstructionPhase::DestroyingBases;
  776. }
  777. ~EvaluatingDestructorRAII() {
  778. if (DidInsert)
  779. EI.ObjectsUnderConstruction.erase(Object);
  780. }
  781. };
  782. ConstructionPhase
  783. isEvaluatingCtorDtor(APValue::LValueBase Base,
  784. ArrayRef<APValue::LValuePathEntry> Path) {
  785. return ObjectsUnderConstruction.lookup({Base, Path});
  786. }
  787. /// If we're currently speculatively evaluating, the outermost call stack
  788. /// depth at which we can mutate state, otherwise 0.
  789. unsigned SpeculativeEvaluationDepth = 0;
  790. /// The current array initialization index, if we're performing array
  791. /// initialization.
  792. uint64_t ArrayInitIndex = -1;
  793. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  794. /// notes attached to it will also be stored, otherwise they will not be.
  795. bool HasActiveDiagnostic;
  796. /// Have we emitted a diagnostic explaining why we couldn't constant
  797. /// fold (not just why it's not strictly a constant expression)?
  798. bool HasFoldFailureDiagnostic;
  799. /// Whether or not we're in a context where the front end requires a
  800. /// constant value.
  801. bool InConstantContext;
  802. /// Whether we're checking that an expression is a potential constant
  803. /// expression. If so, do not fail on constructs that could become constant
  804. /// later on (such as a use of an undefined global).
  805. bool CheckingPotentialConstantExpression = false;
  806. /// Whether we're checking for an expression that has undefined behavior.
  807. /// If so, we will produce warnings if we encounter an operation that is
  808. /// always undefined.
  809. ///
  810. /// Note that we still need to evaluate the expression normally when this
  811. /// is set; this is used when evaluating ICEs in C.
  812. bool CheckingForUndefinedBehavior = false;
  813. enum EvaluationMode {
  814. /// Evaluate as a constant expression. Stop if we find that the expression
  815. /// is not a constant expression.
  816. EM_ConstantExpression,
  817. /// Evaluate as a constant expression. Stop if we find that the expression
  818. /// is not a constant expression. Some expressions can be retried in the
  819. /// optimizer if we don't constant fold them here, but in an unevaluated
  820. /// context we try to fold them immediately since the optimizer never
  821. /// gets a chance to look at it.
  822. EM_ConstantExpressionUnevaluated,
  823. /// Fold the expression to a constant. Stop if we hit a side-effect that
  824. /// we can't model.
  825. EM_ConstantFold,
  826. /// Evaluate in any way we know how. Don't worry about side-effects that
  827. /// can't be modeled.
  828. EM_IgnoreSideEffects,
  829. } EvalMode;
  830. /// Are we checking whether the expression is a potential constant
  831. /// expression?
  832. bool checkingPotentialConstantExpression() const override {
  833. return CheckingPotentialConstantExpression;
  834. }
  835. /// Are we checking an expression for overflow?
  836. // FIXME: We should check for any kind of undefined or suspicious behavior
  837. // in such constructs, not just overflow.
  838. bool checkingForUndefinedBehavior() const override {
  839. return CheckingForUndefinedBehavior;
  840. }
  841. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  842. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  843. CallStackDepth(0), NextCallIndex(1),
  844. StepsLeft(C.getLangOpts().ConstexprStepLimit),
  845. EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
  846. BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
  847. EvaluatingDecl((const ValueDecl *)nullptr),
  848. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  849. HasFoldFailureDiagnostic(false), InConstantContext(false),
  850. EvalMode(Mode) {}
  851. ~EvalInfo() {
  852. discardCleanups();
  853. }
  854. ASTContext &getCtx() const override { return Ctx; }
  855. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
  856. EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
  857. EvaluatingDecl = Base;
  858. IsEvaluatingDecl = EDK;
  859. EvaluatingDeclValue = &Value;
  860. }
  861. bool CheckCallLimit(SourceLocation Loc) {
  862. // Don't perform any constexpr calls (other than the call we're checking)
  863. // when checking a potential constant expression.
  864. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  865. return false;
  866. if (NextCallIndex == 0) {
  867. // NextCallIndex has wrapped around.
  868. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  869. return false;
  870. }
  871. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  872. return true;
  873. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  874. << getLangOpts().ConstexprCallDepth;
  875. return false;
  876. }
  877. std::pair<CallStackFrame *, unsigned>
  878. getCallFrameAndDepth(unsigned CallIndex) {
  879. assert(CallIndex && "no call index in getCallFrameAndDepth");
  880. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  881. // be null in this loop.
  882. unsigned Depth = CallStackDepth;
  883. CallStackFrame *Frame = CurrentCall;
  884. while (Frame->Index > CallIndex) {
  885. Frame = Frame->Caller;
  886. --Depth;
  887. }
  888. if (Frame->Index == CallIndex)
  889. return {Frame, Depth};
  890. return {nullptr, 0};
  891. }
  892. bool nextStep(const Stmt *S) {
  893. if (!StepsLeft) {
  894. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  895. return false;
  896. }
  897. --StepsLeft;
  898. return true;
  899. }
  900. APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
  901. Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
  902. Optional<DynAlloc*> Result;
  903. auto It = HeapAllocs.find(DA);
  904. if (It != HeapAllocs.end())
  905. Result = &It->second;
  906. return Result;
  907. }
  908. /// Get the allocated storage for the given parameter of the given call.
  909. APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
  910. CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
  911. return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
  912. : nullptr;
  913. }
  914. /// Information about a stack frame for std::allocator<T>::[de]allocate.
  915. struct StdAllocatorCaller {
  916. unsigned FrameIndex;
  917. QualType ElemType;
  918. explicit operator bool() const { return FrameIndex != 0; };
  919. };
  920. StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
  921. for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
  922. Call = Call->Caller) {
  923. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
  924. if (!MD)
  925. continue;
  926. const IdentifierInfo *FnII = MD->getIdentifier();
  927. if (!FnII || !FnII->isStr(FnName))
  928. continue;
  929. const auto *CTSD =
  930. dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
  931. if (!CTSD)
  932. continue;
  933. const IdentifierInfo *ClassII = CTSD->getIdentifier();
  934. const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
  935. if (CTSD->isInStdNamespace() && ClassII &&
  936. ClassII->isStr("allocator") && TAL.size() >= 1 &&
  937. TAL[0].getKind() == TemplateArgument::Type)
  938. return {Call->Index, TAL[0].getAsType()};
  939. }
  940. return {};
  941. }
  942. void performLifetimeExtension() {
  943. // Disable the cleanups for lifetime-extended temporaries.
  944. llvm::erase_if(CleanupStack, [](Cleanup &C) {
  945. return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
  946. });
  947. }
  948. /// Throw away any remaining cleanups at the end of evaluation. If any
  949. /// cleanups would have had a side-effect, note that as an unmodeled
  950. /// side-effect and return false. Otherwise, return true.
  951. bool discardCleanups() {
  952. for (Cleanup &C : CleanupStack) {
  953. if (C.hasSideEffect() && !noteSideEffect()) {
  954. CleanupStack.clear();
  955. return false;
  956. }
  957. }
  958. CleanupStack.clear();
  959. return true;
  960. }
  961. private:
  962. interp::Frame *getCurrentFrame() override { return CurrentCall; }
  963. const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
  964. bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
  965. void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
  966. void setFoldFailureDiagnostic(bool Flag) override {
  967. HasFoldFailureDiagnostic = Flag;
  968. }
  969. Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
  970. // If we have a prior diagnostic, it will be noting that the expression
  971. // isn't a constant expression. This diagnostic is more important,
  972. // unless we require this evaluation to produce a constant expression.
  973. //
  974. // FIXME: We might want to show both diagnostics to the user in
  975. // EM_ConstantFold mode.
  976. bool hasPriorDiagnostic() override {
  977. if (!EvalStatus.Diag->empty()) {
  978. switch (EvalMode) {
  979. case EM_ConstantFold:
  980. case EM_IgnoreSideEffects:
  981. if (!HasFoldFailureDiagnostic)
  982. break;
  983. // We've already failed to fold something. Keep that diagnostic.
  984. LLVM_FALLTHROUGH;
  985. case EM_ConstantExpression:
  986. case EM_ConstantExpressionUnevaluated:
  987. setActiveDiagnostic(false);
  988. return true;
  989. }
  990. }
  991. return false;
  992. }
  993. unsigned getCallStackDepth() override { return CallStackDepth; }
  994. public:
  995. /// Should we continue evaluation after encountering a side-effect that we
  996. /// couldn't model?
  997. bool keepEvaluatingAfterSideEffect() {
  998. switch (EvalMode) {
  999. case EM_IgnoreSideEffects:
  1000. return true;
  1001. case EM_ConstantExpression:
  1002. case EM_ConstantExpressionUnevaluated:
  1003. case EM_ConstantFold:
  1004. // By default, assume any side effect might be valid in some other
  1005. // evaluation of this expression from a different context.
  1006. return checkingPotentialConstantExpression() ||
  1007. checkingForUndefinedBehavior();
  1008. }
  1009. llvm_unreachable("Missed EvalMode case");
  1010. }
  1011. /// Note that we have had a side-effect, and determine whether we should
  1012. /// keep evaluating.
  1013. bool noteSideEffect() {
  1014. EvalStatus.HasSideEffects = true;
  1015. return keepEvaluatingAfterSideEffect();
  1016. }
  1017. /// Should we continue evaluation after encountering undefined behavior?
  1018. bool keepEvaluatingAfterUndefinedBehavior() {
  1019. switch (EvalMode) {
  1020. case EM_IgnoreSideEffects:
  1021. case EM_ConstantFold:
  1022. return true;
  1023. case EM_ConstantExpression:
  1024. case EM_ConstantExpressionUnevaluated:
  1025. return checkingForUndefinedBehavior();
  1026. }
  1027. llvm_unreachable("Missed EvalMode case");
  1028. }
  1029. /// Note that we hit something that was technically undefined behavior, but
  1030. /// that we can evaluate past it (such as signed overflow or floating-point
  1031. /// division by zero.)
  1032. bool noteUndefinedBehavior() override {
  1033. EvalStatus.HasUndefinedBehavior = true;
  1034. return keepEvaluatingAfterUndefinedBehavior();
  1035. }
  1036. /// Should we continue evaluation as much as possible after encountering a
  1037. /// construct which can't be reduced to a value?
  1038. bool keepEvaluatingAfterFailure() const override {
  1039. if (!StepsLeft)
  1040. return false;
  1041. switch (EvalMode) {
  1042. case EM_ConstantExpression:
  1043. case EM_ConstantExpressionUnevaluated:
  1044. case EM_ConstantFold:
  1045. case EM_IgnoreSideEffects:
  1046. return checkingPotentialConstantExpression() ||
  1047. checkingForUndefinedBehavior();
  1048. }
  1049. llvm_unreachable("Missed EvalMode case");
  1050. }
  1051. /// Notes that we failed to evaluate an expression that other expressions
  1052. /// directly depend on, and determine if we should keep evaluating. This
  1053. /// should only be called if we actually intend to keep evaluating.
  1054. ///
  1055. /// Call noteSideEffect() instead if we may be able to ignore the value that
  1056. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  1057. ///
  1058. /// (Foo(), 1) // use noteSideEffect
  1059. /// (Foo() || true) // use noteSideEffect
  1060. /// Foo() + 1 // use noteFailure
  1061. LLVM_NODISCARD bool noteFailure() {
  1062. // Failure when evaluating some expression often means there is some
  1063. // subexpression whose evaluation was skipped. Therefore, (because we
  1064. // don't track whether we skipped an expression when unwinding after an
  1065. // evaluation failure) every evaluation failure that bubbles up from a
  1066. // subexpression implies that a side-effect has potentially happened. We
  1067. // skip setting the HasSideEffects flag to true until we decide to
  1068. // continue evaluating after that point, which happens here.
  1069. bool KeepGoing = keepEvaluatingAfterFailure();
  1070. EvalStatus.HasSideEffects |= KeepGoing;
  1071. return KeepGoing;
  1072. }
  1073. class ArrayInitLoopIndex {
  1074. EvalInfo &Info;
  1075. uint64_t OuterIndex;
  1076. public:
  1077. ArrayInitLoopIndex(EvalInfo &Info)
  1078. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  1079. Info.ArrayInitIndex = 0;
  1080. }
  1081. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  1082. operator uint64_t&() { return Info.ArrayInitIndex; }
  1083. };
  1084. };
  1085. /// Object used to treat all foldable expressions as constant expressions.
  1086. struct FoldConstant {
  1087. EvalInfo &Info;
  1088. bool Enabled;
  1089. bool HadNoPriorDiags;
  1090. EvalInfo::EvaluationMode OldMode;
  1091. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  1092. : Info(Info),
  1093. Enabled(Enabled),
  1094. HadNoPriorDiags(Info.EvalStatus.Diag &&
  1095. Info.EvalStatus.Diag->empty() &&
  1096. !Info.EvalStatus.HasSideEffects),
  1097. OldMode(Info.EvalMode) {
  1098. if (Enabled)
  1099. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1100. }
  1101. void keepDiagnostics() { Enabled = false; }
  1102. ~FoldConstant() {
  1103. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1104. !Info.EvalStatus.HasSideEffects)
  1105. Info.EvalStatus.Diag->clear();
  1106. Info.EvalMode = OldMode;
  1107. }
  1108. };
  1109. /// RAII object used to set the current evaluation mode to ignore
  1110. /// side-effects.
  1111. struct IgnoreSideEffectsRAII {
  1112. EvalInfo &Info;
  1113. EvalInfo::EvaluationMode OldMode;
  1114. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1115. : Info(Info), OldMode(Info.EvalMode) {
  1116. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1117. }
  1118. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1119. };
  1120. /// RAII object used to optionally suppress diagnostics and side-effects from
  1121. /// a speculative evaluation.
  1122. class SpeculativeEvaluationRAII {
  1123. EvalInfo *Info = nullptr;
  1124. Expr::EvalStatus OldStatus;
  1125. unsigned OldSpeculativeEvaluationDepth;
  1126. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1127. Info = Other.Info;
  1128. OldStatus = Other.OldStatus;
  1129. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1130. Other.Info = nullptr;
  1131. }
  1132. void maybeRestoreState() {
  1133. if (!Info)
  1134. return;
  1135. Info->EvalStatus = OldStatus;
  1136. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1137. }
  1138. public:
  1139. SpeculativeEvaluationRAII() = default;
  1140. SpeculativeEvaluationRAII(
  1141. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1142. : Info(&Info), OldStatus(Info.EvalStatus),
  1143. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1144. Info.EvalStatus.Diag = NewDiag;
  1145. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1146. }
  1147. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1148. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1149. moveFromAndCancel(std::move(Other));
  1150. }
  1151. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1152. maybeRestoreState();
  1153. moveFromAndCancel(std::move(Other));
  1154. return *this;
  1155. }
  1156. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1157. };
  1158. /// RAII object wrapping a full-expression or block scope, and handling
  1159. /// the ending of the lifetime of temporaries created within it.
  1160. template<ScopeKind Kind>
  1161. class ScopeRAII {
  1162. EvalInfo &Info;
  1163. unsigned OldStackSize;
  1164. public:
  1165. ScopeRAII(EvalInfo &Info)
  1166. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1167. // Push a new temporary version. This is needed to distinguish between
  1168. // temporaries created in different iterations of a loop.
  1169. Info.CurrentCall->pushTempVersion();
  1170. }
  1171. bool destroy(bool RunDestructors = true) {
  1172. bool OK = cleanup(Info, RunDestructors, OldStackSize);
  1173. OldStackSize = -1U;
  1174. return OK;
  1175. }
  1176. ~ScopeRAII() {
  1177. if (OldStackSize != -1U)
  1178. destroy(false);
  1179. // Body moved to a static method to encourage the compiler to inline away
  1180. // instances of this class.
  1181. Info.CurrentCall->popTempVersion();
  1182. }
  1183. private:
  1184. static bool cleanup(EvalInfo &Info, bool RunDestructors,
  1185. unsigned OldStackSize) {
  1186. assert(OldStackSize <= Info.CleanupStack.size() &&
  1187. "running cleanups out of order?");
  1188. // Run all cleanups for a block scope, and non-lifetime-extended cleanups
  1189. // for a full-expression scope.
  1190. bool Success = true;
  1191. for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
  1192. if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
  1193. if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
  1194. Success = false;
  1195. break;
  1196. }
  1197. }
  1198. }
  1199. // Compact any retained cleanups.
  1200. auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
  1201. if (Kind != ScopeKind::Block)
  1202. NewEnd =
  1203. std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
  1204. return C.isDestroyedAtEndOf(Kind);
  1205. });
  1206. Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
  1207. return Success;
  1208. }
  1209. };
  1210. typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
  1211. typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
  1212. typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
  1213. }
  1214. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1215. CheckSubobjectKind CSK) {
  1216. if (Invalid)
  1217. return false;
  1218. if (isOnePastTheEnd()) {
  1219. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1220. << CSK;
  1221. setInvalid();
  1222. return false;
  1223. }
  1224. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1225. // must actually be at least one array element; even a VLA cannot have a
  1226. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1227. return true;
  1228. }
  1229. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1230. const Expr *E) {
  1231. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1232. // Do not set the designator as invalid: we can represent this situation,
  1233. // and correct handling of __builtin_object_size requires us to do so.
  1234. }
  1235. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1236. const Expr *E,
  1237. const APSInt &N) {
  1238. // If we're complaining, we must be able to statically determine the size of
  1239. // the most derived array.
  1240. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1241. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1242. << N << /*array*/ 0
  1243. << static_cast<unsigned>(getMostDerivedArraySize());
  1244. else
  1245. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1246. << N << /*non-array*/ 1;
  1247. setInvalid();
  1248. }
  1249. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1250. const FunctionDecl *Callee, const LValue *This,
  1251. CallRef Call)
  1252. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1253. Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1254. Info.CurrentCall = this;
  1255. ++Info.CallStackDepth;
  1256. }
  1257. CallStackFrame::~CallStackFrame() {
  1258. assert(Info.CurrentCall == this && "calls retired out of order");
  1259. --Info.CallStackDepth;
  1260. Info.CurrentCall = Caller;
  1261. }
  1262. static bool isRead(AccessKinds AK) {
  1263. return AK == AK_Read || AK == AK_ReadObjectRepresentation;
  1264. }
  1265. static bool isModification(AccessKinds AK) {
  1266. switch (AK) {
  1267. case AK_Read:
  1268. case AK_ReadObjectRepresentation:
  1269. case AK_MemberCall:
  1270. case AK_DynamicCast:
  1271. case AK_TypeId:
  1272. return false;
  1273. case AK_Assign:
  1274. case AK_Increment:
  1275. case AK_Decrement:
  1276. case AK_Construct:
  1277. case AK_Destroy:
  1278. return true;
  1279. }
  1280. llvm_unreachable("unknown access kind");
  1281. }
  1282. static bool isAnyAccess(AccessKinds AK) {
  1283. return isRead(AK) || isModification(AK);
  1284. }
  1285. /// Is this an access per the C++ definition?
  1286. static bool isFormalAccess(AccessKinds AK) {
  1287. return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
  1288. }
  1289. /// Is this kind of axcess valid on an indeterminate object value?
  1290. static bool isValidIndeterminateAccess(AccessKinds AK) {
  1291. switch (AK) {
  1292. case AK_Read:
  1293. case AK_Increment:
  1294. case AK_Decrement:
  1295. // These need the object's value.
  1296. return false;
  1297. case AK_ReadObjectRepresentation:
  1298. case AK_Assign:
  1299. case AK_Construct:
  1300. case AK_Destroy:
  1301. // Construction and destruction don't need the value.
  1302. return true;
  1303. case AK_MemberCall:
  1304. case AK_DynamicCast:
  1305. case AK_TypeId:
  1306. // These aren't really meaningful on scalars.
  1307. return true;
  1308. }
  1309. llvm_unreachable("unknown access kind");
  1310. }
  1311. namespace {
  1312. struct ComplexValue {
  1313. private:
  1314. bool IsInt;
  1315. public:
  1316. APSInt IntReal, IntImag;
  1317. APFloat FloatReal, FloatImag;
  1318. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1319. void makeComplexFloat() { IsInt = false; }
  1320. bool isComplexFloat() const { return !IsInt; }
  1321. APFloat &getComplexFloatReal() { return FloatReal; }
  1322. APFloat &getComplexFloatImag() { return FloatImag; }
  1323. void makeComplexInt() { IsInt = true; }
  1324. bool isComplexInt() const { return IsInt; }
  1325. APSInt &getComplexIntReal() { return IntReal; }
  1326. APSInt &getComplexIntImag() { return IntImag; }
  1327. void moveInto(APValue &v) const {
  1328. if (isComplexFloat())
  1329. v = APValue(FloatReal, FloatImag);
  1330. else
  1331. v = APValue(IntReal, IntImag);
  1332. }
  1333. void setFrom(const APValue &v) {
  1334. assert(v.isComplexFloat() || v.isComplexInt());
  1335. if (v.isComplexFloat()) {
  1336. makeComplexFloat();
  1337. FloatReal = v.getComplexFloatReal();
  1338. FloatImag = v.getComplexFloatImag();
  1339. } else {
  1340. makeComplexInt();
  1341. IntReal = v.getComplexIntReal();
  1342. IntImag = v.getComplexIntImag();
  1343. }
  1344. }
  1345. };
  1346. struct LValue {
  1347. APValue::LValueBase Base;
  1348. CharUnits Offset;
  1349. SubobjectDesignator Designator;
  1350. bool IsNullPtr : 1;
  1351. bool InvalidBase : 1;
  1352. const APValue::LValueBase getLValueBase() const { return Base; }
  1353. CharUnits &getLValueOffset() { return Offset; }
  1354. const CharUnits &getLValueOffset() const { return Offset; }
  1355. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1356. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1357. bool isNullPointer() const { return IsNullPtr;}
  1358. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1359. unsigned getLValueVersion() const { return Base.getVersion(); }
  1360. void moveInto(APValue &V) const {
  1361. if (Designator.Invalid)
  1362. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1363. else {
  1364. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1365. V = APValue(Base, Offset, Designator.Entries,
  1366. Designator.IsOnePastTheEnd, IsNullPtr);
  1367. }
  1368. }
  1369. void setFrom(ASTContext &Ctx, const APValue &V) {
  1370. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1371. Base = V.getLValueBase();
  1372. Offset = V.getLValueOffset();
  1373. InvalidBase = false;
  1374. Designator = SubobjectDesignator(Ctx, V);
  1375. IsNullPtr = V.isNullPointer();
  1376. }
  1377. void set(APValue::LValueBase B, bool BInvalid = false) {
  1378. #ifndef NDEBUG
  1379. // We only allow a few types of invalid bases. Enforce that here.
  1380. if (BInvalid) {
  1381. const auto *E = B.get<const Expr *>();
  1382. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1383. "Unexpected type of invalid base");
  1384. }
  1385. #endif
  1386. Base = B;
  1387. Offset = CharUnits::fromQuantity(0);
  1388. InvalidBase = BInvalid;
  1389. Designator = SubobjectDesignator(getType(B));
  1390. IsNullPtr = false;
  1391. }
  1392. void setNull(ASTContext &Ctx, QualType PointerTy) {
  1393. Base = (const ValueDecl *)nullptr;
  1394. Offset =
  1395. CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
  1396. InvalidBase = false;
  1397. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1398. IsNullPtr = true;
  1399. }
  1400. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1401. set(B, true);
  1402. }
  1403. std::string toString(ASTContext &Ctx, QualType T) const {
  1404. APValue Printable;
  1405. moveInto(Printable);
  1406. return Printable.getAsString(Ctx, T);
  1407. }
  1408. private:
  1409. // Check that this LValue is not based on a null pointer. If it is, produce
  1410. // a diagnostic and mark the designator as invalid.
  1411. template <typename GenDiagType>
  1412. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1413. if (Designator.Invalid)
  1414. return false;
  1415. if (IsNullPtr) {
  1416. GenDiag();
  1417. Designator.setInvalid();
  1418. return false;
  1419. }
  1420. return true;
  1421. }
  1422. public:
  1423. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1424. CheckSubobjectKind CSK) {
  1425. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1426. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1427. });
  1428. }
  1429. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1430. AccessKinds AK) {
  1431. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1432. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1433. });
  1434. }
  1435. // Check this LValue refers to an object. If not, set the designator to be
  1436. // invalid and emit a diagnostic.
  1437. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1438. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1439. Designator.checkSubobject(Info, E, CSK);
  1440. }
  1441. void addDecl(EvalInfo &Info, const Expr *E,
  1442. const Decl *D, bool Virtual = false) {
  1443. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1444. Designator.addDeclUnchecked(D, Virtual);
  1445. }
  1446. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1447. if (!Designator.Entries.empty()) {
  1448. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1449. Designator.setInvalid();
  1450. return;
  1451. }
  1452. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1453. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1454. Designator.FirstEntryIsAnUnsizedArray = true;
  1455. Designator.addUnsizedArrayUnchecked(ElemTy);
  1456. }
  1457. }
  1458. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1459. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1460. Designator.addArrayUnchecked(CAT);
  1461. }
  1462. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1463. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1464. Designator.addComplexUnchecked(EltTy, Imag);
  1465. }
  1466. void clearIsNullPointer() {
  1467. IsNullPtr = false;
  1468. }
  1469. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1470. const APSInt &Index, CharUnits ElementSize) {
  1471. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1472. // but we're not required to diagnose it and it's valid in C++.)
  1473. if (!Index)
  1474. return;
  1475. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1476. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1477. // offsets.
  1478. uint64_t Offset64 = Offset.getQuantity();
  1479. uint64_t ElemSize64 = ElementSize.getQuantity();
  1480. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1481. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1482. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1483. Designator.adjustIndex(Info, E, Index);
  1484. clearIsNullPointer();
  1485. }
  1486. void adjustOffset(CharUnits N) {
  1487. Offset += N;
  1488. if (N.getQuantity())
  1489. clearIsNullPointer();
  1490. }
  1491. };
  1492. struct MemberPtr {
  1493. MemberPtr() {}
  1494. explicit MemberPtr(const ValueDecl *Decl)
  1495. : DeclAndIsDerivedMember(Decl, false) {}
  1496. /// The member or (direct or indirect) field referred to by this member
  1497. /// pointer, or 0 if this is a null member pointer.
  1498. const ValueDecl *getDecl() const {
  1499. return DeclAndIsDerivedMember.getPointer();
  1500. }
  1501. /// Is this actually a member of some type derived from the relevant class?
  1502. bool isDerivedMember() const {
  1503. return DeclAndIsDerivedMember.getInt();
  1504. }
  1505. /// Get the class which the declaration actually lives in.
  1506. const CXXRecordDecl *getContainingRecord() const {
  1507. return cast<CXXRecordDecl>(
  1508. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1509. }
  1510. void moveInto(APValue &V) const {
  1511. V = APValue(getDecl(), isDerivedMember(), Path);
  1512. }
  1513. void setFrom(const APValue &V) {
  1514. assert(V.isMemberPointer());
  1515. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1516. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1517. Path.clear();
  1518. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1519. Path.insert(Path.end(), P.begin(), P.end());
  1520. }
  1521. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1522. /// whether the member is a member of some class derived from the class type
  1523. /// of the member pointer.
  1524. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1525. /// Path - The path of base/derived classes from the member declaration's
  1526. /// class (exclusive) to the class type of the member pointer (inclusive).
  1527. SmallVector<const CXXRecordDecl*, 4> Path;
  1528. /// Perform a cast towards the class of the Decl (either up or down the
  1529. /// hierarchy).
  1530. bool castBack(const CXXRecordDecl *Class) {
  1531. assert(!Path.empty());
  1532. const CXXRecordDecl *Expected;
  1533. if (Path.size() >= 2)
  1534. Expected = Path[Path.size() - 2];
  1535. else
  1536. Expected = getContainingRecord();
  1537. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1538. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1539. // if B does not contain the original member and is not a base or
  1540. // derived class of the class containing the original member, the result
  1541. // of the cast is undefined.
  1542. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1543. // (D::*). We consider that to be a language defect.
  1544. return false;
  1545. }
  1546. Path.pop_back();
  1547. return true;
  1548. }
  1549. /// Perform a base-to-derived member pointer cast.
  1550. bool castToDerived(const CXXRecordDecl *Derived) {
  1551. if (!getDecl())
  1552. return true;
  1553. if (!isDerivedMember()) {
  1554. Path.push_back(Derived);
  1555. return true;
  1556. }
  1557. if (!castBack(Derived))
  1558. return false;
  1559. if (Path.empty())
  1560. DeclAndIsDerivedMember.setInt(false);
  1561. return true;
  1562. }
  1563. /// Perform a derived-to-base member pointer cast.
  1564. bool castToBase(const CXXRecordDecl *Base) {
  1565. if (!getDecl())
  1566. return true;
  1567. if (Path.empty())
  1568. DeclAndIsDerivedMember.setInt(true);
  1569. if (isDerivedMember()) {
  1570. Path.push_back(Base);
  1571. return true;
  1572. }
  1573. return castBack(Base);
  1574. }
  1575. };
  1576. /// Compare two member pointers, which are assumed to be of the same type.
  1577. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1578. if (!LHS.getDecl() || !RHS.getDecl())
  1579. return !LHS.getDecl() && !RHS.getDecl();
  1580. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1581. return false;
  1582. return LHS.Path == RHS.Path;
  1583. }
  1584. }
  1585. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1586. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1587. const LValue &This, const Expr *E,
  1588. bool AllowNonLiteralTypes = false);
  1589. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1590. bool InvalidBaseOK = false);
  1591. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1592. bool InvalidBaseOK = false);
  1593. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1594. EvalInfo &Info);
  1595. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1596. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1597. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1598. EvalInfo &Info);
  1599. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1600. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1601. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1602. EvalInfo &Info);
  1603. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1604. static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
  1605. EvalInfo &Info);
  1606. /// Evaluate an integer or fixed point expression into an APResult.
  1607. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1608. EvalInfo &Info);
  1609. /// Evaluate only a fixed point expression into an APResult.
  1610. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1611. EvalInfo &Info);
  1612. //===----------------------------------------------------------------------===//
  1613. // Misc utilities
  1614. //===----------------------------------------------------------------------===//
  1615. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1616. /// preserving its value (by extending by up to one bit as needed).
  1617. static void negateAsSigned(APSInt &Int) {
  1618. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1619. Int = Int.extend(Int.getBitWidth() + 1);
  1620. Int.setIsSigned(true);
  1621. }
  1622. Int = -Int;
  1623. }
  1624. template<typename KeyT>
  1625. APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
  1626. ScopeKind Scope, LValue &LV) {
  1627. unsigned Version = getTempVersion();
  1628. APValue::LValueBase Base(Key, Index, Version);
  1629. LV.set(Base);
  1630. return createLocal(Base, Key, T, Scope);
  1631. }
  1632. /// Allocate storage for a parameter of a function call made in this frame.
  1633. APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
  1634. LValue &LV) {
  1635. assert(Args.CallIndex == Index && "creating parameter in wrong frame");
  1636. APValue::LValueBase Base(PVD, Index, Args.Version);
  1637. LV.set(Base);
  1638. // We always destroy parameters at the end of the call, even if we'd allow
  1639. // them to live to the end of the full-expression at runtime, in order to
  1640. // give portable results and match other compilers.
  1641. return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
  1642. }
  1643. APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
  1644. QualType T, ScopeKind Scope) {
  1645. assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
  1646. unsigned Version = Base.getVersion();
  1647. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1648. assert(Result.isAbsent() && "local created multiple times");
  1649. // If we're creating a local immediately in the operand of a speculative
  1650. // evaluation, don't register a cleanup to be run outside the speculative
  1651. // evaluation context, since we won't actually be able to initialize this
  1652. // object.
  1653. if (Index <= Info.SpeculativeEvaluationDepth) {
  1654. if (T.isDestructedType())
  1655. Info.noteSideEffect();
  1656. } else {
  1657. Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
  1658. }
  1659. return Result;
  1660. }
  1661. APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
  1662. if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
  1663. FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
  1664. return nullptr;
  1665. }
  1666. DynamicAllocLValue DA(NumHeapAllocs++);
  1667. LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
  1668. auto Result = HeapAllocs.emplace(std::piecewise_construct,
  1669. std::forward_as_tuple(DA), std::tuple<>());
  1670. assert(Result.second && "reused a heap alloc index?");
  1671. Result.first->second.AllocExpr = E;
  1672. return &Result.first->second.Value;
  1673. }
  1674. /// Produce a string describing the given constexpr call.
  1675. void CallStackFrame::describe(raw_ostream &Out) {
  1676. unsigned ArgIndex = 0;
  1677. bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
  1678. !isa<CXXConstructorDecl>(Callee) &&
  1679. cast<CXXMethodDecl>(Callee)->isInstance();
  1680. if (!IsMemberCall)
  1681. Out << *Callee << '(';
  1682. if (This && IsMemberCall) {
  1683. APValue Val;
  1684. This->moveInto(Val);
  1685. Val.printPretty(Out, Info.Ctx,
  1686. This->Designator.MostDerivedType);
  1687. // FIXME: Add parens around Val if needed.
  1688. Out << "->" << *Callee << '(';
  1689. IsMemberCall = false;
  1690. }
  1691. for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
  1692. E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1693. if (ArgIndex > (unsigned)IsMemberCall)
  1694. Out << ", ";
  1695. const ParmVarDecl *Param = *I;
  1696. APValue *V = Info.getParamSlot(Arguments, Param);
  1697. if (V)
  1698. V->printPretty(Out, Info.Ctx, Param->getType());
  1699. else
  1700. Out << "<...>";
  1701. if (ArgIndex == 0 && IsMemberCall)
  1702. Out << "->" << *Callee << '(';
  1703. }
  1704. Out << ')';
  1705. }
  1706. /// Evaluate an expression to see if it had side-effects, and discard its
  1707. /// result.
  1708. /// \return \c true if the caller should keep evaluating.
  1709. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1710. assert(!E->isValueDependent());
  1711. APValue Scratch;
  1712. if (!Evaluate(Scratch, Info, E))
  1713. // We don't need the value, but we might have skipped a side effect here.
  1714. return Info.noteSideEffect();
  1715. return true;
  1716. }
  1717. /// Should this call expression be treated as a constant?
  1718. static bool IsConstantCall(const CallExpr *E) {
  1719. unsigned Builtin = E->getBuiltinCallee();
  1720. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1721. Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
  1722. Builtin == Builtin::BI__builtin_function_start);
  1723. }
  1724. static bool IsGlobalLValue(APValue::LValueBase B) {
  1725. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1726. // constant expression of pointer type that evaluates to...
  1727. // ... a null pointer value, or a prvalue core constant expression of type
  1728. // std::nullptr_t.
  1729. if (!B) return true;
  1730. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1731. // ... the address of an object with static storage duration,
  1732. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1733. return VD->hasGlobalStorage();
  1734. if (isa<TemplateParamObjectDecl>(D))
  1735. return true;
  1736. // ... the address of a function,
  1737. // ... the address of a GUID [MS extension],
  1738. return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
  1739. }
  1740. if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
  1741. return true;
  1742. const Expr *E = B.get<const Expr*>();
  1743. switch (E->getStmtClass()) {
  1744. default:
  1745. return false;
  1746. case Expr::CompoundLiteralExprClass: {
  1747. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1748. return CLE->isFileScope() && CLE->isLValue();
  1749. }
  1750. case Expr::MaterializeTemporaryExprClass:
  1751. // A materialized temporary might have been lifetime-extended to static
  1752. // storage duration.
  1753. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1754. // A string literal has static storage duration.
  1755. case Expr::StringLiteralClass:
  1756. case Expr::PredefinedExprClass:
  1757. case Expr::ObjCStringLiteralClass:
  1758. case Expr::ObjCEncodeExprClass:
  1759. return true;
  1760. case Expr::ObjCBoxedExprClass:
  1761. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1762. case Expr::CallExprClass:
  1763. return IsConstantCall(cast<CallExpr>(E));
  1764. // For GCC compatibility, &&label has static storage duration.
  1765. case Expr::AddrLabelExprClass:
  1766. return true;
  1767. // A Block literal expression may be used as the initialization value for
  1768. // Block variables at global or local static scope.
  1769. case Expr::BlockExprClass:
  1770. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1771. case Expr::ImplicitValueInitExprClass:
  1772. // FIXME:
  1773. // We can never form an lvalue with an implicit value initialization as its
  1774. // base through expression evaluation, so these only appear in one case: the
  1775. // implicit variable declaration we invent when checking whether a constexpr
  1776. // constructor can produce a constant expression. We must assume that such
  1777. // an expression might be a global lvalue.
  1778. return true;
  1779. }
  1780. }
  1781. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1782. return LVal.Base.dyn_cast<const ValueDecl*>();
  1783. }
  1784. static bool IsLiteralLValue(const LValue &Value) {
  1785. if (Value.getLValueCallIndex())
  1786. return false;
  1787. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1788. return E && !isa<MaterializeTemporaryExpr>(E);
  1789. }
  1790. static bool IsWeakLValue(const LValue &Value) {
  1791. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1792. return Decl && Decl->isWeak();
  1793. }
  1794. static bool isZeroSized(const LValue &Value) {
  1795. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1796. if (Decl && isa<VarDecl>(Decl)) {
  1797. QualType Ty = Decl->getType();
  1798. if (Ty->isArrayType())
  1799. return Ty->isIncompleteType() ||
  1800. Decl->getASTContext().getTypeSize(Ty) == 0;
  1801. }
  1802. return false;
  1803. }
  1804. static bool HasSameBase(const LValue &A, const LValue &B) {
  1805. if (!A.getLValueBase())
  1806. return !B.getLValueBase();
  1807. if (!B.getLValueBase())
  1808. return false;
  1809. if (A.getLValueBase().getOpaqueValue() !=
  1810. B.getLValueBase().getOpaqueValue())
  1811. return false;
  1812. return A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1813. A.getLValueVersion() == B.getLValueVersion();
  1814. }
  1815. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1816. assert(Base && "no location for a null lvalue");
  1817. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1818. // For a parameter, find the corresponding call stack frame (if it still
  1819. // exists), and point at the parameter of the function definition we actually
  1820. // invoked.
  1821. if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
  1822. unsigned Idx = PVD->getFunctionScopeIndex();
  1823. for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
  1824. if (F->Arguments.CallIndex == Base.getCallIndex() &&
  1825. F->Arguments.Version == Base.getVersion() && F->Callee &&
  1826. Idx < F->Callee->getNumParams()) {
  1827. VD = F->Callee->getParamDecl(Idx);
  1828. break;
  1829. }
  1830. }
  1831. }
  1832. if (VD)
  1833. Info.Note(VD->getLocation(), diag::note_declared_at);
  1834. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1835. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1836. else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  1837. // FIXME: Produce a note for dangling pointers too.
  1838. if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
  1839. Info.Note((*Alloc)->AllocExpr->getExprLoc(),
  1840. diag::note_constexpr_dynamic_alloc_here);
  1841. }
  1842. // We have no information to show for a typeid(T) object.
  1843. }
  1844. enum class CheckEvaluationResultKind {
  1845. ConstantExpression,
  1846. FullyInitialized,
  1847. };
  1848. /// Materialized temporaries that we've already checked to determine if they're
  1849. /// initializsed by a constant expression.
  1850. using CheckedTemporaries =
  1851. llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
  1852. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  1853. EvalInfo &Info, SourceLocation DiagLoc,
  1854. QualType Type, const APValue &Value,
  1855. ConstantExprKind Kind,
  1856. SourceLocation SubobjectLoc,
  1857. CheckedTemporaries &CheckedTemps);
  1858. /// Check that this reference or pointer core constant expression is a valid
  1859. /// value for an address or reference constant expression. Return true if we
  1860. /// can fold this expression, whether or not it's a constant expression.
  1861. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1862. QualType Type, const LValue &LVal,
  1863. ConstantExprKind Kind,
  1864. CheckedTemporaries &CheckedTemps) {
  1865. bool IsReferenceType = Type->isReferenceType();
  1866. APValue::LValueBase Base = LVal.getLValueBase();
  1867. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1868. const Expr *BaseE = Base.dyn_cast<const Expr *>();
  1869. const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
  1870. // Additional restrictions apply in a template argument. We only enforce the
  1871. // C++20 restrictions here; additional syntactic and semantic restrictions
  1872. // are applied elsewhere.
  1873. if (isTemplateArgument(Kind)) {
  1874. int InvalidBaseKind = -1;
  1875. StringRef Ident;
  1876. if (Base.is<TypeInfoLValue>())
  1877. InvalidBaseKind = 0;
  1878. else if (isa_and_nonnull<StringLiteral>(BaseE))
  1879. InvalidBaseKind = 1;
  1880. else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
  1881. isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
  1882. InvalidBaseKind = 2;
  1883. else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
  1884. InvalidBaseKind = 3;
  1885. Ident = PE->getIdentKindName();
  1886. }
  1887. if (InvalidBaseKind != -1) {
  1888. Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
  1889. << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
  1890. << Ident;
  1891. return false;
  1892. }
  1893. }
  1894. if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
  1895. if (FD->isConsteval()) {
  1896. Info.FFDiag(Loc, diag::note_consteval_address_accessible)
  1897. << !Type->isAnyPointerType();
  1898. Info.Note(FD->getLocation(), diag::note_declared_at);
  1899. return false;
  1900. }
  1901. }
  1902. // Check that the object is a global. Note that the fake 'this' object we
  1903. // manufacture when checking potential constant expressions is conservatively
  1904. // assumed to be global here.
  1905. if (!IsGlobalLValue(Base)) {
  1906. if (Info.getLangOpts().CPlusPlus11) {
  1907. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1908. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1909. << IsReferenceType << !Designator.Entries.empty()
  1910. << !!VD << VD;
  1911. auto *VarD = dyn_cast_or_null<VarDecl>(VD);
  1912. if (VarD && VarD->isConstexpr()) {
  1913. // Non-static local constexpr variables have unintuitive semantics:
  1914. // constexpr int a = 1;
  1915. // constexpr const int *p = &a;
  1916. // ... is invalid because the address of 'a' is not constant. Suggest
  1917. // adding a 'static' in this case.
  1918. Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
  1919. << VarD
  1920. << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
  1921. } else {
  1922. NoteLValueLocation(Info, Base);
  1923. }
  1924. } else {
  1925. Info.FFDiag(Loc);
  1926. }
  1927. // Don't allow references to temporaries to escape.
  1928. return false;
  1929. }
  1930. assert((Info.checkingPotentialConstantExpression() ||
  1931. LVal.getLValueCallIndex() == 0) &&
  1932. "have call index for global lvalue");
  1933. if (Base.is<DynamicAllocLValue>()) {
  1934. Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
  1935. << IsReferenceType << !Designator.Entries.empty();
  1936. NoteLValueLocation(Info, Base);
  1937. return false;
  1938. }
  1939. if (BaseVD) {
  1940. if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
  1941. // Check if this is a thread-local variable.
  1942. if (Var->getTLSKind())
  1943. // FIXME: Diagnostic!
  1944. return false;
  1945. // A dllimport variable never acts like a constant, unless we're
  1946. // evaluating a value for use only in name mangling.
  1947. if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
  1948. // FIXME: Diagnostic!
  1949. return false;
  1950. // In CUDA/HIP device compilation, only device side variables have
  1951. // constant addresses.
  1952. if (Info.getCtx().getLangOpts().CUDA &&
  1953. Info.getCtx().getLangOpts().CUDAIsDevice &&
  1954. Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
  1955. if ((!Var->hasAttr<CUDADeviceAttr>() &&
  1956. !Var->hasAttr<CUDAConstantAttr>() &&
  1957. !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
  1958. !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
  1959. Var->hasAttr<HIPManagedAttr>())
  1960. return false;
  1961. }
  1962. }
  1963. if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
  1964. // __declspec(dllimport) must be handled very carefully:
  1965. // We must never initialize an expression with the thunk in C++.
  1966. // Doing otherwise would allow the same id-expression to yield
  1967. // different addresses for the same function in different translation
  1968. // units. However, this means that we must dynamically initialize the
  1969. // expression with the contents of the import address table at runtime.
  1970. //
  1971. // The C language has no notion of ODR; furthermore, it has no notion of
  1972. // dynamic initialization. This means that we are permitted to
  1973. // perform initialization with the address of the thunk.
  1974. if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
  1975. FD->hasAttr<DLLImportAttr>())
  1976. // FIXME: Diagnostic!
  1977. return false;
  1978. }
  1979. } else if (const auto *MTE =
  1980. dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
  1981. if (CheckedTemps.insert(MTE).second) {
  1982. QualType TempType = getType(Base);
  1983. if (TempType.isDestructedType()) {
  1984. Info.FFDiag(MTE->getExprLoc(),
  1985. diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
  1986. << TempType;
  1987. return false;
  1988. }
  1989. APValue *V = MTE->getOrCreateValue(false);
  1990. assert(V && "evasluation result refers to uninitialised temporary");
  1991. if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  1992. Info, MTE->getExprLoc(), TempType, *V,
  1993. Kind, SourceLocation(), CheckedTemps))
  1994. return false;
  1995. }
  1996. }
  1997. // Allow address constant expressions to be past-the-end pointers. This is
  1998. // an extension: the standard requires them to point to an object.
  1999. if (!IsReferenceType)
  2000. return true;
  2001. // A reference constant expression must refer to an object.
  2002. if (!Base) {
  2003. // FIXME: diagnostic
  2004. Info.CCEDiag(Loc);
  2005. return true;
  2006. }
  2007. // Does this refer one past the end of some object?
  2008. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  2009. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  2010. << !Designator.Entries.empty() << !!BaseVD << BaseVD;
  2011. NoteLValueLocation(Info, Base);
  2012. }
  2013. return true;
  2014. }
  2015. /// Member pointers are constant expressions unless they point to a
  2016. /// non-virtual dllimport member function.
  2017. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  2018. SourceLocation Loc,
  2019. QualType Type,
  2020. const APValue &Value,
  2021. ConstantExprKind Kind) {
  2022. const ValueDecl *Member = Value.getMemberPointerDecl();
  2023. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  2024. if (!FD)
  2025. return true;
  2026. if (FD->isConsteval()) {
  2027. Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
  2028. Info.Note(FD->getLocation(), diag::note_declared_at);
  2029. return false;
  2030. }
  2031. return isForManglingOnly(Kind) || FD->isVirtual() ||
  2032. !FD->hasAttr<DLLImportAttr>();
  2033. }
  2034. /// Check that this core constant expression is of literal type, and if not,
  2035. /// produce an appropriate diagnostic.
  2036. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  2037. const LValue *This = nullptr) {
  2038. if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
  2039. return true;
  2040. // C++1y: A constant initializer for an object o [...] may also invoke
  2041. // constexpr constructors for o and its subobjects even if those objects
  2042. // are of non-literal class types.
  2043. //
  2044. // C++11 missed this detail for aggregates, so classes like this:
  2045. // struct foo_t { union { int i; volatile int j; } u; };
  2046. // are not (obviously) initializable like so:
  2047. // __attribute__((__require_constant_initialization__))
  2048. // static const foo_t x = {{0}};
  2049. // because "i" is a subobject with non-literal initialization (due to the
  2050. // volatile member of the union). See:
  2051. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  2052. // Therefore, we use the C++1y behavior.
  2053. if (This && Info.EvaluatingDecl == This->getLValueBase())
  2054. return true;
  2055. // Prvalue constant expressions must be of literal types.
  2056. if (Info.getLangOpts().CPlusPlus11)
  2057. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  2058. << E->getType();
  2059. else
  2060. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2061. return false;
  2062. }
  2063. static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
  2064. EvalInfo &Info, SourceLocation DiagLoc,
  2065. QualType Type, const APValue &Value,
  2066. ConstantExprKind Kind,
  2067. SourceLocation SubobjectLoc,
  2068. CheckedTemporaries &CheckedTemps) {
  2069. if (!Value.hasValue()) {
  2070. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  2071. << true << Type;
  2072. if (SubobjectLoc.isValid())
  2073. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  2074. return false;
  2075. }
  2076. // We allow _Atomic(T) to be initialized from anything that T can be
  2077. // initialized from.
  2078. if (const AtomicType *AT = Type->getAs<AtomicType>())
  2079. Type = AT->getValueType();
  2080. // Core issue 1454: For a literal constant expression of array or class type,
  2081. // each subobject of its value shall have been initialized by a constant
  2082. // expression.
  2083. if (Value.isArray()) {
  2084. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  2085. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  2086. if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  2087. Value.getArrayInitializedElt(I), Kind,
  2088. SubobjectLoc, CheckedTemps))
  2089. return false;
  2090. }
  2091. if (!Value.hasArrayFiller())
  2092. return true;
  2093. return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
  2094. Value.getArrayFiller(), Kind, SubobjectLoc,
  2095. CheckedTemps);
  2096. }
  2097. if (Value.isUnion() && Value.getUnionField()) {
  2098. return CheckEvaluationResult(
  2099. CERK, Info, DiagLoc, Value.getUnionField()->getType(),
  2100. Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
  2101. CheckedTemps);
  2102. }
  2103. if (Value.isStruct()) {
  2104. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  2105. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  2106. unsigned BaseIndex = 0;
  2107. for (const CXXBaseSpecifier &BS : CD->bases()) {
  2108. if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
  2109. Value.getStructBase(BaseIndex), Kind,
  2110. BS.getBeginLoc(), CheckedTemps))
  2111. return false;
  2112. ++BaseIndex;
  2113. }
  2114. }
  2115. for (const auto *I : RD->fields()) {
  2116. if (I->isUnnamedBitfield())
  2117. continue;
  2118. if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
  2119. Value.getStructField(I->getFieldIndex()),
  2120. Kind, I->getLocation(), CheckedTemps))
  2121. return false;
  2122. }
  2123. }
  2124. if (Value.isLValue() &&
  2125. CERK == CheckEvaluationResultKind::ConstantExpression) {
  2126. LValue LVal;
  2127. LVal.setFrom(Info.Ctx, Value);
  2128. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
  2129. CheckedTemps);
  2130. }
  2131. if (Value.isMemberPointer() &&
  2132. CERK == CheckEvaluationResultKind::ConstantExpression)
  2133. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
  2134. // Everything else is fine.
  2135. return true;
  2136. }
  2137. /// Check that this core constant expression value is a valid value for a
  2138. /// constant expression. If not, report an appropriate diagnostic. Does not
  2139. /// check that the expression is of literal type.
  2140. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  2141. QualType Type, const APValue &Value,
  2142. ConstantExprKind Kind) {
  2143. // Nothing to check for a constant expression of type 'cv void'.
  2144. if (Type->isVoidType())
  2145. return true;
  2146. CheckedTemporaries CheckedTemps;
  2147. return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
  2148. Info, DiagLoc, Type, Value, Kind,
  2149. SourceLocation(), CheckedTemps);
  2150. }
  2151. /// Check that this evaluated value is fully-initialized and can be loaded by
  2152. /// an lvalue-to-rvalue conversion.
  2153. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
  2154. QualType Type, const APValue &Value) {
  2155. CheckedTemporaries CheckedTemps;
  2156. return CheckEvaluationResult(
  2157. CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
  2158. ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
  2159. }
  2160. /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
  2161. /// "the allocated storage is deallocated within the evaluation".
  2162. static bool CheckMemoryLeaks(EvalInfo &Info) {
  2163. if (!Info.HeapAllocs.empty()) {
  2164. // We can still fold to a constant despite a compile-time memory leak,
  2165. // so long as the heap allocation isn't referenced in the result (we check
  2166. // that in CheckConstantExpression).
  2167. Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
  2168. diag::note_constexpr_memory_leak)
  2169. << unsigned(Info.HeapAllocs.size() - 1);
  2170. }
  2171. return true;
  2172. }
  2173. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  2174. // A null base expression indicates a null pointer. These are always
  2175. // evaluatable, and they are false unless the offset is zero.
  2176. if (!Value.getLValueBase()) {
  2177. Result = !Value.getLValueOffset().isZero();
  2178. return true;
  2179. }
  2180. // We have a non-null base. These are generally known to be true, but if it's
  2181. // a weak declaration it can be null at runtime.
  2182. Result = true;
  2183. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  2184. return !Decl || !Decl->isWeak();
  2185. }
  2186. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  2187. switch (Val.getKind()) {
  2188. case APValue::None:
  2189. case APValue::Indeterminate:
  2190. return false;
  2191. case APValue::Int:
  2192. Result = Val.getInt().getBoolValue();
  2193. return true;
  2194. case APValue::FixedPoint:
  2195. Result = Val.getFixedPoint().getBoolValue();
  2196. return true;
  2197. case APValue::Float:
  2198. Result = !Val.getFloat().isZero();
  2199. return true;
  2200. case APValue::ComplexInt:
  2201. Result = Val.getComplexIntReal().getBoolValue() ||
  2202. Val.getComplexIntImag().getBoolValue();
  2203. return true;
  2204. case APValue::ComplexFloat:
  2205. Result = !Val.getComplexFloatReal().isZero() ||
  2206. !Val.getComplexFloatImag().isZero();
  2207. return true;
  2208. case APValue::LValue:
  2209. return EvalPointerValueAsBool(Val, Result);
  2210. case APValue::MemberPointer:
  2211. Result = Val.getMemberPointerDecl();
  2212. return true;
  2213. case APValue::Vector:
  2214. case APValue::Array:
  2215. case APValue::Struct:
  2216. case APValue::Union:
  2217. case APValue::AddrLabelDiff:
  2218. return false;
  2219. }
  2220. llvm_unreachable("unknown APValue kind");
  2221. }
  2222. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  2223. EvalInfo &Info) {
  2224. assert(!E->isValueDependent());
  2225. assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
  2226. APValue Val;
  2227. if (!Evaluate(Val, Info, E))
  2228. return false;
  2229. return HandleConversionToBool(Val, Result);
  2230. }
  2231. template<typename T>
  2232. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  2233. const T &SrcValue, QualType DestType) {
  2234. Info.CCEDiag(E, diag::note_constexpr_overflow)
  2235. << SrcValue << DestType;
  2236. return Info.noteUndefinedBehavior();
  2237. }
  2238. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  2239. QualType SrcType, const APFloat &Value,
  2240. QualType DestType, APSInt &Result) {
  2241. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2242. // Determine whether we are converting to unsigned or signed.
  2243. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  2244. Result = APSInt(DestWidth, !DestSigned);
  2245. bool ignored;
  2246. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  2247. & APFloat::opInvalidOp)
  2248. return HandleOverflow(Info, E, Value, DestType);
  2249. return true;
  2250. }
  2251. /// Get rounding mode used for evaluation of the specified expression.
  2252. /// \param[out] DynamicRM Is set to true is the requested rounding mode is
  2253. /// dynamic.
  2254. /// If rounding mode is unknown at compile time, still try to evaluate the
  2255. /// expression. If the result is exact, it does not depend on rounding mode.
  2256. /// So return "tonearest" mode instead of "dynamic".
  2257. static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
  2258. bool &DynamicRM) {
  2259. llvm::RoundingMode RM =
  2260. E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
  2261. DynamicRM = (RM == llvm::RoundingMode::Dynamic);
  2262. if (DynamicRM)
  2263. RM = llvm::RoundingMode::NearestTiesToEven;
  2264. return RM;
  2265. }
  2266. /// Check if the given evaluation result is allowed for constant evaluation.
  2267. static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
  2268. APFloat::opStatus St) {
  2269. // In a constant context, assume that any dynamic rounding mode or FP
  2270. // exception state matches the default floating-point environment.
  2271. if (Info.InConstantContext)
  2272. return true;
  2273. FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
  2274. if ((St & APFloat::opInexact) &&
  2275. FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
  2276. // Inexact result means that it depends on rounding mode. If the requested
  2277. // mode is dynamic, the evaluation cannot be made in compile time.
  2278. Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
  2279. return false;
  2280. }
  2281. if ((St != APFloat::opOK) &&
  2282. (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
  2283. FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
  2284. FPO.getAllowFEnvAccess())) {
  2285. Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
  2286. return false;
  2287. }
  2288. if ((St & APFloat::opStatus::opInvalidOp) &&
  2289. FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
  2290. // There is no usefully definable result.
  2291. Info.FFDiag(E);
  2292. return false;
  2293. }
  2294. // FIXME: if:
  2295. // - evaluation triggered other FP exception, and
  2296. // - exception mode is not "ignore", and
  2297. // - the expression being evaluated is not a part of global variable
  2298. // initializer,
  2299. // the evaluation probably need to be rejected.
  2300. return true;
  2301. }
  2302. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  2303. QualType SrcType, QualType DestType,
  2304. APFloat &Result) {
  2305. assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
  2306. bool DynamicRM;
  2307. llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
  2308. APFloat::opStatus St;
  2309. APFloat Value = Result;
  2310. bool ignored;
  2311. St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
  2312. return checkFloatingPointResult(Info, E, St);
  2313. }
  2314. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  2315. QualType DestType, QualType SrcType,
  2316. const APSInt &Value) {
  2317. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  2318. // Figure out if this is a truncate, extend or noop cast.
  2319. // If the input is signed, do a sign extend, noop, or truncate.
  2320. APSInt Result = Value.extOrTrunc(DestWidth);
  2321. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  2322. if (DestType->isBooleanType())
  2323. Result = Value.getBoolValue();
  2324. return Result;
  2325. }
  2326. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  2327. const FPOptions FPO,
  2328. QualType SrcType, const APSInt &Value,
  2329. QualType DestType, APFloat &Result) {
  2330. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  2331. APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
  2332. APFloat::rmNearestTiesToEven);
  2333. if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
  2334. FPO.isFPConstrained()) {
  2335. Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
  2336. return false;
  2337. }
  2338. return true;
  2339. }
  2340. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  2341. APValue &Value, const FieldDecl *FD) {
  2342. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  2343. if (!Value.isInt()) {
  2344. // Trying to store a pointer-cast-to-integer into a bitfield.
  2345. // FIXME: In this case, we should provide the diagnostic for casting
  2346. // a pointer to an integer.
  2347. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  2348. Info.FFDiag(E);
  2349. return false;
  2350. }
  2351. APSInt &Int = Value.getInt();
  2352. unsigned OldBitWidth = Int.getBitWidth();
  2353. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  2354. if (NewBitWidth < OldBitWidth)
  2355. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2356. return true;
  2357. }
  2358. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2359. llvm::APInt &Res) {
  2360. APValue SVal;
  2361. if (!Evaluate(SVal, Info, E))
  2362. return false;
  2363. if (SVal.isInt()) {
  2364. Res = SVal.getInt();
  2365. return true;
  2366. }
  2367. if (SVal.isFloat()) {
  2368. Res = SVal.getFloat().bitcastToAPInt();
  2369. return true;
  2370. }
  2371. if (SVal.isVector()) {
  2372. QualType VecTy = E->getType();
  2373. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2374. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2375. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2376. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2377. Res = llvm::APInt::getZero(VecSize);
  2378. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2379. APValue &Elt = SVal.getVectorElt(i);
  2380. llvm::APInt EltAsInt;
  2381. if (Elt.isInt()) {
  2382. EltAsInt = Elt.getInt();
  2383. } else if (Elt.isFloat()) {
  2384. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2385. } else {
  2386. // Don't try to handle vectors of anything other than int or float
  2387. // (not sure if it's possible to hit this case).
  2388. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2389. return false;
  2390. }
  2391. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2392. if (BigEndian)
  2393. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2394. else
  2395. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2396. }
  2397. return true;
  2398. }
  2399. // Give up if the input isn't an int, float, or vector. For example, we
  2400. // reject "(v4i16)(intptr_t)&a".
  2401. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2402. return false;
  2403. }
  2404. /// Perform the given integer operation, which is known to need at most BitWidth
  2405. /// bits, and check for overflow in the original type (if that type was not an
  2406. /// unsigned type).
  2407. template<typename Operation>
  2408. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2409. const APSInt &LHS, const APSInt &RHS,
  2410. unsigned BitWidth, Operation Op,
  2411. APSInt &Result) {
  2412. if (LHS.isUnsigned()) {
  2413. Result = Op(LHS, RHS);
  2414. return true;
  2415. }
  2416. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2417. Result = Value.trunc(LHS.getBitWidth());
  2418. if (Result.extend(BitWidth) != Value) {
  2419. if (Info.checkingForUndefinedBehavior())
  2420. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2421. diag::warn_integer_constant_overflow)
  2422. << toString(Result, 10) << E->getType();
  2423. return HandleOverflow(Info, E, Value, E->getType());
  2424. }
  2425. return true;
  2426. }
  2427. /// Perform the given binary integer operation.
  2428. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2429. BinaryOperatorKind Opcode, APSInt RHS,
  2430. APSInt &Result) {
  2431. switch (Opcode) {
  2432. default:
  2433. Info.FFDiag(E);
  2434. return false;
  2435. case BO_Mul:
  2436. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2437. std::multiplies<APSInt>(), Result);
  2438. case BO_Add:
  2439. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2440. std::plus<APSInt>(), Result);
  2441. case BO_Sub:
  2442. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2443. std::minus<APSInt>(), Result);
  2444. case BO_And: Result = LHS & RHS; return true;
  2445. case BO_Xor: Result = LHS ^ RHS; return true;
  2446. case BO_Or: Result = LHS | RHS; return true;
  2447. case BO_Div:
  2448. case BO_Rem:
  2449. if (RHS == 0) {
  2450. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2451. return false;
  2452. }
  2453. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2454. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2455. // this operation and gives the two's complement result.
  2456. if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
  2457. LHS.isMinSignedValue())
  2458. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2459. E->getType());
  2460. return true;
  2461. case BO_Shl: {
  2462. if (Info.getLangOpts().OpenCL)
  2463. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2464. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2465. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2466. RHS.isUnsigned());
  2467. else if (RHS.isSigned() && RHS.isNegative()) {
  2468. // During constant-folding, a negative shift is an opposite shift. Such
  2469. // a shift is not a constant expression.
  2470. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2471. RHS = -RHS;
  2472. goto shift_right;
  2473. }
  2474. shift_left:
  2475. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2476. // the shifted type.
  2477. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2478. if (SA != RHS) {
  2479. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2480. << RHS << E->getType() << LHS.getBitWidth();
  2481. } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
  2482. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2483. // operand, and must not overflow the corresponding unsigned type.
  2484. // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
  2485. // E1 x 2^E2 module 2^N.
  2486. if (LHS.isNegative())
  2487. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2488. else if (LHS.countLeadingZeros() < SA)
  2489. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2490. }
  2491. Result = LHS << SA;
  2492. return true;
  2493. }
  2494. case BO_Shr: {
  2495. if (Info.getLangOpts().OpenCL)
  2496. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2497. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2498. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2499. RHS.isUnsigned());
  2500. else if (RHS.isSigned() && RHS.isNegative()) {
  2501. // During constant-folding, a negative shift is an opposite shift. Such a
  2502. // shift is not a constant expression.
  2503. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2504. RHS = -RHS;
  2505. goto shift_left;
  2506. }
  2507. shift_right:
  2508. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2509. // shifted type.
  2510. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2511. if (SA != RHS)
  2512. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2513. << RHS << E->getType() << LHS.getBitWidth();
  2514. Result = LHS >> SA;
  2515. return true;
  2516. }
  2517. case BO_LT: Result = LHS < RHS; return true;
  2518. case BO_GT: Result = LHS > RHS; return true;
  2519. case BO_LE: Result = LHS <= RHS; return true;
  2520. case BO_GE: Result = LHS >= RHS; return true;
  2521. case BO_EQ: Result = LHS == RHS; return true;
  2522. case BO_NE: Result = LHS != RHS; return true;
  2523. case BO_Cmp:
  2524. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2525. }
  2526. }
  2527. /// Perform the given binary floating-point operation, in-place, on LHS.
  2528. static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
  2529. APFloat &LHS, BinaryOperatorKind Opcode,
  2530. const APFloat &RHS) {
  2531. bool DynamicRM;
  2532. llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
  2533. APFloat::opStatus St;
  2534. switch (Opcode) {
  2535. default:
  2536. Info.FFDiag(E);
  2537. return false;
  2538. case BO_Mul:
  2539. St = LHS.multiply(RHS, RM);
  2540. break;
  2541. case BO_Add:
  2542. St = LHS.add(RHS, RM);
  2543. break;
  2544. case BO_Sub:
  2545. St = LHS.subtract(RHS, RM);
  2546. break;
  2547. case BO_Div:
  2548. // [expr.mul]p4:
  2549. // If the second operand of / or % is zero the behavior is undefined.
  2550. if (RHS.isZero())
  2551. Info.CCEDiag(E, diag::note_expr_divide_by_zero);
  2552. St = LHS.divide(RHS, RM);
  2553. break;
  2554. }
  2555. // [expr.pre]p4:
  2556. // If during the evaluation of an expression, the result is not
  2557. // mathematically defined [...], the behavior is undefined.
  2558. // FIXME: C++ rules require us to not conform to IEEE 754 here.
  2559. if (LHS.isNaN()) {
  2560. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2561. return Info.noteUndefinedBehavior();
  2562. }
  2563. return checkFloatingPointResult(Info, E, St);
  2564. }
  2565. static bool handleLogicalOpForVector(const APInt &LHSValue,
  2566. BinaryOperatorKind Opcode,
  2567. const APInt &RHSValue, APInt &Result) {
  2568. bool LHS = (LHSValue != 0);
  2569. bool RHS = (RHSValue != 0);
  2570. if (Opcode == BO_LAnd)
  2571. Result = LHS && RHS;
  2572. else
  2573. Result = LHS || RHS;
  2574. return true;
  2575. }
  2576. static bool handleLogicalOpForVector(const APFloat &LHSValue,
  2577. BinaryOperatorKind Opcode,
  2578. const APFloat &RHSValue, APInt &Result) {
  2579. bool LHS = !LHSValue.isZero();
  2580. bool RHS = !RHSValue.isZero();
  2581. if (Opcode == BO_LAnd)
  2582. Result = LHS && RHS;
  2583. else
  2584. Result = LHS || RHS;
  2585. return true;
  2586. }
  2587. static bool handleLogicalOpForVector(const APValue &LHSValue,
  2588. BinaryOperatorKind Opcode,
  2589. const APValue &RHSValue, APInt &Result) {
  2590. // The result is always an int type, however operands match the first.
  2591. if (LHSValue.getKind() == APValue::Int)
  2592. return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
  2593. RHSValue.getInt(), Result);
  2594. assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
  2595. return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
  2596. RHSValue.getFloat(), Result);
  2597. }
  2598. template <typename APTy>
  2599. static bool
  2600. handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
  2601. const APTy &RHSValue, APInt &Result) {
  2602. switch (Opcode) {
  2603. default:
  2604. llvm_unreachable("unsupported binary operator");
  2605. case BO_EQ:
  2606. Result = (LHSValue == RHSValue);
  2607. break;
  2608. case BO_NE:
  2609. Result = (LHSValue != RHSValue);
  2610. break;
  2611. case BO_LT:
  2612. Result = (LHSValue < RHSValue);
  2613. break;
  2614. case BO_GT:
  2615. Result = (LHSValue > RHSValue);
  2616. break;
  2617. case BO_LE:
  2618. Result = (LHSValue <= RHSValue);
  2619. break;
  2620. case BO_GE:
  2621. Result = (LHSValue >= RHSValue);
  2622. break;
  2623. }
  2624. // The boolean operations on these vector types use an instruction that
  2625. // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
  2626. // to -1 to make sure that we produce the correct value.
  2627. Result.negate();
  2628. return true;
  2629. }
  2630. static bool handleCompareOpForVector(const APValue &LHSValue,
  2631. BinaryOperatorKind Opcode,
  2632. const APValue &RHSValue, APInt &Result) {
  2633. // The result is always an int type, however operands match the first.
  2634. if (LHSValue.getKind() == APValue::Int)
  2635. return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
  2636. RHSValue.getInt(), Result);
  2637. assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
  2638. return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
  2639. RHSValue.getFloat(), Result);
  2640. }
  2641. // Perform binary operations for vector types, in place on the LHS.
  2642. static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
  2643. BinaryOperatorKind Opcode,
  2644. APValue &LHSValue,
  2645. const APValue &RHSValue) {
  2646. assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
  2647. "Operation not supported on vector types");
  2648. const auto *VT = E->getType()->castAs<VectorType>();
  2649. unsigned NumElements = VT->getNumElements();
  2650. QualType EltTy = VT->getElementType();
  2651. // In the cases (typically C as I've observed) where we aren't evaluating
  2652. // constexpr but are checking for cases where the LHS isn't yet evaluatable,
  2653. // just give up.
  2654. if (!LHSValue.isVector()) {
  2655. assert(LHSValue.isLValue() &&
  2656. "A vector result that isn't a vector OR uncalculated LValue");
  2657. Info.FFDiag(E);
  2658. return false;
  2659. }
  2660. assert(LHSValue.getVectorLength() == NumElements &&
  2661. RHSValue.getVectorLength() == NumElements && "Different vector sizes");
  2662. SmallVector<APValue, 4> ResultElements;
  2663. for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
  2664. APValue LHSElt = LHSValue.getVectorElt(EltNum);
  2665. APValue RHSElt = RHSValue.getVectorElt(EltNum);
  2666. if (EltTy->isIntegerType()) {
  2667. APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
  2668. EltTy->isUnsignedIntegerType()};
  2669. bool Success = true;
  2670. if (BinaryOperator::isLogicalOp(Opcode))
  2671. Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
  2672. else if (BinaryOperator::isComparisonOp(Opcode))
  2673. Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
  2674. else
  2675. Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
  2676. RHSElt.getInt(), EltResult);
  2677. if (!Success) {
  2678. Info.FFDiag(E);
  2679. return false;
  2680. }
  2681. ResultElements.emplace_back(EltResult);
  2682. } else if (EltTy->isFloatingType()) {
  2683. assert(LHSElt.getKind() == APValue::Float &&
  2684. RHSElt.getKind() == APValue::Float &&
  2685. "Mismatched LHS/RHS/Result Type");
  2686. APFloat LHSFloat = LHSElt.getFloat();
  2687. if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
  2688. RHSElt.getFloat())) {
  2689. Info.FFDiag(E);
  2690. return false;
  2691. }
  2692. ResultElements.emplace_back(LHSFloat);
  2693. }
  2694. }
  2695. LHSValue = APValue(ResultElements.data(), ResultElements.size());
  2696. return true;
  2697. }
  2698. /// Cast an lvalue referring to a base subobject to a derived class, by
  2699. /// truncating the lvalue's path to the given length.
  2700. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2701. const RecordDecl *TruncatedType,
  2702. unsigned TruncatedElements) {
  2703. SubobjectDesignator &D = Result.Designator;
  2704. // Check we actually point to a derived class object.
  2705. if (TruncatedElements == D.Entries.size())
  2706. return true;
  2707. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2708. "not casting to a derived class");
  2709. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2710. return false;
  2711. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2712. const RecordDecl *RD = TruncatedType;
  2713. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2714. if (RD->isInvalidDecl()) return false;
  2715. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2716. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2717. if (isVirtualBaseClass(D.Entries[I]))
  2718. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2719. else
  2720. Result.Offset -= Layout.getBaseClassOffset(Base);
  2721. RD = Base;
  2722. }
  2723. D.Entries.resize(TruncatedElements);
  2724. return true;
  2725. }
  2726. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2727. const CXXRecordDecl *Derived,
  2728. const CXXRecordDecl *Base,
  2729. const ASTRecordLayout *RL = nullptr) {
  2730. if (!RL) {
  2731. if (Derived->isInvalidDecl()) return false;
  2732. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2733. }
  2734. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2735. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2736. return true;
  2737. }
  2738. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2739. const CXXRecordDecl *DerivedDecl,
  2740. const CXXBaseSpecifier *Base) {
  2741. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2742. if (!Base->isVirtual())
  2743. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2744. SubobjectDesignator &D = Obj.Designator;
  2745. if (D.Invalid)
  2746. return false;
  2747. // Extract most-derived object and corresponding type.
  2748. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2749. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2750. return false;
  2751. // Find the virtual base class.
  2752. if (DerivedDecl->isInvalidDecl()) return false;
  2753. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2754. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2755. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2756. return true;
  2757. }
  2758. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2759. QualType Type, LValue &Result) {
  2760. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2761. PathE = E->path_end();
  2762. PathI != PathE; ++PathI) {
  2763. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2764. *PathI))
  2765. return false;
  2766. Type = (*PathI)->getType();
  2767. }
  2768. return true;
  2769. }
  2770. /// Cast an lvalue referring to a derived class to a known base subobject.
  2771. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2772. const CXXRecordDecl *DerivedRD,
  2773. const CXXRecordDecl *BaseRD) {
  2774. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2775. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2776. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2777. llvm_unreachable("Class must be derived from the passed in base class!");
  2778. for (CXXBasePathElement &Elem : Paths.front())
  2779. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2780. return false;
  2781. return true;
  2782. }
  2783. /// Update LVal to refer to the given field, which must be a member of the type
  2784. /// currently described by LVal.
  2785. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2786. const FieldDecl *FD,
  2787. const ASTRecordLayout *RL = nullptr) {
  2788. if (!RL) {
  2789. if (FD->getParent()->isInvalidDecl()) return false;
  2790. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2791. }
  2792. unsigned I = FD->getFieldIndex();
  2793. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2794. LVal.addDecl(Info, E, FD);
  2795. return true;
  2796. }
  2797. /// Update LVal to refer to the given indirect field.
  2798. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2799. LValue &LVal,
  2800. const IndirectFieldDecl *IFD) {
  2801. for (const auto *C : IFD->chain())
  2802. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2803. return false;
  2804. return true;
  2805. }
  2806. /// Get the size of the given type in char units.
  2807. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2808. QualType Type, CharUnits &Size) {
  2809. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2810. // extension.
  2811. if (Type->isVoidType() || Type->isFunctionType()) {
  2812. Size = CharUnits::One();
  2813. return true;
  2814. }
  2815. if (Type->isDependentType()) {
  2816. Info.FFDiag(Loc);
  2817. return false;
  2818. }
  2819. if (!Type->isConstantSizeType()) {
  2820. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2821. // FIXME: Better diagnostic.
  2822. Info.FFDiag(Loc);
  2823. return false;
  2824. }
  2825. Size = Info.Ctx.getTypeSizeInChars(Type);
  2826. return true;
  2827. }
  2828. /// Update a pointer value to model pointer arithmetic.
  2829. /// \param Info - Information about the ongoing evaluation.
  2830. /// \param E - The expression being evaluated, for diagnostic purposes.
  2831. /// \param LVal - The pointer value to be updated.
  2832. /// \param EltTy - The pointee type represented by LVal.
  2833. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2834. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2835. LValue &LVal, QualType EltTy,
  2836. APSInt Adjustment) {
  2837. CharUnits SizeOfPointee;
  2838. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2839. return false;
  2840. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2841. return true;
  2842. }
  2843. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2844. LValue &LVal, QualType EltTy,
  2845. int64_t Adjustment) {
  2846. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2847. APSInt::get(Adjustment));
  2848. }
  2849. /// Update an lvalue to refer to a component of a complex number.
  2850. /// \param Info - Information about the ongoing evaluation.
  2851. /// \param LVal - The lvalue to be updated.
  2852. /// \param EltTy - The complex number's component type.
  2853. /// \param Imag - False for the real component, true for the imaginary.
  2854. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2855. LValue &LVal, QualType EltTy,
  2856. bool Imag) {
  2857. if (Imag) {
  2858. CharUnits SizeOfComponent;
  2859. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2860. return false;
  2861. LVal.Offset += SizeOfComponent;
  2862. }
  2863. LVal.addComplex(Info, E, EltTy, Imag);
  2864. return true;
  2865. }
  2866. /// Try to evaluate the initializer for a variable declaration.
  2867. ///
  2868. /// \param Info Information about the ongoing evaluation.
  2869. /// \param E An expression to be used when printing diagnostics.
  2870. /// \param VD The variable whose initializer should be obtained.
  2871. /// \param Version The version of the variable within the frame.
  2872. /// \param Frame The frame in which the variable was created. Must be null
  2873. /// if this variable is not local to the evaluation.
  2874. /// \param Result Filled in with a pointer to the value of the variable.
  2875. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2876. const VarDecl *VD, CallStackFrame *Frame,
  2877. unsigned Version, APValue *&Result) {
  2878. APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
  2879. // If this is a local variable, dig out its value.
  2880. if (Frame) {
  2881. Result = Frame->getTemporary(VD, Version);
  2882. if (Result)
  2883. return true;
  2884. if (!isa<ParmVarDecl>(VD)) {
  2885. // Assume variables referenced within a lambda's call operator that were
  2886. // not declared within the call operator are captures and during checking
  2887. // of a potential constant expression, assume they are unknown constant
  2888. // expressions.
  2889. assert(isLambdaCallOperator(Frame->Callee) &&
  2890. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2891. "missing value for local variable");
  2892. if (Info.checkingPotentialConstantExpression())
  2893. return false;
  2894. // FIXME: This diagnostic is bogus; we do support captures. Is this code
  2895. // still reachable at all?
  2896. Info.FFDiag(E->getBeginLoc(),
  2897. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2898. << "captures not currently allowed";
  2899. return false;
  2900. }
  2901. }
  2902. // If we're currently evaluating the initializer of this declaration, use that
  2903. // in-flight value.
  2904. if (Info.EvaluatingDecl == Base) {
  2905. Result = Info.EvaluatingDeclValue;
  2906. return true;
  2907. }
  2908. if (isa<ParmVarDecl>(VD)) {
  2909. // Assume parameters of a potential constant expression are usable in
  2910. // constant expressions.
  2911. if (!Info.checkingPotentialConstantExpression() ||
  2912. !Info.CurrentCall->Callee ||
  2913. !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  2914. if (Info.getLangOpts().CPlusPlus11) {
  2915. Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
  2916. << VD;
  2917. NoteLValueLocation(Info, Base);
  2918. } else {
  2919. Info.FFDiag(E);
  2920. }
  2921. }
  2922. return false;
  2923. }
  2924. // Dig out the initializer, and use the declaration which it's attached to.
  2925. // FIXME: We should eventually check whether the variable has a reachable
  2926. // initializing declaration.
  2927. const Expr *Init = VD->getAnyInitializer(VD);
  2928. if (!Init) {
  2929. // Don't diagnose during potential constant expression checking; an
  2930. // initializer might be added later.
  2931. if (!Info.checkingPotentialConstantExpression()) {
  2932. Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
  2933. << VD;
  2934. NoteLValueLocation(Info, Base);
  2935. }
  2936. return false;
  2937. }
  2938. if (Init->isValueDependent()) {
  2939. // The DeclRefExpr is not value-dependent, but the variable it refers to
  2940. // has a value-dependent initializer. This should only happen in
  2941. // constant-folding cases, where the variable is not actually of a suitable
  2942. // type for use in a constant expression (otherwise the DeclRefExpr would
  2943. // have been value-dependent too), so diagnose that.
  2944. assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
  2945. if (!Info.checkingPotentialConstantExpression()) {
  2946. Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
  2947. ? diag::note_constexpr_ltor_non_constexpr
  2948. : diag::note_constexpr_ltor_non_integral, 1)
  2949. << VD << VD->getType();
  2950. NoteLValueLocation(Info, Base);
  2951. }
  2952. return false;
  2953. }
  2954. // Check that we can fold the initializer. In C++, we will have already done
  2955. // this in the cases where it matters for conformance.
  2956. if (!VD->evaluateValue()) {
  2957. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
  2958. NoteLValueLocation(Info, Base);
  2959. return false;
  2960. }
  2961. // Check that the variable is actually usable in constant expressions. For a
  2962. // const integral variable or a reference, we might have a non-constant
  2963. // initializer that we can nonetheless evaluate the initializer for. Such
  2964. // variables are not usable in constant expressions. In C++98, the
  2965. // initializer also syntactically needs to be an ICE.
  2966. //
  2967. // FIXME: We don't diagnose cases that aren't potentially usable in constant
  2968. // expressions here; doing so would regress diagnostics for things like
  2969. // reading from a volatile constexpr variable.
  2970. if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
  2971. VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
  2972. ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
  2973. !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
  2974. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
  2975. NoteLValueLocation(Info, Base);
  2976. }
  2977. // Never use the initializer of a weak variable, not even for constant
  2978. // folding. We can't be sure that this is the definition that will be used.
  2979. if (VD->isWeak()) {
  2980. Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
  2981. NoteLValueLocation(Info, Base);
  2982. return false;
  2983. }
  2984. Result = VD->getEvaluatedValue();
  2985. return true;
  2986. }
  2987. /// Get the base index of the given base class within an APValue representing
  2988. /// the given derived class.
  2989. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2990. const CXXRecordDecl *Base) {
  2991. Base = Base->getCanonicalDecl();
  2992. unsigned Index = 0;
  2993. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2994. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2995. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2996. return Index;
  2997. }
  2998. llvm_unreachable("base class missing from derived class's bases list");
  2999. }
  3000. /// Extract the value of a character from a string literal.
  3001. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  3002. uint64_t Index) {
  3003. assert(!isa<SourceLocExpr>(Lit) &&
  3004. "SourceLocExpr should have already been converted to a StringLiteral");
  3005. // FIXME: Support MakeStringConstant
  3006. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  3007. std::string Str;
  3008. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  3009. assert(Index <= Str.size() && "Index too large");
  3010. return APSInt::getUnsigned(Str.c_str()[Index]);
  3011. }
  3012. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  3013. Lit = PE->getFunctionName();
  3014. const StringLiteral *S = cast<StringLiteral>(Lit);
  3015. const ConstantArrayType *CAT =
  3016. Info.Ctx.getAsConstantArrayType(S->getType());
  3017. assert(CAT && "string literal isn't an array");
  3018. QualType CharType = CAT->getElementType();
  3019. assert(CharType->isIntegerType() && "unexpected character type");
  3020. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  3021. CharType->isUnsignedIntegerType());
  3022. if (Index < S->getLength())
  3023. Value = S->getCodeUnit(Index);
  3024. return Value;
  3025. }
  3026. // Expand a string literal into an array of characters.
  3027. //
  3028. // FIXME: This is inefficient; we should probably introduce something similar
  3029. // to the LLVM ConstantDataArray to make this cheaper.
  3030. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  3031. APValue &Result,
  3032. QualType AllocType = QualType()) {
  3033. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  3034. AllocType.isNull() ? S->getType() : AllocType);
  3035. assert(CAT && "string literal isn't an array");
  3036. QualType CharType = CAT->getElementType();
  3037. assert(CharType->isIntegerType() && "unexpected character type");
  3038. unsigned Elts = CAT->getSize().getZExtValue();
  3039. Result = APValue(APValue::UninitArray(),
  3040. std::min(S->getLength(), Elts), Elts);
  3041. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  3042. CharType->isUnsignedIntegerType());
  3043. if (Result.hasArrayFiller())
  3044. Result.getArrayFiller() = APValue(Value);
  3045. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  3046. Value = S->getCodeUnit(I);
  3047. Result.getArrayInitializedElt(I) = APValue(Value);
  3048. }
  3049. }
  3050. // Expand an array so that it has more than Index filled elements.
  3051. static void expandArray(APValue &Array, unsigned Index) {
  3052. unsigned Size = Array.getArraySize();
  3053. assert(Index < Size);
  3054. // Always at least double the number of elements for which we store a value.
  3055. unsigned OldElts = Array.getArrayInitializedElts();
  3056. unsigned NewElts = std::max(Index+1, OldElts * 2);
  3057. NewElts = std::min(Size, std::max(NewElts, 8u));
  3058. // Copy the data across.
  3059. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  3060. for (unsigned I = 0; I != OldElts; ++I)
  3061. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  3062. for (unsigned I = OldElts; I != NewElts; ++I)
  3063. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  3064. if (NewValue.hasArrayFiller())
  3065. NewValue.getArrayFiller() = Array.getArrayFiller();
  3066. Array.swap(NewValue);
  3067. }
  3068. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  3069. /// conversion. If it's of class type, we may assume that the copy operation
  3070. /// is trivial. Note that this is never true for a union type with fields
  3071. /// (because the copy always "reads" the active member) and always true for
  3072. /// a non-class type.
  3073. static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
  3074. static bool isReadByLvalueToRvalueConversion(QualType T) {
  3075. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3076. return !RD || isReadByLvalueToRvalueConversion(RD);
  3077. }
  3078. static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
  3079. // FIXME: A trivial copy of a union copies the object representation, even if
  3080. // the union is empty.
  3081. if (RD->isUnion())
  3082. return !RD->field_empty();
  3083. if (RD->isEmpty())
  3084. return false;
  3085. for (auto *Field : RD->fields())
  3086. if (!Field->isUnnamedBitfield() &&
  3087. isReadByLvalueToRvalueConversion(Field->getType()))
  3088. return true;
  3089. for (auto &BaseSpec : RD->bases())
  3090. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  3091. return true;
  3092. return false;
  3093. }
  3094. /// Diagnose an attempt to read from any unreadable field within the specified
  3095. /// type, which might be a class type.
  3096. static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
  3097. QualType T) {
  3098. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3099. if (!RD)
  3100. return false;
  3101. if (!RD->hasMutableFields())
  3102. return false;
  3103. for (auto *Field : RD->fields()) {
  3104. // If we're actually going to read this field in some way, then it can't
  3105. // be mutable. If we're in a union, then assigning to a mutable field
  3106. // (even an empty one) can change the active member, so that's not OK.
  3107. // FIXME: Add core issue number for the union case.
  3108. if (Field->isMutable() &&
  3109. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  3110. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
  3111. Info.Note(Field->getLocation(), diag::note_declared_at);
  3112. return true;
  3113. }
  3114. if (diagnoseMutableFields(Info, E, AK, Field->getType()))
  3115. return true;
  3116. }
  3117. for (auto &BaseSpec : RD->bases())
  3118. if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
  3119. return true;
  3120. // All mutable fields were empty, and thus not actually read.
  3121. return false;
  3122. }
  3123. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  3124. APValue::LValueBase Base,
  3125. bool MutableSubobject = false) {
  3126. // A temporary or transient heap allocation we created.
  3127. if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
  3128. return true;
  3129. switch (Info.IsEvaluatingDecl) {
  3130. case EvalInfo::EvaluatingDeclKind::None:
  3131. return false;
  3132. case EvalInfo::EvaluatingDeclKind::Ctor:
  3133. // The variable whose initializer we're evaluating.
  3134. if (Info.EvaluatingDecl == Base)
  3135. return true;
  3136. // A temporary lifetime-extended by the variable whose initializer we're
  3137. // evaluating.
  3138. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  3139. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  3140. return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
  3141. return false;
  3142. case EvalInfo::EvaluatingDeclKind::Dtor:
  3143. // C++2a [expr.const]p6:
  3144. // [during constant destruction] the lifetime of a and its non-mutable
  3145. // subobjects (but not its mutable subobjects) [are] considered to start
  3146. // within e.
  3147. if (MutableSubobject || Base != Info.EvaluatingDecl)
  3148. return false;
  3149. // FIXME: We can meaningfully extend this to cover non-const objects, but
  3150. // we will need special handling: we should be able to access only
  3151. // subobjects of such objects that are themselves declared const.
  3152. QualType T = getType(Base);
  3153. return T.isConstQualified() || T->isReferenceType();
  3154. }
  3155. llvm_unreachable("unknown evaluating decl kind");
  3156. }
  3157. namespace {
  3158. /// A handle to a complete object (an object that is not a subobject of
  3159. /// another object).
  3160. struct CompleteObject {
  3161. /// The identity of the object.
  3162. APValue::LValueBase Base;
  3163. /// The value of the complete object.
  3164. APValue *Value;
  3165. /// The type of the complete object.
  3166. QualType Type;
  3167. CompleteObject() : Value(nullptr) {}
  3168. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  3169. : Base(Base), Value(Value), Type(Type) {}
  3170. bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
  3171. // If this isn't a "real" access (eg, if it's just accessing the type
  3172. // info), allow it. We assume the type doesn't change dynamically for
  3173. // subobjects of constexpr objects (even though we'd hit UB here if it
  3174. // did). FIXME: Is this right?
  3175. if (!isAnyAccess(AK))
  3176. return true;
  3177. // In C++14 onwards, it is permitted to read a mutable member whose
  3178. // lifetime began within the evaluation.
  3179. // FIXME: Should we also allow this in C++11?
  3180. if (!Info.getLangOpts().CPlusPlus14)
  3181. return false;
  3182. return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
  3183. }
  3184. explicit operator bool() const { return !Type.isNull(); }
  3185. };
  3186. } // end anonymous namespace
  3187. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  3188. bool IsMutable = false) {
  3189. // C++ [basic.type.qualifier]p1:
  3190. // - A const object is an object of type const T or a non-mutable subobject
  3191. // of a const object.
  3192. if (ObjType.isConstQualified() && !IsMutable)
  3193. SubobjType.addConst();
  3194. // - A volatile object is an object of type const T or a subobject of a
  3195. // volatile object.
  3196. if (ObjType.isVolatileQualified())
  3197. SubobjType.addVolatile();
  3198. return SubobjType;
  3199. }
  3200. /// Find the designated sub-object of an rvalue.
  3201. template<typename SubobjectHandler>
  3202. typename SubobjectHandler::result_type
  3203. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  3204. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  3205. if (Sub.Invalid)
  3206. // A diagnostic will have already been produced.
  3207. return handler.failed();
  3208. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  3209. if (Info.getLangOpts().CPlusPlus11)
  3210. Info.FFDiag(E, Sub.isOnePastTheEnd()
  3211. ? diag::note_constexpr_access_past_end
  3212. : diag::note_constexpr_access_unsized_array)
  3213. << handler.AccessKind;
  3214. else
  3215. Info.FFDiag(E);
  3216. return handler.failed();
  3217. }
  3218. APValue *O = Obj.Value;
  3219. QualType ObjType = Obj.Type;
  3220. const FieldDecl *LastField = nullptr;
  3221. const FieldDecl *VolatileField = nullptr;
  3222. // Walk the designator's path to find the subobject.
  3223. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  3224. // Reading an indeterminate value is undefined, but assigning over one is OK.
  3225. if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
  3226. (O->isIndeterminate() &&
  3227. !isValidIndeterminateAccess(handler.AccessKind))) {
  3228. if (!Info.checkingPotentialConstantExpression())
  3229. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  3230. << handler.AccessKind << O->isIndeterminate();
  3231. return handler.failed();
  3232. }
  3233. // C++ [class.ctor]p5, C++ [class.dtor]p5:
  3234. // const and volatile semantics are not applied on an object under
  3235. // {con,de}struction.
  3236. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  3237. ObjType->isRecordType() &&
  3238. Info.isEvaluatingCtorDtor(
  3239. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  3240. Sub.Entries.begin() + I)) !=
  3241. ConstructionPhase::None) {
  3242. ObjType = Info.Ctx.getCanonicalType(ObjType);
  3243. ObjType.removeLocalConst();
  3244. ObjType.removeLocalVolatile();
  3245. }
  3246. // If this is our last pass, check that the final object type is OK.
  3247. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  3248. // Accesses to volatile objects are prohibited.
  3249. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  3250. if (Info.getLangOpts().CPlusPlus) {
  3251. int DiagKind;
  3252. SourceLocation Loc;
  3253. const NamedDecl *Decl = nullptr;
  3254. if (VolatileField) {
  3255. DiagKind = 2;
  3256. Loc = VolatileField->getLocation();
  3257. Decl = VolatileField;
  3258. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  3259. DiagKind = 1;
  3260. Loc = VD->getLocation();
  3261. Decl = VD;
  3262. } else {
  3263. DiagKind = 0;
  3264. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  3265. Loc = E->getExprLoc();
  3266. }
  3267. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  3268. << handler.AccessKind << DiagKind << Decl;
  3269. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  3270. } else {
  3271. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  3272. }
  3273. return handler.failed();
  3274. }
  3275. // If we are reading an object of class type, there may still be more
  3276. // things we need to check: if there are any mutable subobjects, we
  3277. // cannot perform this read. (This only happens when performing a trivial
  3278. // copy or assignment.)
  3279. if (ObjType->isRecordType() &&
  3280. !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
  3281. diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
  3282. return handler.failed();
  3283. }
  3284. if (I == N) {
  3285. if (!handler.found(*O, ObjType))
  3286. return false;
  3287. // If we modified a bit-field, truncate it to the right width.
  3288. if (isModification(handler.AccessKind) &&
  3289. LastField && LastField->isBitField() &&
  3290. !truncateBitfieldValue(Info, E, *O, LastField))
  3291. return false;
  3292. return true;
  3293. }
  3294. LastField = nullptr;
  3295. if (ObjType->isArrayType()) {
  3296. // Next subobject is an array element.
  3297. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  3298. assert(CAT && "vla in literal type?");
  3299. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  3300. if (CAT->getSize().ule(Index)) {
  3301. // Note, it should not be possible to form a pointer with a valid
  3302. // designator which points more than one past the end of the array.
  3303. if (Info.getLangOpts().CPlusPlus11)
  3304. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  3305. << handler.AccessKind;
  3306. else
  3307. Info.FFDiag(E);
  3308. return handler.failed();
  3309. }
  3310. ObjType = CAT->getElementType();
  3311. if (O->getArrayInitializedElts() > Index)
  3312. O = &O->getArrayInitializedElt(Index);
  3313. else if (!isRead(handler.AccessKind)) {
  3314. expandArray(*O, Index);
  3315. O = &O->getArrayInitializedElt(Index);
  3316. } else
  3317. O = &O->getArrayFiller();
  3318. } else if (ObjType->isAnyComplexType()) {
  3319. // Next subobject is a complex number.
  3320. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  3321. if (Index > 1) {
  3322. if (Info.getLangOpts().CPlusPlus11)
  3323. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  3324. << handler.AccessKind;
  3325. else
  3326. Info.FFDiag(E);
  3327. return handler.failed();
  3328. }
  3329. ObjType = getSubobjectType(
  3330. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  3331. assert(I == N - 1 && "extracting subobject of scalar?");
  3332. if (O->isComplexInt()) {
  3333. return handler.found(Index ? O->getComplexIntImag()
  3334. : O->getComplexIntReal(), ObjType);
  3335. } else {
  3336. assert(O->isComplexFloat());
  3337. return handler.found(Index ? O->getComplexFloatImag()
  3338. : O->getComplexFloatReal(), ObjType);
  3339. }
  3340. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  3341. if (Field->isMutable() &&
  3342. !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
  3343. Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
  3344. << handler.AccessKind << Field;
  3345. Info.Note(Field->getLocation(), diag::note_declared_at);
  3346. return handler.failed();
  3347. }
  3348. // Next subobject is a class, struct or union field.
  3349. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  3350. if (RD->isUnion()) {
  3351. const FieldDecl *UnionField = O->getUnionField();
  3352. if (!UnionField ||
  3353. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  3354. if (I == N - 1 && handler.AccessKind == AK_Construct) {
  3355. // Placement new onto an inactive union member makes it active.
  3356. O->setUnion(Field, APValue());
  3357. } else {
  3358. // FIXME: If O->getUnionValue() is absent, report that there's no
  3359. // active union member rather than reporting the prior active union
  3360. // member. We'll need to fix nullptr_t to not use APValue() as its
  3361. // representation first.
  3362. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  3363. << handler.AccessKind << Field << !UnionField << UnionField;
  3364. return handler.failed();
  3365. }
  3366. }
  3367. O = &O->getUnionValue();
  3368. } else
  3369. O = &O->getStructField(Field->getFieldIndex());
  3370. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  3371. LastField = Field;
  3372. if (Field->getType().isVolatileQualified())
  3373. VolatileField = Field;
  3374. } else {
  3375. // Next subobject is a base class.
  3376. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  3377. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  3378. O = &O->getStructBase(getBaseIndex(Derived, Base));
  3379. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  3380. }
  3381. }
  3382. }
  3383. namespace {
  3384. struct ExtractSubobjectHandler {
  3385. EvalInfo &Info;
  3386. const Expr *E;
  3387. APValue &Result;
  3388. const AccessKinds AccessKind;
  3389. typedef bool result_type;
  3390. bool failed() { return false; }
  3391. bool found(APValue &Subobj, QualType SubobjType) {
  3392. Result = Subobj;
  3393. if (AccessKind == AK_ReadObjectRepresentation)
  3394. return true;
  3395. return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
  3396. }
  3397. bool found(APSInt &Value, QualType SubobjType) {
  3398. Result = APValue(Value);
  3399. return true;
  3400. }
  3401. bool found(APFloat &Value, QualType SubobjType) {
  3402. Result = APValue(Value);
  3403. return true;
  3404. }
  3405. };
  3406. } // end anonymous namespace
  3407. /// Extract the designated sub-object of an rvalue.
  3408. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  3409. const CompleteObject &Obj,
  3410. const SubobjectDesignator &Sub, APValue &Result,
  3411. AccessKinds AK = AK_Read) {
  3412. assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
  3413. ExtractSubobjectHandler Handler = {Info, E, Result, AK};
  3414. return findSubobject(Info, E, Obj, Sub, Handler);
  3415. }
  3416. namespace {
  3417. struct ModifySubobjectHandler {
  3418. EvalInfo &Info;
  3419. APValue &NewVal;
  3420. const Expr *E;
  3421. typedef bool result_type;
  3422. static const AccessKinds AccessKind = AK_Assign;
  3423. bool checkConst(QualType QT) {
  3424. // Assigning to a const object has undefined behavior.
  3425. if (QT.isConstQualified()) {
  3426. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3427. return false;
  3428. }
  3429. return true;
  3430. }
  3431. bool failed() { return false; }
  3432. bool found(APValue &Subobj, QualType SubobjType) {
  3433. if (!checkConst(SubobjType))
  3434. return false;
  3435. // We've been given ownership of NewVal, so just swap it in.
  3436. Subobj.swap(NewVal);
  3437. return true;
  3438. }
  3439. bool found(APSInt &Value, QualType SubobjType) {
  3440. if (!checkConst(SubobjType))
  3441. return false;
  3442. if (!NewVal.isInt()) {
  3443. // Maybe trying to write a cast pointer value into a complex?
  3444. Info.FFDiag(E);
  3445. return false;
  3446. }
  3447. Value = NewVal.getInt();
  3448. return true;
  3449. }
  3450. bool found(APFloat &Value, QualType SubobjType) {
  3451. if (!checkConst(SubobjType))
  3452. return false;
  3453. Value = NewVal.getFloat();
  3454. return true;
  3455. }
  3456. };
  3457. } // end anonymous namespace
  3458. const AccessKinds ModifySubobjectHandler::AccessKind;
  3459. /// Update the designated sub-object of an rvalue to the given value.
  3460. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  3461. const CompleteObject &Obj,
  3462. const SubobjectDesignator &Sub,
  3463. APValue &NewVal) {
  3464. ModifySubobjectHandler Handler = { Info, NewVal, E };
  3465. return findSubobject(Info, E, Obj, Sub, Handler);
  3466. }
  3467. /// Find the position where two subobject designators diverge, or equivalently
  3468. /// the length of the common initial subsequence.
  3469. static unsigned FindDesignatorMismatch(QualType ObjType,
  3470. const SubobjectDesignator &A,
  3471. const SubobjectDesignator &B,
  3472. bool &WasArrayIndex) {
  3473. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  3474. for (/**/; I != N; ++I) {
  3475. if (!ObjType.isNull() &&
  3476. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  3477. // Next subobject is an array element.
  3478. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  3479. WasArrayIndex = true;
  3480. return I;
  3481. }
  3482. if (ObjType->isAnyComplexType())
  3483. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  3484. else
  3485. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  3486. } else {
  3487. if (A.Entries[I].getAsBaseOrMember() !=
  3488. B.Entries[I].getAsBaseOrMember()) {
  3489. WasArrayIndex = false;
  3490. return I;
  3491. }
  3492. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  3493. // Next subobject is a field.
  3494. ObjType = FD->getType();
  3495. else
  3496. // Next subobject is a base class.
  3497. ObjType = QualType();
  3498. }
  3499. }
  3500. WasArrayIndex = false;
  3501. return I;
  3502. }
  3503. /// Determine whether the given subobject designators refer to elements of the
  3504. /// same array object.
  3505. static bool AreElementsOfSameArray(QualType ObjType,
  3506. const SubobjectDesignator &A,
  3507. const SubobjectDesignator &B) {
  3508. if (A.Entries.size() != B.Entries.size())
  3509. return false;
  3510. bool IsArray = A.MostDerivedIsArrayElement;
  3511. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  3512. // A is a subobject of the array element.
  3513. return false;
  3514. // If A (and B) designates an array element, the last entry will be the array
  3515. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  3516. // of length 1' case, and the entire path must match.
  3517. bool WasArrayIndex;
  3518. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  3519. return CommonLength >= A.Entries.size() - IsArray;
  3520. }
  3521. /// Find the complete object to which an LValue refers.
  3522. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  3523. AccessKinds AK, const LValue &LVal,
  3524. QualType LValType) {
  3525. if (LVal.InvalidBase) {
  3526. Info.FFDiag(E);
  3527. return CompleteObject();
  3528. }
  3529. if (!LVal.Base) {
  3530. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  3531. return CompleteObject();
  3532. }
  3533. CallStackFrame *Frame = nullptr;
  3534. unsigned Depth = 0;
  3535. if (LVal.getLValueCallIndex()) {
  3536. std::tie(Frame, Depth) =
  3537. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  3538. if (!Frame) {
  3539. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  3540. << AK << LVal.Base.is<const ValueDecl*>();
  3541. NoteLValueLocation(Info, LVal.Base);
  3542. return CompleteObject();
  3543. }
  3544. }
  3545. bool IsAccess = isAnyAccess(AK);
  3546. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  3547. // is not a constant expression (even if the object is non-volatile). We also
  3548. // apply this rule to C++98, in order to conform to the expected 'volatile'
  3549. // semantics.
  3550. if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
  3551. if (Info.getLangOpts().CPlusPlus)
  3552. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  3553. << AK << LValType;
  3554. else
  3555. Info.FFDiag(E);
  3556. return CompleteObject();
  3557. }
  3558. // Compute value storage location and type of base object.
  3559. APValue *BaseVal = nullptr;
  3560. QualType BaseType = getType(LVal.Base);
  3561. if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
  3562. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3563. // This is the object whose initializer we're evaluating, so its lifetime
  3564. // started in the current evaluation.
  3565. BaseVal = Info.EvaluatingDeclValue;
  3566. } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
  3567. // Allow reading from a GUID declaration.
  3568. if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
  3569. if (isModification(AK)) {
  3570. // All the remaining cases do not permit modification of the object.
  3571. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3572. return CompleteObject();
  3573. }
  3574. APValue &V = GD->getAsAPValue();
  3575. if (V.isAbsent()) {
  3576. Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
  3577. << GD->getType();
  3578. return CompleteObject();
  3579. }
  3580. return CompleteObject(LVal.Base, &V, GD->getType());
  3581. }
  3582. // Allow reading from template parameter objects.
  3583. if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
  3584. if (isModification(AK)) {
  3585. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3586. return CompleteObject();
  3587. }
  3588. return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
  3589. TPO->getType());
  3590. }
  3591. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  3592. // In C++11, constexpr, non-volatile variables initialized with constant
  3593. // expressions are constant expressions too. Inside constexpr functions,
  3594. // parameters are constant expressions even if they're non-const.
  3595. // In C++1y, objects local to a constant expression (those with a Frame) are
  3596. // both readable and writable inside constant expressions.
  3597. // In C, such things can also be folded, although they are not ICEs.
  3598. const VarDecl *VD = dyn_cast<VarDecl>(D);
  3599. if (VD) {
  3600. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3601. VD = VDef;
  3602. }
  3603. if (!VD || VD->isInvalidDecl()) {
  3604. Info.FFDiag(E);
  3605. return CompleteObject();
  3606. }
  3607. bool IsConstant = BaseType.isConstant(Info.Ctx);
  3608. // Unless we're looking at a local variable or argument in a constexpr call,
  3609. // the variable we're reading must be const.
  3610. if (!Frame) {
  3611. if (IsAccess && isa<ParmVarDecl>(VD)) {
  3612. // Access of a parameter that's not associated with a frame isn't going
  3613. // to work out, but we can leave it to evaluateVarDeclInit to provide a
  3614. // suitable diagnostic.
  3615. } else if (Info.getLangOpts().CPlusPlus14 &&
  3616. lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3617. // OK, we can read and modify an object if we're in the process of
  3618. // evaluating its initializer, because its lifetime began in this
  3619. // evaluation.
  3620. } else if (isModification(AK)) {
  3621. // All the remaining cases do not permit modification of the object.
  3622. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3623. return CompleteObject();
  3624. } else if (VD->isConstexpr()) {
  3625. // OK, we can read this variable.
  3626. } else if (BaseType->isIntegralOrEnumerationType()) {
  3627. if (!IsConstant) {
  3628. if (!IsAccess)
  3629. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3630. if (Info.getLangOpts().CPlusPlus) {
  3631. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3632. Info.Note(VD->getLocation(), diag::note_declared_at);
  3633. } else {
  3634. Info.FFDiag(E);
  3635. }
  3636. return CompleteObject();
  3637. }
  3638. } else if (!IsAccess) {
  3639. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3640. } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
  3641. BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
  3642. // This variable might end up being constexpr. Don't diagnose it yet.
  3643. } else if (IsConstant) {
  3644. // Keep evaluating to see what we can do. In particular, we support
  3645. // folding of const floating-point types, in order to make static const
  3646. // data members of such types (supported as an extension) more useful.
  3647. if (Info.getLangOpts().CPlusPlus) {
  3648. Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
  3649. ? diag::note_constexpr_ltor_non_constexpr
  3650. : diag::note_constexpr_ltor_non_integral, 1)
  3651. << VD << BaseType;
  3652. Info.Note(VD->getLocation(), diag::note_declared_at);
  3653. } else {
  3654. Info.CCEDiag(E);
  3655. }
  3656. } else {
  3657. // Never allow reading a non-const value.
  3658. if (Info.getLangOpts().CPlusPlus) {
  3659. Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
  3660. ? diag::note_constexpr_ltor_non_constexpr
  3661. : diag::note_constexpr_ltor_non_integral, 1)
  3662. << VD << BaseType;
  3663. Info.Note(VD->getLocation(), diag::note_declared_at);
  3664. } else {
  3665. Info.FFDiag(E);
  3666. }
  3667. return CompleteObject();
  3668. }
  3669. }
  3670. if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
  3671. return CompleteObject();
  3672. } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
  3673. Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
  3674. if (!Alloc) {
  3675. Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
  3676. return CompleteObject();
  3677. }
  3678. return CompleteObject(LVal.Base, &(*Alloc)->Value,
  3679. LVal.Base.getDynamicAllocType());
  3680. } else {
  3681. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3682. if (!Frame) {
  3683. if (const MaterializeTemporaryExpr *MTE =
  3684. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3685. assert(MTE->getStorageDuration() == SD_Static &&
  3686. "should have a frame for a non-global materialized temporary");
  3687. // C++20 [expr.const]p4: [DR2126]
  3688. // An object or reference is usable in constant expressions if it is
  3689. // - a temporary object of non-volatile const-qualified literal type
  3690. // whose lifetime is extended to that of a variable that is usable
  3691. // in constant expressions
  3692. //
  3693. // C++20 [expr.const]p5:
  3694. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3695. // - a non-volatile glvalue that refers to an object that is usable
  3696. // in constant expressions, or
  3697. // - a non-volatile glvalue of literal type that refers to a
  3698. // non-volatile object whose lifetime began within the evaluation
  3699. // of E;
  3700. //
  3701. // C++11 misses the 'began within the evaluation of e' check and
  3702. // instead allows all temporaries, including things like:
  3703. // int &&r = 1;
  3704. // int x = ++r;
  3705. // constexpr int k = r;
  3706. // Therefore we use the C++14-onwards rules in C++11 too.
  3707. //
  3708. // Note that temporaries whose lifetimes began while evaluating a
  3709. // variable's constructor are not usable while evaluating the
  3710. // corresponding destructor, not even if they're of const-qualified
  3711. // types.
  3712. if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
  3713. !lifetimeStartedInEvaluation(Info, LVal.Base)) {
  3714. if (!IsAccess)
  3715. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3716. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3717. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3718. return CompleteObject();
  3719. }
  3720. BaseVal = MTE->getOrCreateValue(false);
  3721. assert(BaseVal && "got reference to unevaluated temporary");
  3722. } else {
  3723. if (!IsAccess)
  3724. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3725. APValue Val;
  3726. LVal.moveInto(Val);
  3727. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3728. << AK
  3729. << Val.getAsString(Info.Ctx,
  3730. Info.Ctx.getLValueReferenceType(LValType));
  3731. NoteLValueLocation(Info, LVal.Base);
  3732. return CompleteObject();
  3733. }
  3734. } else {
  3735. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3736. assert(BaseVal && "missing value for temporary");
  3737. }
  3738. }
  3739. // In C++14, we can't safely access any mutable state when we might be
  3740. // evaluating after an unmodeled side effect. Parameters are modeled as state
  3741. // in the caller, but aren't visible once the call returns, so they can be
  3742. // modified in a speculatively-evaluated call.
  3743. //
  3744. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3745. // to be read here (but take care with 'mutable' fields).
  3746. unsigned VisibleDepth = Depth;
  3747. if (llvm::isa_and_nonnull<ParmVarDecl>(
  3748. LVal.Base.dyn_cast<const ValueDecl *>()))
  3749. ++VisibleDepth;
  3750. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3751. Info.EvalStatus.HasSideEffects) ||
  3752. (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
  3753. return CompleteObject();
  3754. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3755. }
  3756. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3757. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3758. /// glvalue referred to by an entity of reference type.
  3759. ///
  3760. /// \param Info - Information about the ongoing evaluation.
  3761. /// \param Conv - The expression for which we are performing the conversion.
  3762. /// Used for diagnostics.
  3763. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3764. /// case of a non-class type).
  3765. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3766. /// \param RVal - The produced value will be placed here.
  3767. /// \param WantObjectRepresentation - If true, we're looking for the object
  3768. /// representation rather than the value, and in particular,
  3769. /// there is no requirement that the result be fully initialized.
  3770. static bool
  3771. handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
  3772. const LValue &LVal, APValue &RVal,
  3773. bool WantObjectRepresentation = false) {
  3774. if (LVal.Designator.Invalid)
  3775. return false;
  3776. // Check for special cases where there is no existing APValue to look at.
  3777. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3778. AccessKinds AK =
  3779. WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
  3780. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3781. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3782. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3783. // initializer until now for such expressions. Such an expression can't be
  3784. // an ICE in C, so this only matters for fold.
  3785. if (Type.isVolatileQualified()) {
  3786. Info.FFDiag(Conv);
  3787. return false;
  3788. }
  3789. APValue Lit;
  3790. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3791. return false;
  3792. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3793. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
  3794. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3795. // Special-case character extraction so we don't have to construct an
  3796. // APValue for the whole string.
  3797. assert(LVal.Designator.Entries.size() <= 1 &&
  3798. "Can only read characters from string literals");
  3799. if (LVal.Designator.Entries.empty()) {
  3800. // Fail for now for LValue to RValue conversion of an array.
  3801. // (This shouldn't show up in C/C++, but it could be triggered by a
  3802. // weird EvaluateAsRValue call from a tool.)
  3803. Info.FFDiag(Conv);
  3804. return false;
  3805. }
  3806. if (LVal.Designator.isOnePastTheEnd()) {
  3807. if (Info.getLangOpts().CPlusPlus11)
  3808. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
  3809. else
  3810. Info.FFDiag(Conv);
  3811. return false;
  3812. }
  3813. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3814. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3815. return true;
  3816. }
  3817. }
  3818. CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
  3819. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
  3820. }
  3821. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3822. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3823. QualType LValType, APValue &Val) {
  3824. if (LVal.Designator.Invalid)
  3825. return false;
  3826. if (!Info.getLangOpts().CPlusPlus14) {
  3827. Info.FFDiag(E);
  3828. return false;
  3829. }
  3830. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3831. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3832. }
  3833. namespace {
  3834. struct CompoundAssignSubobjectHandler {
  3835. EvalInfo &Info;
  3836. const CompoundAssignOperator *E;
  3837. QualType PromotedLHSType;
  3838. BinaryOperatorKind Opcode;
  3839. const APValue &RHS;
  3840. static const AccessKinds AccessKind = AK_Assign;
  3841. typedef bool result_type;
  3842. bool checkConst(QualType QT) {
  3843. // Assigning to a const object has undefined behavior.
  3844. if (QT.isConstQualified()) {
  3845. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3846. return false;
  3847. }
  3848. return true;
  3849. }
  3850. bool failed() { return false; }
  3851. bool found(APValue &Subobj, QualType SubobjType) {
  3852. switch (Subobj.getKind()) {
  3853. case APValue::Int:
  3854. return found(Subobj.getInt(), SubobjType);
  3855. case APValue::Float:
  3856. return found(Subobj.getFloat(), SubobjType);
  3857. case APValue::ComplexInt:
  3858. case APValue::ComplexFloat:
  3859. // FIXME: Implement complex compound assignment.
  3860. Info.FFDiag(E);
  3861. return false;
  3862. case APValue::LValue:
  3863. return foundPointer(Subobj, SubobjType);
  3864. case APValue::Vector:
  3865. return foundVector(Subobj, SubobjType);
  3866. default:
  3867. // FIXME: can this happen?
  3868. Info.FFDiag(E);
  3869. return false;
  3870. }
  3871. }
  3872. bool foundVector(APValue &Value, QualType SubobjType) {
  3873. if (!checkConst(SubobjType))
  3874. return false;
  3875. if (!SubobjType->isVectorType()) {
  3876. Info.FFDiag(E);
  3877. return false;
  3878. }
  3879. return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
  3880. }
  3881. bool found(APSInt &Value, QualType SubobjType) {
  3882. if (!checkConst(SubobjType))
  3883. return false;
  3884. if (!SubobjType->isIntegerType()) {
  3885. // We don't support compound assignment on integer-cast-to-pointer
  3886. // values.
  3887. Info.FFDiag(E);
  3888. return false;
  3889. }
  3890. if (RHS.isInt()) {
  3891. APSInt LHS =
  3892. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3893. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3894. return false;
  3895. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3896. return true;
  3897. } else if (RHS.isFloat()) {
  3898. const FPOptions FPO = E->getFPFeaturesInEffect(
  3899. Info.Ctx.getLangOpts());
  3900. APFloat FValue(0.0);
  3901. return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
  3902. PromotedLHSType, FValue) &&
  3903. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3904. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3905. Value);
  3906. }
  3907. Info.FFDiag(E);
  3908. return false;
  3909. }
  3910. bool found(APFloat &Value, QualType SubobjType) {
  3911. return checkConst(SubobjType) &&
  3912. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3913. Value) &&
  3914. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3915. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3916. }
  3917. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3918. if (!checkConst(SubobjType))
  3919. return false;
  3920. QualType PointeeType;
  3921. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3922. PointeeType = PT->getPointeeType();
  3923. if (PointeeType.isNull() || !RHS.isInt() ||
  3924. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3925. Info.FFDiag(E);
  3926. return false;
  3927. }
  3928. APSInt Offset = RHS.getInt();
  3929. if (Opcode == BO_Sub)
  3930. negateAsSigned(Offset);
  3931. LValue LVal;
  3932. LVal.setFrom(Info.Ctx, Subobj);
  3933. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3934. return false;
  3935. LVal.moveInto(Subobj);
  3936. return true;
  3937. }
  3938. };
  3939. } // end anonymous namespace
  3940. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3941. /// Perform a compound assignment of LVal <op>= RVal.
  3942. static bool handleCompoundAssignment(EvalInfo &Info,
  3943. const CompoundAssignOperator *E,
  3944. const LValue &LVal, QualType LValType,
  3945. QualType PromotedLValType,
  3946. BinaryOperatorKind Opcode,
  3947. const APValue &RVal) {
  3948. if (LVal.Designator.Invalid)
  3949. return false;
  3950. if (!Info.getLangOpts().CPlusPlus14) {
  3951. Info.FFDiag(E);
  3952. return false;
  3953. }
  3954. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3955. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3956. RVal };
  3957. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3958. }
  3959. namespace {
  3960. struct IncDecSubobjectHandler {
  3961. EvalInfo &Info;
  3962. const UnaryOperator *E;
  3963. AccessKinds AccessKind;
  3964. APValue *Old;
  3965. typedef bool result_type;
  3966. bool checkConst(QualType QT) {
  3967. // Assigning to a const object has undefined behavior.
  3968. if (QT.isConstQualified()) {
  3969. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3970. return false;
  3971. }
  3972. return true;
  3973. }
  3974. bool failed() { return false; }
  3975. bool found(APValue &Subobj, QualType SubobjType) {
  3976. // Stash the old value. Also clear Old, so we don't clobber it later
  3977. // if we're post-incrementing a complex.
  3978. if (Old) {
  3979. *Old = Subobj;
  3980. Old = nullptr;
  3981. }
  3982. switch (Subobj.getKind()) {
  3983. case APValue::Int:
  3984. return found(Subobj.getInt(), SubobjType);
  3985. case APValue::Float:
  3986. return found(Subobj.getFloat(), SubobjType);
  3987. case APValue::ComplexInt:
  3988. return found(Subobj.getComplexIntReal(),
  3989. SubobjType->castAs<ComplexType>()->getElementType()
  3990. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3991. case APValue::ComplexFloat:
  3992. return found(Subobj.getComplexFloatReal(),
  3993. SubobjType->castAs<ComplexType>()->getElementType()
  3994. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3995. case APValue::LValue:
  3996. return foundPointer(Subobj, SubobjType);
  3997. default:
  3998. // FIXME: can this happen?
  3999. Info.FFDiag(E);
  4000. return false;
  4001. }
  4002. }
  4003. bool found(APSInt &Value, QualType SubobjType) {
  4004. if (!checkConst(SubobjType))
  4005. return false;
  4006. if (!SubobjType->isIntegerType()) {
  4007. // We don't support increment / decrement on integer-cast-to-pointer
  4008. // values.
  4009. Info.FFDiag(E);
  4010. return false;
  4011. }
  4012. if (Old) *Old = APValue(Value);
  4013. // bool arithmetic promotes to int, and the conversion back to bool
  4014. // doesn't reduce mod 2^n, so special-case it.
  4015. if (SubobjType->isBooleanType()) {
  4016. if (AccessKind == AK_Increment)
  4017. Value = 1;
  4018. else
  4019. Value = !Value;
  4020. return true;
  4021. }
  4022. bool WasNegative = Value.isNegative();
  4023. if (AccessKind == AK_Increment) {
  4024. ++Value;
  4025. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  4026. APSInt ActualValue(Value, /*IsUnsigned*/true);
  4027. return HandleOverflow(Info, E, ActualValue, SubobjType);
  4028. }
  4029. } else {
  4030. --Value;
  4031. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  4032. unsigned BitWidth = Value.getBitWidth();
  4033. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  4034. ActualValue.setBit(BitWidth);
  4035. return HandleOverflow(Info, E, ActualValue, SubobjType);
  4036. }
  4037. }
  4038. return true;
  4039. }
  4040. bool found(APFloat &Value, QualType SubobjType) {
  4041. if (!checkConst(SubobjType))
  4042. return false;
  4043. if (Old) *Old = APValue(Value);
  4044. APFloat One(Value.getSemantics(), 1);
  4045. if (AccessKind == AK_Increment)
  4046. Value.add(One, APFloat::rmNearestTiesToEven);
  4047. else
  4048. Value.subtract(One, APFloat::rmNearestTiesToEven);
  4049. return true;
  4050. }
  4051. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  4052. if (!checkConst(SubobjType))
  4053. return false;
  4054. QualType PointeeType;
  4055. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  4056. PointeeType = PT->getPointeeType();
  4057. else {
  4058. Info.FFDiag(E);
  4059. return false;
  4060. }
  4061. LValue LVal;
  4062. LVal.setFrom(Info.Ctx, Subobj);
  4063. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  4064. AccessKind == AK_Increment ? 1 : -1))
  4065. return false;
  4066. LVal.moveInto(Subobj);
  4067. return true;
  4068. }
  4069. };
  4070. } // end anonymous namespace
  4071. /// Perform an increment or decrement on LVal.
  4072. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  4073. QualType LValType, bool IsIncrement, APValue *Old) {
  4074. if (LVal.Designator.Invalid)
  4075. return false;
  4076. if (!Info.getLangOpts().CPlusPlus14) {
  4077. Info.FFDiag(E);
  4078. return false;
  4079. }
  4080. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  4081. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  4082. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  4083. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  4084. }
  4085. /// Build an lvalue for the object argument of a member function call.
  4086. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  4087. LValue &This) {
  4088. if (Object->getType()->isPointerType() && Object->isPRValue())
  4089. return EvaluatePointer(Object, This, Info);
  4090. if (Object->isGLValue())
  4091. return EvaluateLValue(Object, This, Info);
  4092. if (Object->getType()->isLiteralType(Info.Ctx))
  4093. return EvaluateTemporary(Object, This, Info);
  4094. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  4095. return false;
  4096. }
  4097. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  4098. /// lvalue referring to the result.
  4099. ///
  4100. /// \param Info - Information about the ongoing evaluation.
  4101. /// \param LV - An lvalue referring to the base of the member pointer.
  4102. /// \param RHS - The member pointer expression.
  4103. /// \param IncludeMember - Specifies whether the member itself is included in
  4104. /// the resulting LValue subobject designator. This is not possible when
  4105. /// creating a bound member function.
  4106. /// \return The field or method declaration to which the member pointer refers,
  4107. /// or 0 if evaluation fails.
  4108. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  4109. QualType LVType,
  4110. LValue &LV,
  4111. const Expr *RHS,
  4112. bool IncludeMember = true) {
  4113. MemberPtr MemPtr;
  4114. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  4115. return nullptr;
  4116. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  4117. // member value, the behavior is undefined.
  4118. if (!MemPtr.getDecl()) {
  4119. // FIXME: Specific diagnostic.
  4120. Info.FFDiag(RHS);
  4121. return nullptr;
  4122. }
  4123. if (MemPtr.isDerivedMember()) {
  4124. // This is a member of some derived class. Truncate LV appropriately.
  4125. // The end of the derived-to-base path for the base object must match the
  4126. // derived-to-base path for the member pointer.
  4127. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  4128. LV.Designator.Entries.size()) {
  4129. Info.FFDiag(RHS);
  4130. return nullptr;
  4131. }
  4132. unsigned PathLengthToMember =
  4133. LV.Designator.Entries.size() - MemPtr.Path.size();
  4134. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  4135. const CXXRecordDecl *LVDecl = getAsBaseClass(
  4136. LV.Designator.Entries[PathLengthToMember + I]);
  4137. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  4138. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  4139. Info.FFDiag(RHS);
  4140. return nullptr;
  4141. }
  4142. }
  4143. // Truncate the lvalue to the appropriate derived class.
  4144. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  4145. PathLengthToMember))
  4146. return nullptr;
  4147. } else if (!MemPtr.Path.empty()) {
  4148. // Extend the LValue path with the member pointer's path.
  4149. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  4150. MemPtr.Path.size() + IncludeMember);
  4151. // Walk down to the appropriate base class.
  4152. if (const PointerType *PT = LVType->getAs<PointerType>())
  4153. LVType = PT->getPointeeType();
  4154. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  4155. assert(RD && "member pointer access on non-class-type expression");
  4156. // The first class in the path is that of the lvalue.
  4157. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  4158. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  4159. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  4160. return nullptr;
  4161. RD = Base;
  4162. }
  4163. // Finally cast to the class containing the member.
  4164. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  4165. MemPtr.getContainingRecord()))
  4166. return nullptr;
  4167. }
  4168. // Add the member. Note that we cannot build bound member functions here.
  4169. if (IncludeMember) {
  4170. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  4171. if (!HandleLValueMember(Info, RHS, LV, FD))
  4172. return nullptr;
  4173. } else if (const IndirectFieldDecl *IFD =
  4174. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  4175. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  4176. return nullptr;
  4177. } else {
  4178. llvm_unreachable("can't construct reference to bound member function");
  4179. }
  4180. }
  4181. return MemPtr.getDecl();
  4182. }
  4183. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  4184. const BinaryOperator *BO,
  4185. LValue &LV,
  4186. bool IncludeMember = true) {
  4187. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  4188. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  4189. if (Info.noteFailure()) {
  4190. MemberPtr MemPtr;
  4191. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  4192. }
  4193. return nullptr;
  4194. }
  4195. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  4196. BO->getRHS(), IncludeMember);
  4197. }
  4198. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  4199. /// the provided lvalue, which currently refers to the base object.
  4200. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  4201. LValue &Result) {
  4202. SubobjectDesignator &D = Result.Designator;
  4203. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  4204. return false;
  4205. QualType TargetQT = E->getType();
  4206. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  4207. TargetQT = PT->getPointeeType();
  4208. // Check this cast lands within the final derived-to-base subobject path.
  4209. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  4210. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  4211. << D.MostDerivedType << TargetQT;
  4212. return false;
  4213. }
  4214. // Check the type of the final cast. We don't need to check the path,
  4215. // since a cast can only be formed if the path is unique.
  4216. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  4217. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  4218. const CXXRecordDecl *FinalType;
  4219. if (NewEntriesSize == D.MostDerivedPathLength)
  4220. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  4221. else
  4222. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  4223. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  4224. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  4225. << D.MostDerivedType << TargetQT;
  4226. return false;
  4227. }
  4228. // Truncate the lvalue to the appropriate derived class.
  4229. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  4230. }
  4231. /// Get the value to use for a default-initialized object of type T.
  4232. /// Return false if it encounters something invalid.
  4233. static bool getDefaultInitValue(QualType T, APValue &Result) {
  4234. bool Success = true;
  4235. if (auto *RD = T->getAsCXXRecordDecl()) {
  4236. if (RD->isInvalidDecl()) {
  4237. Result = APValue();
  4238. return false;
  4239. }
  4240. if (RD->isUnion()) {
  4241. Result = APValue((const FieldDecl *)nullptr);
  4242. return true;
  4243. }
  4244. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4245. std::distance(RD->field_begin(), RD->field_end()));
  4246. unsigned Index = 0;
  4247. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  4248. End = RD->bases_end();
  4249. I != End; ++I, ++Index)
  4250. Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
  4251. for (const auto *I : RD->fields()) {
  4252. if (I->isUnnamedBitfield())
  4253. continue;
  4254. Success &= getDefaultInitValue(I->getType(),
  4255. Result.getStructField(I->getFieldIndex()));
  4256. }
  4257. return Success;
  4258. }
  4259. if (auto *AT =
  4260. dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
  4261. Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  4262. if (Result.hasArrayFiller())
  4263. Success &=
  4264. getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
  4265. return Success;
  4266. }
  4267. Result = APValue::IndeterminateValue();
  4268. return true;
  4269. }
  4270. namespace {
  4271. enum EvalStmtResult {
  4272. /// Evaluation failed.
  4273. ESR_Failed,
  4274. /// Hit a 'return' statement.
  4275. ESR_Returned,
  4276. /// Evaluation succeeded.
  4277. ESR_Succeeded,
  4278. /// Hit a 'continue' statement.
  4279. ESR_Continue,
  4280. /// Hit a 'break' statement.
  4281. ESR_Break,
  4282. /// Still scanning for 'case' or 'default' statement.
  4283. ESR_CaseNotFound
  4284. };
  4285. }
  4286. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  4287. // We don't need to evaluate the initializer for a static local.
  4288. if (!VD->hasLocalStorage())
  4289. return true;
  4290. LValue Result;
  4291. APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
  4292. ScopeKind::Block, Result);
  4293. const Expr *InitE = VD->getInit();
  4294. if (!InitE) {
  4295. if (VD->getType()->isDependentType())
  4296. return Info.noteSideEffect();
  4297. return getDefaultInitValue(VD->getType(), Val);
  4298. }
  4299. if (InitE->isValueDependent())
  4300. return false;
  4301. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  4302. // Wipe out any partially-computed value, to allow tracking that this
  4303. // evaluation failed.
  4304. Val = APValue();
  4305. return false;
  4306. }
  4307. return true;
  4308. }
  4309. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  4310. bool OK = true;
  4311. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  4312. OK &= EvaluateVarDecl(Info, VD);
  4313. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  4314. for (auto *BD : DD->bindings())
  4315. if (auto *VD = BD->getHoldingVar())
  4316. OK &= EvaluateDecl(Info, VD);
  4317. return OK;
  4318. }
  4319. static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
  4320. assert(E->isValueDependent());
  4321. if (Info.noteSideEffect())
  4322. return true;
  4323. assert(E->containsErrors() && "valid value-dependent expression should never "
  4324. "reach invalid code path.");
  4325. return false;
  4326. }
  4327. /// Evaluate a condition (either a variable declaration or an expression).
  4328. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  4329. const Expr *Cond, bool &Result) {
  4330. if (Cond->isValueDependent())
  4331. return false;
  4332. FullExpressionRAII Scope(Info);
  4333. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  4334. return false;
  4335. if (!EvaluateAsBooleanCondition(Cond, Result, Info))
  4336. return false;
  4337. return Scope.destroy();
  4338. }
  4339. namespace {
  4340. /// A location where the result (returned value) of evaluating a
  4341. /// statement should be stored.
  4342. struct StmtResult {
  4343. /// The APValue that should be filled in with the returned value.
  4344. APValue &Value;
  4345. /// The location containing the result, if any (used to support RVO).
  4346. const LValue *Slot;
  4347. };
  4348. struct TempVersionRAII {
  4349. CallStackFrame &Frame;
  4350. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  4351. Frame.pushTempVersion();
  4352. }
  4353. ~TempVersionRAII() {
  4354. Frame.popTempVersion();
  4355. }
  4356. };
  4357. }
  4358. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  4359. const Stmt *S,
  4360. const SwitchCase *SC = nullptr);
  4361. /// Evaluate the body of a loop, and translate the result as appropriate.
  4362. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  4363. const Stmt *Body,
  4364. const SwitchCase *Case = nullptr) {
  4365. BlockScopeRAII Scope(Info);
  4366. EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
  4367. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  4368. ESR = ESR_Failed;
  4369. switch (ESR) {
  4370. case ESR_Break:
  4371. return ESR_Succeeded;
  4372. case ESR_Succeeded:
  4373. case ESR_Continue:
  4374. return ESR_Continue;
  4375. case ESR_Failed:
  4376. case ESR_Returned:
  4377. case ESR_CaseNotFound:
  4378. return ESR;
  4379. }
  4380. llvm_unreachable("Invalid EvalStmtResult!");
  4381. }
  4382. /// Evaluate a switch statement.
  4383. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  4384. const SwitchStmt *SS) {
  4385. BlockScopeRAII Scope(Info);
  4386. // Evaluate the switch condition.
  4387. APSInt Value;
  4388. {
  4389. if (const Stmt *Init = SS->getInit()) {
  4390. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4391. if (ESR != ESR_Succeeded) {
  4392. if (ESR != ESR_Failed && !Scope.destroy())
  4393. ESR = ESR_Failed;
  4394. return ESR;
  4395. }
  4396. }
  4397. FullExpressionRAII CondScope(Info);
  4398. if (SS->getConditionVariable() &&
  4399. !EvaluateDecl(Info, SS->getConditionVariable()))
  4400. return ESR_Failed;
  4401. if (SS->getCond()->isValueDependent()) {
  4402. if (!EvaluateDependentExpr(SS->getCond(), Info))
  4403. return ESR_Failed;
  4404. } else {
  4405. if (!EvaluateInteger(SS->getCond(), Value, Info))
  4406. return ESR_Failed;
  4407. }
  4408. if (!CondScope.destroy())
  4409. return ESR_Failed;
  4410. }
  4411. // Find the switch case corresponding to the value of the condition.
  4412. // FIXME: Cache this lookup.
  4413. const SwitchCase *Found = nullptr;
  4414. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  4415. SC = SC->getNextSwitchCase()) {
  4416. if (isa<DefaultStmt>(SC)) {
  4417. Found = SC;
  4418. continue;
  4419. }
  4420. const CaseStmt *CS = cast<CaseStmt>(SC);
  4421. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  4422. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  4423. : LHS;
  4424. if (LHS <= Value && Value <= RHS) {
  4425. Found = SC;
  4426. break;
  4427. }
  4428. }
  4429. if (!Found)
  4430. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4431. // Search the switch body for the switch case and evaluate it from there.
  4432. EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
  4433. if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
  4434. return ESR_Failed;
  4435. switch (ESR) {
  4436. case ESR_Break:
  4437. return ESR_Succeeded;
  4438. case ESR_Succeeded:
  4439. case ESR_Continue:
  4440. case ESR_Failed:
  4441. case ESR_Returned:
  4442. return ESR;
  4443. case ESR_CaseNotFound:
  4444. // This can only happen if the switch case is nested within a statement
  4445. // expression. We have no intention of supporting that.
  4446. Info.FFDiag(Found->getBeginLoc(),
  4447. diag::note_constexpr_stmt_expr_unsupported);
  4448. return ESR_Failed;
  4449. }
  4450. llvm_unreachable("Invalid EvalStmtResult!");
  4451. }
  4452. // Evaluate a statement.
  4453. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  4454. const Stmt *S, const SwitchCase *Case) {
  4455. if (!Info.nextStep(S))
  4456. return ESR_Failed;
  4457. // If we're hunting down a 'case' or 'default' label, recurse through
  4458. // substatements until we hit the label.
  4459. if (Case) {
  4460. switch (S->getStmtClass()) {
  4461. case Stmt::CompoundStmtClass:
  4462. // FIXME: Precompute which substatement of a compound statement we
  4463. // would jump to, and go straight there rather than performing a
  4464. // linear scan each time.
  4465. case Stmt::LabelStmtClass:
  4466. case Stmt::AttributedStmtClass:
  4467. case Stmt::DoStmtClass:
  4468. break;
  4469. case Stmt::CaseStmtClass:
  4470. case Stmt::DefaultStmtClass:
  4471. if (Case == S)
  4472. Case = nullptr;
  4473. break;
  4474. case Stmt::IfStmtClass: {
  4475. // FIXME: Precompute which side of an 'if' we would jump to, and go
  4476. // straight there rather than scanning both sides.
  4477. const IfStmt *IS = cast<IfStmt>(S);
  4478. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  4479. // preceded by our switch label.
  4480. BlockScopeRAII Scope(Info);
  4481. // Step into the init statement in case it brings an (uninitialized)
  4482. // variable into scope.
  4483. if (const Stmt *Init = IS->getInit()) {
  4484. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  4485. if (ESR != ESR_CaseNotFound) {
  4486. assert(ESR != ESR_Succeeded);
  4487. return ESR;
  4488. }
  4489. }
  4490. // Condition variable must be initialized if it exists.
  4491. // FIXME: We can skip evaluating the body if there's a condition
  4492. // variable, as there can't be any case labels within it.
  4493. // (The same is true for 'for' statements.)
  4494. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  4495. if (ESR == ESR_Failed)
  4496. return ESR;
  4497. if (ESR != ESR_CaseNotFound)
  4498. return Scope.destroy() ? ESR : ESR_Failed;
  4499. if (!IS->getElse())
  4500. return ESR_CaseNotFound;
  4501. ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
  4502. if (ESR == ESR_Failed)
  4503. return ESR;
  4504. if (ESR != ESR_CaseNotFound)
  4505. return Scope.destroy() ? ESR : ESR_Failed;
  4506. return ESR_CaseNotFound;
  4507. }
  4508. case Stmt::WhileStmtClass: {
  4509. EvalStmtResult ESR =
  4510. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  4511. if (ESR != ESR_Continue)
  4512. return ESR;
  4513. break;
  4514. }
  4515. case Stmt::ForStmtClass: {
  4516. const ForStmt *FS = cast<ForStmt>(S);
  4517. BlockScopeRAII Scope(Info);
  4518. // Step into the init statement in case it brings an (uninitialized)
  4519. // variable into scope.
  4520. if (const Stmt *Init = FS->getInit()) {
  4521. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
  4522. if (ESR != ESR_CaseNotFound) {
  4523. assert(ESR != ESR_Succeeded);
  4524. return ESR;
  4525. }
  4526. }
  4527. EvalStmtResult ESR =
  4528. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  4529. if (ESR != ESR_Continue)
  4530. return ESR;
  4531. if (const auto *Inc = FS->getInc()) {
  4532. if (Inc->isValueDependent()) {
  4533. if (!EvaluateDependentExpr(Inc, Info))
  4534. return ESR_Failed;
  4535. } else {
  4536. FullExpressionRAII IncScope(Info);
  4537. if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
  4538. return ESR_Failed;
  4539. }
  4540. }
  4541. break;
  4542. }
  4543. case Stmt::DeclStmtClass: {
  4544. // Start the lifetime of any uninitialized variables we encounter. They
  4545. // might be used by the selected branch of the switch.
  4546. const DeclStmt *DS = cast<DeclStmt>(S);
  4547. for (const auto *D : DS->decls()) {
  4548. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  4549. if (VD->hasLocalStorage() && !VD->getInit())
  4550. if (!EvaluateVarDecl(Info, VD))
  4551. return ESR_Failed;
  4552. // FIXME: If the variable has initialization that can't be jumped
  4553. // over, bail out of any immediately-surrounding compound-statement
  4554. // too. There can't be any case labels here.
  4555. }
  4556. }
  4557. return ESR_CaseNotFound;
  4558. }
  4559. default:
  4560. return ESR_CaseNotFound;
  4561. }
  4562. }
  4563. switch (S->getStmtClass()) {
  4564. default:
  4565. if (const Expr *E = dyn_cast<Expr>(S)) {
  4566. if (E->isValueDependent()) {
  4567. if (!EvaluateDependentExpr(E, Info))
  4568. return ESR_Failed;
  4569. } else {
  4570. // Don't bother evaluating beyond an expression-statement which couldn't
  4571. // be evaluated.
  4572. // FIXME: Do we need the FullExpressionRAII object here?
  4573. // VisitExprWithCleanups should create one when necessary.
  4574. FullExpressionRAII Scope(Info);
  4575. if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
  4576. return ESR_Failed;
  4577. }
  4578. return ESR_Succeeded;
  4579. }
  4580. Info.FFDiag(S->getBeginLoc());
  4581. return ESR_Failed;
  4582. case Stmt::NullStmtClass:
  4583. return ESR_Succeeded;
  4584. case Stmt::DeclStmtClass: {
  4585. const DeclStmt *DS = cast<DeclStmt>(S);
  4586. for (const auto *D : DS->decls()) {
  4587. // Each declaration initialization is its own full-expression.
  4588. FullExpressionRAII Scope(Info);
  4589. if (!EvaluateDecl(Info, D) && !Info.noteFailure())
  4590. return ESR_Failed;
  4591. if (!Scope.destroy())
  4592. return ESR_Failed;
  4593. }
  4594. return ESR_Succeeded;
  4595. }
  4596. case Stmt::ReturnStmtClass: {
  4597. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  4598. FullExpressionRAII Scope(Info);
  4599. if (RetExpr && RetExpr->isValueDependent()) {
  4600. EvaluateDependentExpr(RetExpr, Info);
  4601. // We know we returned, but we don't know what the value is.
  4602. return ESR_Failed;
  4603. }
  4604. if (RetExpr &&
  4605. !(Result.Slot
  4606. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  4607. : Evaluate(Result.Value, Info, RetExpr)))
  4608. return ESR_Failed;
  4609. return Scope.destroy() ? ESR_Returned : ESR_Failed;
  4610. }
  4611. case Stmt::CompoundStmtClass: {
  4612. BlockScopeRAII Scope(Info);
  4613. const CompoundStmt *CS = cast<CompoundStmt>(S);
  4614. for (const auto *BI : CS->body()) {
  4615. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  4616. if (ESR == ESR_Succeeded)
  4617. Case = nullptr;
  4618. else if (ESR != ESR_CaseNotFound) {
  4619. if (ESR != ESR_Failed && !Scope.destroy())
  4620. return ESR_Failed;
  4621. return ESR;
  4622. }
  4623. }
  4624. if (Case)
  4625. return ESR_CaseNotFound;
  4626. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4627. }
  4628. case Stmt::IfStmtClass: {
  4629. const IfStmt *IS = cast<IfStmt>(S);
  4630. // Evaluate the condition, as either a var decl or as an expression.
  4631. BlockScopeRAII Scope(Info);
  4632. if (const Stmt *Init = IS->getInit()) {
  4633. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  4634. if (ESR != ESR_Succeeded) {
  4635. if (ESR != ESR_Failed && !Scope.destroy())
  4636. return ESR_Failed;
  4637. return ESR;
  4638. }
  4639. }
  4640. bool Cond;
  4641. if (IS->isConsteval())
  4642. Cond = IS->isNonNegatedConsteval();
  4643. else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
  4644. Cond))
  4645. return ESR_Failed;
  4646. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  4647. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  4648. if (ESR != ESR_Succeeded) {
  4649. if (ESR != ESR_Failed && !Scope.destroy())
  4650. return ESR_Failed;
  4651. return ESR;
  4652. }
  4653. }
  4654. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4655. }
  4656. case Stmt::WhileStmtClass: {
  4657. const WhileStmt *WS = cast<WhileStmt>(S);
  4658. while (true) {
  4659. BlockScopeRAII Scope(Info);
  4660. bool Continue;
  4661. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  4662. Continue))
  4663. return ESR_Failed;
  4664. if (!Continue)
  4665. break;
  4666. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  4667. if (ESR != ESR_Continue) {
  4668. if (ESR != ESR_Failed && !Scope.destroy())
  4669. return ESR_Failed;
  4670. return ESR;
  4671. }
  4672. if (!Scope.destroy())
  4673. return ESR_Failed;
  4674. }
  4675. return ESR_Succeeded;
  4676. }
  4677. case Stmt::DoStmtClass: {
  4678. const DoStmt *DS = cast<DoStmt>(S);
  4679. bool Continue;
  4680. do {
  4681. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  4682. if (ESR != ESR_Continue)
  4683. return ESR;
  4684. Case = nullptr;
  4685. if (DS->getCond()->isValueDependent()) {
  4686. EvaluateDependentExpr(DS->getCond(), Info);
  4687. // Bailout as we don't know whether to keep going or terminate the loop.
  4688. return ESR_Failed;
  4689. }
  4690. FullExpressionRAII CondScope(Info);
  4691. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
  4692. !CondScope.destroy())
  4693. return ESR_Failed;
  4694. } while (Continue);
  4695. return ESR_Succeeded;
  4696. }
  4697. case Stmt::ForStmtClass: {
  4698. const ForStmt *FS = cast<ForStmt>(S);
  4699. BlockScopeRAII ForScope(Info);
  4700. if (FS->getInit()) {
  4701. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4702. if (ESR != ESR_Succeeded) {
  4703. if (ESR != ESR_Failed && !ForScope.destroy())
  4704. return ESR_Failed;
  4705. return ESR;
  4706. }
  4707. }
  4708. while (true) {
  4709. BlockScopeRAII IterScope(Info);
  4710. bool Continue = true;
  4711. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  4712. FS->getCond(), Continue))
  4713. return ESR_Failed;
  4714. if (!Continue)
  4715. break;
  4716. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4717. if (ESR != ESR_Continue) {
  4718. if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
  4719. return ESR_Failed;
  4720. return ESR;
  4721. }
  4722. if (const auto *Inc = FS->getInc()) {
  4723. if (Inc->isValueDependent()) {
  4724. if (!EvaluateDependentExpr(Inc, Info))
  4725. return ESR_Failed;
  4726. } else {
  4727. FullExpressionRAII IncScope(Info);
  4728. if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
  4729. return ESR_Failed;
  4730. }
  4731. }
  4732. if (!IterScope.destroy())
  4733. return ESR_Failed;
  4734. }
  4735. return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
  4736. }
  4737. case Stmt::CXXForRangeStmtClass: {
  4738. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  4739. BlockScopeRAII Scope(Info);
  4740. // Evaluate the init-statement if present.
  4741. if (FS->getInit()) {
  4742. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  4743. if (ESR != ESR_Succeeded) {
  4744. if (ESR != ESR_Failed && !Scope.destroy())
  4745. return ESR_Failed;
  4746. return ESR;
  4747. }
  4748. }
  4749. // Initialize the __range variable.
  4750. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  4751. if (ESR != ESR_Succeeded) {
  4752. if (ESR != ESR_Failed && !Scope.destroy())
  4753. return ESR_Failed;
  4754. return ESR;
  4755. }
  4756. // In error-recovery cases it's possible to get here even if we failed to
  4757. // synthesize the __begin and __end variables.
  4758. if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
  4759. return ESR_Failed;
  4760. // Create the __begin and __end iterators.
  4761. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  4762. if (ESR != ESR_Succeeded) {
  4763. if (ESR != ESR_Failed && !Scope.destroy())
  4764. return ESR_Failed;
  4765. return ESR;
  4766. }
  4767. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  4768. if (ESR != ESR_Succeeded) {
  4769. if (ESR != ESR_Failed && !Scope.destroy())
  4770. return ESR_Failed;
  4771. return ESR;
  4772. }
  4773. while (true) {
  4774. // Condition: __begin != __end.
  4775. {
  4776. if (FS->getCond()->isValueDependent()) {
  4777. EvaluateDependentExpr(FS->getCond(), Info);
  4778. // We don't know whether to keep going or terminate the loop.
  4779. return ESR_Failed;
  4780. }
  4781. bool Continue = true;
  4782. FullExpressionRAII CondExpr(Info);
  4783. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  4784. return ESR_Failed;
  4785. if (!Continue)
  4786. break;
  4787. }
  4788. // User's variable declaration, initialized by *__begin.
  4789. BlockScopeRAII InnerScope(Info);
  4790. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  4791. if (ESR != ESR_Succeeded) {
  4792. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4793. return ESR_Failed;
  4794. return ESR;
  4795. }
  4796. // Loop body.
  4797. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  4798. if (ESR != ESR_Continue) {
  4799. if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
  4800. return ESR_Failed;
  4801. return ESR;
  4802. }
  4803. if (FS->getInc()->isValueDependent()) {
  4804. if (!EvaluateDependentExpr(FS->getInc(), Info))
  4805. return ESR_Failed;
  4806. } else {
  4807. // Increment: ++__begin
  4808. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  4809. return ESR_Failed;
  4810. }
  4811. if (!InnerScope.destroy())
  4812. return ESR_Failed;
  4813. }
  4814. return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
  4815. }
  4816. case Stmt::SwitchStmtClass:
  4817. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  4818. case Stmt::ContinueStmtClass:
  4819. return ESR_Continue;
  4820. case Stmt::BreakStmtClass:
  4821. return ESR_Break;
  4822. case Stmt::LabelStmtClass:
  4823. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  4824. case Stmt::AttributedStmtClass:
  4825. // As a general principle, C++11 attributes can be ignored without
  4826. // any semantic impact.
  4827. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  4828. Case);
  4829. case Stmt::CaseStmtClass:
  4830. case Stmt::DefaultStmtClass:
  4831. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  4832. case Stmt::CXXTryStmtClass:
  4833. // Evaluate try blocks by evaluating all sub statements.
  4834. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  4835. }
  4836. }
  4837. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  4838. /// default constructor. If so, we'll fold it whether or not it's marked as
  4839. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  4840. /// so we need special handling.
  4841. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4842. const CXXConstructorDecl *CD,
  4843. bool IsValueInitialization) {
  4844. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4845. return false;
  4846. // Value-initialization does not call a trivial default constructor, so such a
  4847. // call is a core constant expression whether or not the constructor is
  4848. // constexpr.
  4849. if (!CD->isConstexpr() && !IsValueInitialization) {
  4850. if (Info.getLangOpts().CPlusPlus11) {
  4851. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4852. // we should be much more explicit about why it's not constexpr.
  4853. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4854. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4855. Info.Note(CD->getLocation(), diag::note_declared_at);
  4856. } else {
  4857. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4858. }
  4859. }
  4860. return true;
  4861. }
  4862. /// CheckConstexprFunction - Check that a function can be called in a constant
  4863. /// expression.
  4864. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4865. const FunctionDecl *Declaration,
  4866. const FunctionDecl *Definition,
  4867. const Stmt *Body) {
  4868. // Potential constant expressions can contain calls to declared, but not yet
  4869. // defined, constexpr functions.
  4870. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4871. Declaration->isConstexpr())
  4872. return false;
  4873. // Bail out if the function declaration itself is invalid. We will
  4874. // have produced a relevant diagnostic while parsing it, so just
  4875. // note the problematic sub-expression.
  4876. if (Declaration->isInvalidDecl()) {
  4877. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4878. return false;
  4879. }
  4880. // DR1872: An instantiated virtual constexpr function can't be called in a
  4881. // constant expression (prior to C++20). We can still constant-fold such a
  4882. // call.
  4883. if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
  4884. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4885. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4886. if (Definition && Definition->isInvalidDecl()) {
  4887. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4888. return false;
  4889. }
  4890. // Can we evaluate this function call?
  4891. if (Definition && Definition->isConstexpr() && Body)
  4892. return true;
  4893. if (Info.getLangOpts().CPlusPlus11) {
  4894. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4895. // If this function is not constexpr because it is an inherited
  4896. // non-constexpr constructor, diagnose that directly.
  4897. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4898. if (CD && CD->isInheritingConstructor()) {
  4899. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4900. if (!Inherited->isConstexpr())
  4901. DiagDecl = CD = Inherited;
  4902. }
  4903. // FIXME: If DiagDecl is an implicitly-declared special member function
  4904. // or an inheriting constructor, we should be much more explicit about why
  4905. // it's not constexpr.
  4906. if (CD && CD->isInheritingConstructor())
  4907. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4908. << CD->getInheritedConstructor().getConstructor()->getParent();
  4909. else
  4910. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4911. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4912. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4913. } else {
  4914. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4915. }
  4916. return false;
  4917. }
  4918. namespace {
  4919. struct CheckDynamicTypeHandler {
  4920. AccessKinds AccessKind;
  4921. typedef bool result_type;
  4922. bool failed() { return false; }
  4923. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4924. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4925. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4926. };
  4927. } // end anonymous namespace
  4928. /// Check that we can access the notional vptr of an object / determine its
  4929. /// dynamic type.
  4930. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4931. AccessKinds AK, bool Polymorphic) {
  4932. if (This.Designator.Invalid)
  4933. return false;
  4934. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4935. if (!Obj)
  4936. return false;
  4937. if (!Obj.Value) {
  4938. // The object is not usable in constant expressions, so we can't inspect
  4939. // its value to see if it's in-lifetime or what the active union members
  4940. // are. We can still check for a one-past-the-end lvalue.
  4941. if (This.Designator.isOnePastTheEnd() ||
  4942. This.Designator.isMostDerivedAnUnsizedArray()) {
  4943. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4944. ? diag::note_constexpr_access_past_end
  4945. : diag::note_constexpr_access_unsized_array)
  4946. << AK;
  4947. return false;
  4948. } else if (Polymorphic) {
  4949. // Conservatively refuse to perform a polymorphic operation if we would
  4950. // not be able to read a notional 'vptr' value.
  4951. APValue Val;
  4952. This.moveInto(Val);
  4953. QualType StarThisType =
  4954. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4955. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4956. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4957. return false;
  4958. }
  4959. return true;
  4960. }
  4961. CheckDynamicTypeHandler Handler{AK};
  4962. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4963. }
  4964. /// Check that the pointee of the 'this' pointer in a member function call is
  4965. /// either within its lifetime or in its period of construction or destruction.
  4966. static bool
  4967. checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4968. const LValue &This,
  4969. const CXXMethodDecl *NamedMember) {
  4970. return checkDynamicType(
  4971. Info, E, This,
  4972. isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
  4973. }
  4974. struct DynamicType {
  4975. /// The dynamic class type of the object.
  4976. const CXXRecordDecl *Type;
  4977. /// The corresponding path length in the lvalue.
  4978. unsigned PathLength;
  4979. };
  4980. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4981. unsigned PathLength) {
  4982. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4983. Designator.Entries.size() && "invalid path length");
  4984. return (PathLength == Designator.MostDerivedPathLength)
  4985. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4986. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4987. }
  4988. /// Determine the dynamic type of an object.
  4989. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4990. LValue &This, AccessKinds AK) {
  4991. // If we don't have an lvalue denoting an object of class type, there is no
  4992. // meaningful dynamic type. (We consider objects of non-class type to have no
  4993. // dynamic type.)
  4994. if (!checkDynamicType(Info, E, This, AK, true))
  4995. return None;
  4996. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4997. // shouldn't happen other than in constant-folding situations, since literal
  4998. // types can't have virtual bases.
  4999. //
  5000. // Note that consumers of DynamicType assume that the type has no virtual
  5001. // bases, and will need modifications if this restriction is relaxed.
  5002. const CXXRecordDecl *Class =
  5003. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  5004. if (!Class || Class->getNumVBases()) {
  5005. Info.FFDiag(E);
  5006. return None;
  5007. }
  5008. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  5009. // binary search here instead. But the overwhelmingly common case is that
  5010. // we're not in the middle of a constructor, so it probably doesn't matter
  5011. // in practice.
  5012. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  5013. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  5014. PathLength <= Path.size(); ++PathLength) {
  5015. switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
  5016. Path.slice(0, PathLength))) {
  5017. case ConstructionPhase::Bases:
  5018. case ConstructionPhase::DestroyingBases:
  5019. // We're constructing or destroying a base class. This is not the dynamic
  5020. // type.
  5021. break;
  5022. case ConstructionPhase::None:
  5023. case ConstructionPhase::AfterBases:
  5024. case ConstructionPhase::AfterFields:
  5025. case ConstructionPhase::Destroying:
  5026. // We've finished constructing the base classes and not yet started
  5027. // destroying them again, so this is the dynamic type.
  5028. return DynamicType{getBaseClassType(This.Designator, PathLength),
  5029. PathLength};
  5030. }
  5031. }
  5032. // CWG issue 1517: we're constructing a base class of the object described by
  5033. // 'This', so that object has not yet begun its period of construction and
  5034. // any polymorphic operation on it results in undefined behavior.
  5035. Info.FFDiag(E);
  5036. return None;
  5037. }
  5038. /// Perform virtual dispatch.
  5039. static const CXXMethodDecl *HandleVirtualDispatch(
  5040. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  5041. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  5042. Optional<DynamicType> DynType = ComputeDynamicType(
  5043. Info, E, This,
  5044. isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
  5045. if (!DynType)
  5046. return nullptr;
  5047. // Find the final overrider. It must be declared in one of the classes on the
  5048. // path from the dynamic type to the static type.
  5049. // FIXME: If we ever allow literal types to have virtual base classes, that
  5050. // won't be true.
  5051. const CXXMethodDecl *Callee = Found;
  5052. unsigned PathLength = DynType->PathLength;
  5053. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  5054. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  5055. const CXXMethodDecl *Overrider =
  5056. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  5057. if (Overrider) {
  5058. Callee = Overrider;
  5059. break;
  5060. }
  5061. }
  5062. // C++2a [class.abstract]p6:
  5063. // the effect of making a virtual call to a pure virtual function [...] is
  5064. // undefined
  5065. if (Callee->isPure()) {
  5066. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  5067. Info.Note(Callee->getLocation(), diag::note_declared_at);
  5068. return nullptr;
  5069. }
  5070. // If necessary, walk the rest of the path to determine the sequence of
  5071. // covariant adjustment steps to apply.
  5072. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  5073. Found->getReturnType())) {
  5074. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  5075. for (unsigned CovariantPathLength = PathLength + 1;
  5076. CovariantPathLength != This.Designator.Entries.size();
  5077. ++CovariantPathLength) {
  5078. const CXXRecordDecl *NextClass =
  5079. getBaseClassType(This.Designator, CovariantPathLength);
  5080. const CXXMethodDecl *Next =
  5081. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  5082. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  5083. Next->getReturnType(), CovariantAdjustmentPath.back()))
  5084. CovariantAdjustmentPath.push_back(Next->getReturnType());
  5085. }
  5086. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  5087. CovariantAdjustmentPath.back()))
  5088. CovariantAdjustmentPath.push_back(Found->getReturnType());
  5089. }
  5090. // Perform 'this' adjustment.
  5091. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  5092. return nullptr;
  5093. return Callee;
  5094. }
  5095. /// Perform the adjustment from a value returned by a virtual function to
  5096. /// a value of the statically expected type, which may be a pointer or
  5097. /// reference to a base class of the returned type.
  5098. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  5099. APValue &Result,
  5100. ArrayRef<QualType> Path) {
  5101. assert(Result.isLValue() &&
  5102. "unexpected kind of APValue for covariant return");
  5103. if (Result.isNullPointer())
  5104. return true;
  5105. LValue LVal;
  5106. LVal.setFrom(Info.Ctx, Result);
  5107. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  5108. for (unsigned I = 1; I != Path.size(); ++I) {
  5109. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  5110. assert(OldClass && NewClass && "unexpected kind of covariant return");
  5111. if (OldClass != NewClass &&
  5112. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  5113. return false;
  5114. OldClass = NewClass;
  5115. }
  5116. LVal.moveInto(Result);
  5117. return true;
  5118. }
  5119. /// Determine whether \p Base, which is known to be a direct base class of
  5120. /// \p Derived, is a public base class.
  5121. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  5122. const CXXRecordDecl *Base) {
  5123. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  5124. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  5125. if (BaseClass && declaresSameEntity(BaseClass, Base))
  5126. return BaseSpec.getAccessSpecifier() == AS_public;
  5127. }
  5128. llvm_unreachable("Base is not a direct base of Derived");
  5129. }
  5130. /// Apply the given dynamic cast operation on the provided lvalue.
  5131. ///
  5132. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  5133. /// to find a suitable target subobject.
  5134. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  5135. LValue &Ptr) {
  5136. // We can't do anything with a non-symbolic pointer value.
  5137. SubobjectDesignator &D = Ptr.Designator;
  5138. if (D.Invalid)
  5139. return false;
  5140. // C++ [expr.dynamic.cast]p6:
  5141. // If v is a null pointer value, the result is a null pointer value.
  5142. if (Ptr.isNullPointer() && !E->isGLValue())
  5143. return true;
  5144. // For all the other cases, we need the pointer to point to an object within
  5145. // its lifetime / period of construction / destruction, and we need to know
  5146. // its dynamic type.
  5147. Optional<DynamicType> DynType =
  5148. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  5149. if (!DynType)
  5150. return false;
  5151. // C++ [expr.dynamic.cast]p7:
  5152. // If T is "pointer to cv void", then the result is a pointer to the most
  5153. // derived object
  5154. if (E->getType()->isVoidPointerType())
  5155. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  5156. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  5157. assert(C && "dynamic_cast target is not void pointer nor class");
  5158. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  5159. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  5160. // C++ [expr.dynamic.cast]p9:
  5161. if (!E->isGLValue()) {
  5162. // The value of a failed cast to pointer type is the null pointer value
  5163. // of the required result type.
  5164. Ptr.setNull(Info.Ctx, E->getType());
  5165. return true;
  5166. }
  5167. // A failed cast to reference type throws [...] std::bad_cast.
  5168. unsigned DiagKind;
  5169. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  5170. DynType->Type->isDerivedFrom(C)))
  5171. DiagKind = 0;
  5172. else if (!Paths || Paths->begin() == Paths->end())
  5173. DiagKind = 1;
  5174. else if (Paths->isAmbiguous(CQT))
  5175. DiagKind = 2;
  5176. else {
  5177. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  5178. DiagKind = 3;
  5179. }
  5180. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  5181. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  5182. << Info.Ctx.getRecordType(DynType->Type)
  5183. << E->getType().getUnqualifiedType();
  5184. return false;
  5185. };
  5186. // Runtime check, phase 1:
  5187. // Walk from the base subobject towards the derived object looking for the
  5188. // target type.
  5189. for (int PathLength = Ptr.Designator.Entries.size();
  5190. PathLength >= (int)DynType->PathLength; --PathLength) {
  5191. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  5192. if (declaresSameEntity(Class, C))
  5193. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  5194. // We can only walk across public inheritance edges.
  5195. if (PathLength > (int)DynType->PathLength &&
  5196. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  5197. Class))
  5198. return RuntimeCheckFailed(nullptr);
  5199. }
  5200. // Runtime check, phase 2:
  5201. // Search the dynamic type for an unambiguous public base of type C.
  5202. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  5203. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  5204. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  5205. Paths.front().Access == AS_public) {
  5206. // Downcast to the dynamic type...
  5207. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  5208. return false;
  5209. // ... then upcast to the chosen base class subobject.
  5210. for (CXXBasePathElement &Elem : Paths.front())
  5211. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  5212. return false;
  5213. return true;
  5214. }
  5215. // Otherwise, the runtime check fails.
  5216. return RuntimeCheckFailed(&Paths);
  5217. }
  5218. namespace {
  5219. struct StartLifetimeOfUnionMemberHandler {
  5220. EvalInfo &Info;
  5221. const Expr *LHSExpr;
  5222. const FieldDecl *Field;
  5223. bool DuringInit;
  5224. bool Failed = false;
  5225. static const AccessKinds AccessKind = AK_Assign;
  5226. typedef bool result_type;
  5227. bool failed() { return Failed; }
  5228. bool found(APValue &Subobj, QualType SubobjType) {
  5229. // We are supposed to perform no initialization but begin the lifetime of
  5230. // the object. We interpret that as meaning to do what default
  5231. // initialization of the object would do if all constructors involved were
  5232. // trivial:
  5233. // * All base, non-variant member, and array element subobjects' lifetimes
  5234. // begin
  5235. // * No variant members' lifetimes begin
  5236. // * All scalar subobjects whose lifetimes begin have indeterminate values
  5237. assert(SubobjType->isUnionType());
  5238. if (declaresSameEntity(Subobj.getUnionField(), Field)) {
  5239. // This union member is already active. If it's also in-lifetime, there's
  5240. // nothing to do.
  5241. if (Subobj.getUnionValue().hasValue())
  5242. return true;
  5243. } else if (DuringInit) {
  5244. // We're currently in the process of initializing a different union
  5245. // member. If we carried on, that initialization would attempt to
  5246. // store to an inactive union member, resulting in undefined behavior.
  5247. Info.FFDiag(LHSExpr,
  5248. diag::note_constexpr_union_member_change_during_init);
  5249. return false;
  5250. }
  5251. APValue Result;
  5252. Failed = !getDefaultInitValue(Field->getType(), Result);
  5253. Subobj.setUnion(Field, Result);
  5254. return true;
  5255. }
  5256. bool found(APSInt &Value, QualType SubobjType) {
  5257. llvm_unreachable("wrong value kind for union object");
  5258. }
  5259. bool found(APFloat &Value, QualType SubobjType) {
  5260. llvm_unreachable("wrong value kind for union object");
  5261. }
  5262. };
  5263. } // end anonymous namespace
  5264. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  5265. /// Handle a builtin simple-assignment or a call to a trivial assignment
  5266. /// operator whose left-hand side might involve a union member access. If it
  5267. /// does, implicitly start the lifetime of any accessed union elements per
  5268. /// C++20 [class.union]5.
  5269. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  5270. const LValue &LHS) {
  5271. if (LHS.InvalidBase || LHS.Designator.Invalid)
  5272. return false;
  5273. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  5274. // C++ [class.union]p5:
  5275. // define the set S(E) of subexpressions of E as follows:
  5276. unsigned PathLength = LHS.Designator.Entries.size();
  5277. for (const Expr *E = LHSExpr; E != nullptr;) {
  5278. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  5279. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  5280. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  5281. // Note that we can't implicitly start the lifetime of a reference,
  5282. // so we don't need to proceed any further if we reach one.
  5283. if (!FD || FD->getType()->isReferenceType())
  5284. break;
  5285. // ... and also contains A.B if B names a union member ...
  5286. if (FD->getParent()->isUnion()) {
  5287. // ... of a non-class, non-array type, or of a class type with a
  5288. // trivial default constructor that is not deleted, or an array of
  5289. // such types.
  5290. auto *RD =
  5291. FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  5292. if (!RD || RD->hasTrivialDefaultConstructor())
  5293. UnionPathLengths.push_back({PathLength - 1, FD});
  5294. }
  5295. E = ME->getBase();
  5296. --PathLength;
  5297. assert(declaresSameEntity(FD,
  5298. LHS.Designator.Entries[PathLength]
  5299. .getAsBaseOrMember().getPointer()));
  5300. // -- If E is of the form A[B] and is interpreted as a built-in array
  5301. // subscripting operator, S(E) is [S(the array operand, if any)].
  5302. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  5303. // Step over an ArrayToPointerDecay implicit cast.
  5304. auto *Base = ASE->getBase()->IgnoreImplicit();
  5305. if (!Base->getType()->isArrayType())
  5306. break;
  5307. E = Base;
  5308. --PathLength;
  5309. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5310. // Step over a derived-to-base conversion.
  5311. E = ICE->getSubExpr();
  5312. if (ICE->getCastKind() == CK_NoOp)
  5313. continue;
  5314. if (ICE->getCastKind() != CK_DerivedToBase &&
  5315. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  5316. break;
  5317. // Walk path backwards as we walk up from the base to the derived class.
  5318. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  5319. --PathLength;
  5320. (void)Elt;
  5321. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  5322. LHS.Designator.Entries[PathLength]
  5323. .getAsBaseOrMember().getPointer()));
  5324. }
  5325. // -- Otherwise, S(E) is empty.
  5326. } else {
  5327. break;
  5328. }
  5329. }
  5330. // Common case: no unions' lifetimes are started.
  5331. if (UnionPathLengths.empty())
  5332. return true;
  5333. // if modification of X [would access an inactive union member], an object
  5334. // of the type of X is implicitly created
  5335. CompleteObject Obj =
  5336. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  5337. if (!Obj)
  5338. return false;
  5339. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  5340. llvm::reverse(UnionPathLengths)) {
  5341. // Form a designator for the union object.
  5342. SubobjectDesignator D = LHS.Designator;
  5343. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  5344. bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
  5345. ConstructionPhase::AfterBases;
  5346. StartLifetimeOfUnionMemberHandler StartLifetime{
  5347. Info, LHSExpr, LengthAndField.second, DuringInit};
  5348. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  5349. return false;
  5350. }
  5351. return true;
  5352. }
  5353. static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
  5354. CallRef Call, EvalInfo &Info,
  5355. bool NonNull = false) {
  5356. LValue LV;
  5357. // Create the parameter slot and register its destruction. For a vararg
  5358. // argument, create a temporary.
  5359. // FIXME: For calling conventions that destroy parameters in the callee,
  5360. // should we consider performing destruction when the function returns
  5361. // instead?
  5362. APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
  5363. : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
  5364. ScopeKind::Call, LV);
  5365. if (!EvaluateInPlace(V, Info, LV, Arg))
  5366. return false;
  5367. // Passing a null pointer to an __attribute__((nonnull)) parameter results in
  5368. // undefined behavior, so is non-constant.
  5369. if (NonNull && V.isLValue() && V.isNullPointer()) {
  5370. Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
  5371. return false;
  5372. }
  5373. return true;
  5374. }
  5375. /// Evaluate the arguments to a function call.
  5376. static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
  5377. EvalInfo &Info, const FunctionDecl *Callee,
  5378. bool RightToLeft = false) {
  5379. bool Success = true;
  5380. llvm::SmallBitVector ForbiddenNullArgs;
  5381. if (Callee->hasAttr<NonNullAttr>()) {
  5382. ForbiddenNullArgs.resize(Args.size());
  5383. for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
  5384. if (!Attr->args_size()) {
  5385. ForbiddenNullArgs.set();
  5386. break;
  5387. } else
  5388. for (auto Idx : Attr->args()) {
  5389. unsigned ASTIdx = Idx.getASTIndex();
  5390. if (ASTIdx >= Args.size())
  5391. continue;
  5392. ForbiddenNullArgs[ASTIdx] = true;
  5393. }
  5394. }
  5395. }
  5396. for (unsigned I = 0; I < Args.size(); I++) {
  5397. unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
  5398. const ParmVarDecl *PVD =
  5399. Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
  5400. bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
  5401. if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
  5402. // If we're checking for a potential constant expression, evaluate all
  5403. // initializers even if some of them fail.
  5404. if (!Info.noteFailure())
  5405. return false;
  5406. Success = false;
  5407. }
  5408. }
  5409. return Success;
  5410. }
  5411. /// Perform a trivial copy from Param, which is the parameter of a copy or move
  5412. /// constructor or assignment operator.
  5413. static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
  5414. const Expr *E, APValue &Result,
  5415. bool CopyObjectRepresentation) {
  5416. // Find the reference argument.
  5417. CallStackFrame *Frame = Info.CurrentCall;
  5418. APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
  5419. if (!RefValue) {
  5420. Info.FFDiag(E);
  5421. return false;
  5422. }
  5423. // Copy out the contents of the RHS object.
  5424. LValue RefLValue;
  5425. RefLValue.setFrom(Info.Ctx, *RefValue);
  5426. return handleLValueToRValueConversion(
  5427. Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
  5428. CopyObjectRepresentation);
  5429. }
  5430. /// Evaluate a function call.
  5431. static bool HandleFunctionCall(SourceLocation CallLoc,
  5432. const FunctionDecl *Callee, const LValue *This,
  5433. ArrayRef<const Expr *> Args, CallRef Call,
  5434. const Stmt *Body, EvalInfo &Info,
  5435. APValue &Result, const LValue *ResultSlot) {
  5436. if (!Info.CheckCallLimit(CallLoc))
  5437. return false;
  5438. CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
  5439. // For a trivial copy or move assignment, perform an APValue copy. This is
  5440. // essential for unions, where the operations performed by the assignment
  5441. // operator cannot be represented as statements.
  5442. //
  5443. // Skip this for non-union classes with no fields; in that case, the defaulted
  5444. // copy/move does not actually read the object.
  5445. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  5446. if (MD && MD->isDefaulted() &&
  5447. (MD->getParent()->isUnion() ||
  5448. (MD->isTrivial() &&
  5449. isReadByLvalueToRvalueConversion(MD->getParent())))) {
  5450. assert(This &&
  5451. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  5452. APValue RHSValue;
  5453. if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
  5454. MD->getParent()->isUnion()))
  5455. return false;
  5456. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  5457. RHSValue))
  5458. return false;
  5459. This->moveInto(Result);
  5460. return true;
  5461. } else if (MD && isLambdaCallOperator(MD)) {
  5462. // We're in a lambda; determine the lambda capture field maps unless we're
  5463. // just constexpr checking a lambda's call operator. constexpr checking is
  5464. // done before the captures have been added to the closure object (unless
  5465. // we're inferring constexpr-ness), so we don't have access to them in this
  5466. // case. But since we don't need the captures to constexpr check, we can
  5467. // just ignore them.
  5468. if (!Info.checkingPotentialConstantExpression())
  5469. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  5470. Frame.LambdaThisCaptureField);
  5471. }
  5472. StmtResult Ret = {Result, ResultSlot};
  5473. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  5474. if (ESR == ESR_Succeeded) {
  5475. if (Callee->getReturnType()->isVoidType())
  5476. return true;
  5477. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  5478. }
  5479. return ESR == ESR_Returned;
  5480. }
  5481. /// Evaluate a constructor call.
  5482. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  5483. CallRef Call,
  5484. const CXXConstructorDecl *Definition,
  5485. EvalInfo &Info, APValue &Result) {
  5486. SourceLocation CallLoc = E->getExprLoc();
  5487. if (!Info.CheckCallLimit(CallLoc))
  5488. return false;
  5489. const CXXRecordDecl *RD = Definition->getParent();
  5490. if (RD->getNumVBases()) {
  5491. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5492. return false;
  5493. }
  5494. EvalInfo::EvaluatingConstructorRAII EvalObj(
  5495. Info,
  5496. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  5497. RD->getNumBases());
  5498. CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
  5499. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5500. // wasteful.
  5501. APValue RetVal;
  5502. StmtResult Ret = {RetVal, nullptr};
  5503. // If it's a delegating constructor, delegate.
  5504. if (Definition->isDelegatingConstructor()) {
  5505. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  5506. if ((*I)->getInit()->isValueDependent()) {
  5507. if (!EvaluateDependentExpr((*I)->getInit(), Info))
  5508. return false;
  5509. } else {
  5510. FullExpressionRAII InitScope(Info);
  5511. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
  5512. !InitScope.destroy())
  5513. return false;
  5514. }
  5515. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  5516. }
  5517. // For a trivial copy or move constructor, perform an APValue copy. This is
  5518. // essential for unions (or classes with anonymous union members), where the
  5519. // operations performed by the constructor cannot be represented by
  5520. // ctor-initializers.
  5521. //
  5522. // Skip this for empty non-union classes; we should not perform an
  5523. // lvalue-to-rvalue conversion on them because their copy constructor does not
  5524. // actually read them.
  5525. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  5526. (Definition->getParent()->isUnion() ||
  5527. (Definition->isTrivial() &&
  5528. isReadByLvalueToRvalueConversion(Definition->getParent())))) {
  5529. return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
  5530. Definition->getParent()->isUnion());
  5531. }
  5532. // Reserve space for the struct members.
  5533. if (!Result.hasValue()) {
  5534. if (!RD->isUnion())
  5535. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  5536. std::distance(RD->field_begin(), RD->field_end()));
  5537. else
  5538. // A union starts with no active member.
  5539. Result = APValue((const FieldDecl*)nullptr);
  5540. }
  5541. if (RD->isInvalidDecl()) return false;
  5542. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5543. // A scope for temporaries lifetime-extended by reference members.
  5544. BlockScopeRAII LifetimeExtendedScope(Info);
  5545. bool Success = true;
  5546. unsigned BasesSeen = 0;
  5547. #ifndef NDEBUG
  5548. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  5549. #endif
  5550. CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
  5551. auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
  5552. // We might be initializing the same field again if this is an indirect
  5553. // field initialization.
  5554. if (FieldIt == RD->field_end() ||
  5555. FieldIt->getFieldIndex() > FD->getFieldIndex()) {
  5556. assert(Indirect && "fields out of order?");
  5557. return;
  5558. }
  5559. // Default-initialize any fields with no explicit initializer.
  5560. for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
  5561. assert(FieldIt != RD->field_end() && "missing field?");
  5562. if (!FieldIt->isUnnamedBitfield())
  5563. Success &= getDefaultInitValue(
  5564. FieldIt->getType(),
  5565. Result.getStructField(FieldIt->getFieldIndex()));
  5566. }
  5567. ++FieldIt;
  5568. };
  5569. for (const auto *I : Definition->inits()) {
  5570. LValue Subobject = This;
  5571. LValue SubobjectParent = This;
  5572. APValue *Value = &Result;
  5573. // Determine the subobject to initialize.
  5574. FieldDecl *FD = nullptr;
  5575. if (I->isBaseInitializer()) {
  5576. QualType BaseType(I->getBaseClass(), 0);
  5577. #ifndef NDEBUG
  5578. // Non-virtual base classes are initialized in the order in the class
  5579. // definition. We have already checked for virtual base classes.
  5580. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  5581. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  5582. "base class initializers not in expected order");
  5583. ++BaseIt;
  5584. #endif
  5585. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  5586. BaseType->getAsCXXRecordDecl(), &Layout))
  5587. return false;
  5588. Value = &Result.getStructBase(BasesSeen++);
  5589. } else if ((FD = I->getMember())) {
  5590. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  5591. return false;
  5592. if (RD->isUnion()) {
  5593. Result = APValue(FD);
  5594. Value = &Result.getUnionValue();
  5595. } else {
  5596. SkipToField(FD, false);
  5597. Value = &Result.getStructField(FD->getFieldIndex());
  5598. }
  5599. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  5600. // Walk the indirect field decl's chain to find the object to initialize,
  5601. // and make sure we've initialized every step along it.
  5602. auto IndirectFieldChain = IFD->chain();
  5603. for (auto *C : IndirectFieldChain) {
  5604. FD = cast<FieldDecl>(C);
  5605. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  5606. // Switch the union field if it differs. This happens if we had
  5607. // preceding zero-initialization, and we're now initializing a union
  5608. // subobject other than the first.
  5609. // FIXME: In this case, the values of the other subobjects are
  5610. // specified, since zero-initialization sets all padding bits to zero.
  5611. if (!Value->hasValue() ||
  5612. (Value->isUnion() && Value->getUnionField() != FD)) {
  5613. if (CD->isUnion())
  5614. *Value = APValue(FD);
  5615. else
  5616. // FIXME: This immediately starts the lifetime of all members of
  5617. // an anonymous struct. It would be preferable to strictly start
  5618. // member lifetime in initialization order.
  5619. Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
  5620. }
  5621. // Store Subobject as its parent before updating it for the last element
  5622. // in the chain.
  5623. if (C == IndirectFieldChain.back())
  5624. SubobjectParent = Subobject;
  5625. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  5626. return false;
  5627. if (CD->isUnion())
  5628. Value = &Value->getUnionValue();
  5629. else {
  5630. if (C == IndirectFieldChain.front() && !RD->isUnion())
  5631. SkipToField(FD, true);
  5632. Value = &Value->getStructField(FD->getFieldIndex());
  5633. }
  5634. }
  5635. } else {
  5636. llvm_unreachable("unknown base initializer kind");
  5637. }
  5638. // Need to override This for implicit field initializers as in this case
  5639. // This refers to innermost anonymous struct/union containing initializer,
  5640. // not to currently constructed class.
  5641. const Expr *Init = I->getInit();
  5642. if (Init->isValueDependent()) {
  5643. if (!EvaluateDependentExpr(Init, Info))
  5644. return false;
  5645. } else {
  5646. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  5647. isa<CXXDefaultInitExpr>(Init));
  5648. FullExpressionRAII InitScope(Info);
  5649. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  5650. (FD && FD->isBitField() &&
  5651. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  5652. // If we're checking for a potential constant expression, evaluate all
  5653. // initializers even if some of them fail.
  5654. if (!Info.noteFailure())
  5655. return false;
  5656. Success = false;
  5657. }
  5658. }
  5659. // This is the point at which the dynamic type of the object becomes this
  5660. // class type.
  5661. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  5662. EvalObj.finishedConstructingBases();
  5663. }
  5664. // Default-initialize any remaining fields.
  5665. if (!RD->isUnion()) {
  5666. for (; FieldIt != RD->field_end(); ++FieldIt) {
  5667. if (!FieldIt->isUnnamedBitfield())
  5668. Success &= getDefaultInitValue(
  5669. FieldIt->getType(),
  5670. Result.getStructField(FieldIt->getFieldIndex()));
  5671. }
  5672. }
  5673. EvalObj.finishedConstructingFields();
  5674. return Success &&
  5675. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
  5676. LifetimeExtendedScope.destroy();
  5677. }
  5678. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  5679. ArrayRef<const Expr*> Args,
  5680. const CXXConstructorDecl *Definition,
  5681. EvalInfo &Info, APValue &Result) {
  5682. CallScopeRAII CallScope(Info);
  5683. CallRef Call = Info.CurrentCall->createCall(Definition);
  5684. if (!EvaluateArgs(Args, Call, Info, Definition))
  5685. return false;
  5686. return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
  5687. CallScope.destroy();
  5688. }
  5689. static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
  5690. const LValue &This, APValue &Value,
  5691. QualType T) {
  5692. // Objects can only be destroyed while they're within their lifetimes.
  5693. // FIXME: We have no representation for whether an object of type nullptr_t
  5694. // is in its lifetime; it usually doesn't matter. Perhaps we should model it
  5695. // as indeterminate instead?
  5696. if (Value.isAbsent() && !T->isNullPtrType()) {
  5697. APValue Printable;
  5698. This.moveInto(Printable);
  5699. Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
  5700. << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
  5701. return false;
  5702. }
  5703. // Invent an expression for location purposes.
  5704. // FIXME: We shouldn't need to do this.
  5705. OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
  5706. // For arrays, destroy elements right-to-left.
  5707. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
  5708. uint64_t Size = CAT->getSize().getZExtValue();
  5709. QualType ElemT = CAT->getElementType();
  5710. LValue ElemLV = This;
  5711. ElemLV.addArray(Info, &LocE, CAT);
  5712. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
  5713. return false;
  5714. // Ensure that we have actual array elements available to destroy; the
  5715. // destructors might mutate the value, so we can't run them on the array
  5716. // filler.
  5717. if (Size && Size > Value.getArrayInitializedElts())
  5718. expandArray(Value, Value.getArraySize() - 1);
  5719. for (; Size != 0; --Size) {
  5720. APValue &Elem = Value.getArrayInitializedElt(Size - 1);
  5721. if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
  5722. !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
  5723. return false;
  5724. }
  5725. // End the lifetime of this array now.
  5726. Value = APValue();
  5727. return true;
  5728. }
  5729. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  5730. if (!RD) {
  5731. if (T.isDestructedType()) {
  5732. Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
  5733. return false;
  5734. }
  5735. Value = APValue();
  5736. return true;
  5737. }
  5738. if (RD->getNumVBases()) {
  5739. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  5740. return false;
  5741. }
  5742. const CXXDestructorDecl *DD = RD->getDestructor();
  5743. if (!DD && !RD->hasTrivialDestructor()) {
  5744. Info.FFDiag(CallLoc);
  5745. return false;
  5746. }
  5747. if (!DD || DD->isTrivial() ||
  5748. (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
  5749. // A trivial destructor just ends the lifetime of the object. Check for
  5750. // this case before checking for a body, because we might not bother
  5751. // building a body for a trivial destructor. Note that it doesn't matter
  5752. // whether the destructor is constexpr in this case; all trivial
  5753. // destructors are constexpr.
  5754. //
  5755. // If an anonymous union would be destroyed, some enclosing destructor must
  5756. // have been explicitly defined, and the anonymous union destruction should
  5757. // have no effect.
  5758. Value = APValue();
  5759. return true;
  5760. }
  5761. if (!Info.CheckCallLimit(CallLoc))
  5762. return false;
  5763. const FunctionDecl *Definition = nullptr;
  5764. const Stmt *Body = DD->getBody(Definition);
  5765. if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
  5766. return false;
  5767. CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
  5768. // We're now in the period of destruction of this object.
  5769. unsigned BasesLeft = RD->getNumBases();
  5770. EvalInfo::EvaluatingDestructorRAII EvalObj(
  5771. Info,
  5772. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
  5773. if (!EvalObj.DidInsert) {
  5774. // C++2a [class.dtor]p19:
  5775. // the behavior is undefined if the destructor is invoked for an object
  5776. // whose lifetime has ended
  5777. // (Note that formally the lifetime ends when the period of destruction
  5778. // begins, even though certain uses of the object remain valid until the
  5779. // period of destruction ends.)
  5780. Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
  5781. return false;
  5782. }
  5783. // FIXME: Creating an APValue just to hold a nonexistent return value is
  5784. // wasteful.
  5785. APValue RetVal;
  5786. StmtResult Ret = {RetVal, nullptr};
  5787. if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
  5788. return false;
  5789. // A union destructor does not implicitly destroy its members.
  5790. if (RD->isUnion())
  5791. return true;
  5792. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5793. // We don't have a good way to iterate fields in reverse, so collect all the
  5794. // fields first and then walk them backwards.
  5795. SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
  5796. for (const FieldDecl *FD : llvm::reverse(Fields)) {
  5797. if (FD->isUnnamedBitfield())
  5798. continue;
  5799. LValue Subobject = This;
  5800. if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
  5801. return false;
  5802. APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
  5803. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5804. FD->getType()))
  5805. return false;
  5806. }
  5807. if (BasesLeft != 0)
  5808. EvalObj.startedDestroyingBases();
  5809. // Destroy base classes in reverse order.
  5810. for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
  5811. --BasesLeft;
  5812. QualType BaseType = Base.getType();
  5813. LValue Subobject = This;
  5814. if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
  5815. BaseType->getAsCXXRecordDecl(), &Layout))
  5816. return false;
  5817. APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
  5818. if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
  5819. BaseType))
  5820. return false;
  5821. }
  5822. assert(BasesLeft == 0 && "NumBases was wrong?");
  5823. // The period of destruction ends now. The object is gone.
  5824. Value = APValue();
  5825. return true;
  5826. }
  5827. namespace {
  5828. struct DestroyObjectHandler {
  5829. EvalInfo &Info;
  5830. const Expr *E;
  5831. const LValue &This;
  5832. const AccessKinds AccessKind;
  5833. typedef bool result_type;
  5834. bool failed() { return false; }
  5835. bool found(APValue &Subobj, QualType SubobjType) {
  5836. return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
  5837. SubobjType);
  5838. }
  5839. bool found(APSInt &Value, QualType SubobjType) {
  5840. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5841. return false;
  5842. }
  5843. bool found(APFloat &Value, QualType SubobjType) {
  5844. Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
  5845. return false;
  5846. }
  5847. };
  5848. }
  5849. /// Perform a destructor or pseudo-destructor call on the given object, which
  5850. /// might in general not be a complete object.
  5851. static bool HandleDestruction(EvalInfo &Info, const Expr *E,
  5852. const LValue &This, QualType ThisType) {
  5853. CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
  5854. DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
  5855. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  5856. }
  5857. /// Destroy and end the lifetime of the given complete object.
  5858. static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
  5859. APValue::LValueBase LVBase, APValue &Value,
  5860. QualType T) {
  5861. // If we've had an unmodeled side-effect, we can't rely on mutable state
  5862. // (such as the object we're about to destroy) being correct.
  5863. if (Info.EvalStatus.HasSideEffects)
  5864. return false;
  5865. LValue LV;
  5866. LV.set({LVBase});
  5867. return HandleDestructionImpl(Info, Loc, LV, Value, T);
  5868. }
  5869. /// Perform a call to 'perator new' or to `__builtin_operator_new'.
  5870. static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
  5871. LValue &Result) {
  5872. if (Info.checkingPotentialConstantExpression() ||
  5873. Info.SpeculativeEvaluationDepth)
  5874. return false;
  5875. // This is permitted only within a call to std::allocator<T>::allocate.
  5876. auto Caller = Info.getStdAllocatorCaller("allocate");
  5877. if (!Caller) {
  5878. Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
  5879. ? diag::note_constexpr_new_untyped
  5880. : diag::note_constexpr_new);
  5881. return false;
  5882. }
  5883. QualType ElemType = Caller.ElemType;
  5884. if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
  5885. Info.FFDiag(E->getExprLoc(),
  5886. diag::note_constexpr_new_not_complete_object_type)
  5887. << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
  5888. return false;
  5889. }
  5890. APSInt ByteSize;
  5891. if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
  5892. return false;
  5893. bool IsNothrow = false;
  5894. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
  5895. EvaluateIgnoredValue(Info, E->getArg(I));
  5896. IsNothrow |= E->getType()->isNothrowT();
  5897. }
  5898. CharUnits ElemSize;
  5899. if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
  5900. return false;
  5901. APInt Size, Remainder;
  5902. APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
  5903. APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
  5904. if (Remainder != 0) {
  5905. // This likely indicates a bug in the implementation of 'std::allocator'.
  5906. Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
  5907. << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
  5908. return false;
  5909. }
  5910. if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  5911. if (IsNothrow) {
  5912. Result.setNull(Info.Ctx, E->getType());
  5913. return true;
  5914. }
  5915. Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
  5916. return false;
  5917. }
  5918. QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
  5919. ArrayType::Normal, 0);
  5920. APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
  5921. *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
  5922. Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
  5923. return true;
  5924. }
  5925. static bool hasVirtualDestructor(QualType T) {
  5926. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  5927. if (CXXDestructorDecl *DD = RD->getDestructor())
  5928. return DD->isVirtual();
  5929. return false;
  5930. }
  5931. static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
  5932. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  5933. if (CXXDestructorDecl *DD = RD->getDestructor())
  5934. return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
  5935. return nullptr;
  5936. }
  5937. /// Check that the given object is a suitable pointer to a heap allocation that
  5938. /// still exists and is of the right kind for the purpose of a deletion.
  5939. ///
  5940. /// On success, returns the heap allocation to deallocate. On failure, produces
  5941. /// a diagnostic and returns None.
  5942. static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
  5943. const LValue &Pointer,
  5944. DynAlloc::Kind DeallocKind) {
  5945. auto PointerAsString = [&] {
  5946. return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
  5947. };
  5948. DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
  5949. if (!DA) {
  5950. Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
  5951. << PointerAsString();
  5952. if (Pointer.Base)
  5953. NoteLValueLocation(Info, Pointer.Base);
  5954. return None;
  5955. }
  5956. Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
  5957. if (!Alloc) {
  5958. Info.FFDiag(E, diag::note_constexpr_double_delete);
  5959. return None;
  5960. }
  5961. QualType AllocType = Pointer.Base.getDynamicAllocType();
  5962. if (DeallocKind != (*Alloc)->getKind()) {
  5963. Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
  5964. << DeallocKind << (*Alloc)->getKind() << AllocType;
  5965. NoteLValueLocation(Info, Pointer.Base);
  5966. return None;
  5967. }
  5968. bool Subobject = false;
  5969. if (DeallocKind == DynAlloc::New) {
  5970. Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
  5971. Pointer.Designator.isOnePastTheEnd();
  5972. } else {
  5973. Subobject = Pointer.Designator.Entries.size() != 1 ||
  5974. Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
  5975. }
  5976. if (Subobject) {
  5977. Info.FFDiag(E, diag::note_constexpr_delete_subobject)
  5978. << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
  5979. return None;
  5980. }
  5981. return Alloc;
  5982. }
  5983. // Perform a call to 'operator delete' or '__builtin_operator_delete'.
  5984. bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
  5985. if (Info.checkingPotentialConstantExpression() ||
  5986. Info.SpeculativeEvaluationDepth)
  5987. return false;
  5988. // This is permitted only within a call to std::allocator<T>::deallocate.
  5989. if (!Info.getStdAllocatorCaller("deallocate")) {
  5990. Info.FFDiag(E->getExprLoc());
  5991. return true;
  5992. }
  5993. LValue Pointer;
  5994. if (!EvaluatePointer(E->getArg(0), Pointer, Info))
  5995. return false;
  5996. for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
  5997. EvaluateIgnoredValue(Info, E->getArg(I));
  5998. if (Pointer.Designator.Invalid)
  5999. return false;
  6000. // Deleting a null pointer would have no effect, but it's not permitted by
  6001. // std::allocator<T>::deallocate's contract.
  6002. if (Pointer.isNullPointer()) {
  6003. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
  6004. return true;
  6005. }
  6006. if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
  6007. return false;
  6008. Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
  6009. return true;
  6010. }
  6011. //===----------------------------------------------------------------------===//
  6012. // Generic Evaluation
  6013. //===----------------------------------------------------------------------===//
  6014. namespace {
  6015. class BitCastBuffer {
  6016. // FIXME: We're going to need bit-level granularity when we support
  6017. // bit-fields.
  6018. // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
  6019. // we don't support a host or target where that is the case. Still, we should
  6020. // use a more generic type in case we ever do.
  6021. SmallVector<Optional<unsigned char>, 32> Bytes;
  6022. static_assert(std::numeric_limits<unsigned char>::digits >= 8,
  6023. "Need at least 8 bit unsigned char");
  6024. bool TargetIsLittleEndian;
  6025. public:
  6026. BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
  6027. : Bytes(Width.getQuantity()),
  6028. TargetIsLittleEndian(TargetIsLittleEndian) {}
  6029. LLVM_NODISCARD
  6030. bool readObject(CharUnits Offset, CharUnits Width,
  6031. SmallVectorImpl<unsigned char> &Output) const {
  6032. for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
  6033. // If a byte of an integer is uninitialized, then the whole integer is
  6034. // uninitialized.
  6035. if (!Bytes[I.getQuantity()])
  6036. return false;
  6037. Output.push_back(*Bytes[I.getQuantity()]);
  6038. }
  6039. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  6040. std::reverse(Output.begin(), Output.end());
  6041. return true;
  6042. }
  6043. void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
  6044. if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
  6045. std::reverse(Input.begin(), Input.end());
  6046. size_t Index = 0;
  6047. for (unsigned char Byte : Input) {
  6048. assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
  6049. Bytes[Offset.getQuantity() + Index] = Byte;
  6050. ++Index;
  6051. }
  6052. }
  6053. size_t size() { return Bytes.size(); }
  6054. };
  6055. /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
  6056. /// target would represent the value at runtime.
  6057. class APValueToBufferConverter {
  6058. EvalInfo &Info;
  6059. BitCastBuffer Buffer;
  6060. const CastExpr *BCE;
  6061. APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
  6062. const CastExpr *BCE)
  6063. : Info(Info),
  6064. Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
  6065. BCE(BCE) {}
  6066. bool visit(const APValue &Val, QualType Ty) {
  6067. return visit(Val, Ty, CharUnits::fromQuantity(0));
  6068. }
  6069. // Write out Val with type Ty into Buffer starting at Offset.
  6070. bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
  6071. assert((size_t)Offset.getQuantity() <= Buffer.size());
  6072. // As a special case, nullptr_t has an indeterminate value.
  6073. if (Ty->isNullPtrType())
  6074. return true;
  6075. // Dig through Src to find the byte at SrcOffset.
  6076. switch (Val.getKind()) {
  6077. case APValue::Indeterminate:
  6078. case APValue::None:
  6079. return true;
  6080. case APValue::Int:
  6081. return visitInt(Val.getInt(), Ty, Offset);
  6082. case APValue::Float:
  6083. return visitFloat(Val.getFloat(), Ty, Offset);
  6084. case APValue::Array:
  6085. return visitArray(Val, Ty, Offset);
  6086. case APValue::Struct:
  6087. return visitRecord(Val, Ty, Offset);
  6088. case APValue::ComplexInt:
  6089. case APValue::ComplexFloat:
  6090. case APValue::Vector:
  6091. case APValue::FixedPoint:
  6092. // FIXME: We should support these.
  6093. case APValue::Union:
  6094. case APValue::MemberPointer:
  6095. case APValue::AddrLabelDiff: {
  6096. Info.FFDiag(BCE->getBeginLoc(),
  6097. diag::note_constexpr_bit_cast_unsupported_type)
  6098. << Ty;
  6099. return false;
  6100. }
  6101. case APValue::LValue:
  6102. llvm_unreachable("LValue subobject in bit_cast?");
  6103. }
  6104. llvm_unreachable("Unhandled APValue::ValueKind");
  6105. }
  6106. bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
  6107. const RecordDecl *RD = Ty->getAsRecordDecl();
  6108. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6109. // Visit the base classes.
  6110. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  6111. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  6112. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  6113. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  6114. if (!visitRecord(Val.getStructBase(I), BS.getType(),
  6115. Layout.getBaseClassOffset(BaseDecl) + Offset))
  6116. return false;
  6117. }
  6118. }
  6119. // Visit the fields.
  6120. unsigned FieldIdx = 0;
  6121. for (FieldDecl *FD : RD->fields()) {
  6122. if (FD->isBitField()) {
  6123. Info.FFDiag(BCE->getBeginLoc(),
  6124. diag::note_constexpr_bit_cast_unsupported_bitfield);
  6125. return false;
  6126. }
  6127. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  6128. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
  6129. "only bit-fields can have sub-char alignment");
  6130. CharUnits FieldOffset =
  6131. Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
  6132. QualType FieldTy = FD->getType();
  6133. if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
  6134. return false;
  6135. ++FieldIdx;
  6136. }
  6137. return true;
  6138. }
  6139. bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
  6140. const auto *CAT =
  6141. dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
  6142. if (!CAT)
  6143. return false;
  6144. CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
  6145. unsigned NumInitializedElts = Val.getArrayInitializedElts();
  6146. unsigned ArraySize = Val.getArraySize();
  6147. // First, initialize the initialized elements.
  6148. for (unsigned I = 0; I != NumInitializedElts; ++I) {
  6149. const APValue &SubObj = Val.getArrayInitializedElt(I);
  6150. if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
  6151. return false;
  6152. }
  6153. // Next, initialize the rest of the array using the filler.
  6154. if (Val.hasArrayFiller()) {
  6155. const APValue &Filler = Val.getArrayFiller();
  6156. for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
  6157. if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
  6158. return false;
  6159. }
  6160. }
  6161. return true;
  6162. }
  6163. bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
  6164. APSInt AdjustedVal = Val;
  6165. unsigned Width = AdjustedVal.getBitWidth();
  6166. if (Ty->isBooleanType()) {
  6167. Width = Info.Ctx.getTypeSize(Ty);
  6168. AdjustedVal = AdjustedVal.extend(Width);
  6169. }
  6170. SmallVector<unsigned char, 8> Bytes(Width / 8);
  6171. llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
  6172. Buffer.writeObject(Offset, Bytes);
  6173. return true;
  6174. }
  6175. bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
  6176. APSInt AsInt(Val.bitcastToAPInt());
  6177. return visitInt(AsInt, Ty, Offset);
  6178. }
  6179. public:
  6180. static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
  6181. const CastExpr *BCE) {
  6182. CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
  6183. APValueToBufferConverter Converter(Info, DstSize, BCE);
  6184. if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
  6185. return None;
  6186. return Converter.Buffer;
  6187. }
  6188. };
  6189. /// Write an BitCastBuffer into an APValue.
  6190. class BufferToAPValueConverter {
  6191. EvalInfo &Info;
  6192. const BitCastBuffer &Buffer;
  6193. const CastExpr *BCE;
  6194. BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
  6195. const CastExpr *BCE)
  6196. : Info(Info), Buffer(Buffer), BCE(BCE) {}
  6197. // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
  6198. // with an invalid type, so anything left is a deficiency on our part (FIXME).
  6199. // Ideally this will be unreachable.
  6200. llvm::NoneType unsupportedType(QualType Ty) {
  6201. Info.FFDiag(BCE->getBeginLoc(),
  6202. diag::note_constexpr_bit_cast_unsupported_type)
  6203. << Ty;
  6204. return None;
  6205. }
  6206. llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
  6207. Info.FFDiag(BCE->getBeginLoc(),
  6208. diag::note_constexpr_bit_cast_unrepresentable_value)
  6209. << Ty << toString(Val, /*Radix=*/10);
  6210. return None;
  6211. }
  6212. Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
  6213. const EnumType *EnumSugar = nullptr) {
  6214. if (T->isNullPtrType()) {
  6215. uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
  6216. return APValue((Expr *)nullptr,
  6217. /*Offset=*/CharUnits::fromQuantity(NullValue),
  6218. APValue::NoLValuePath{}, /*IsNullPtr=*/true);
  6219. }
  6220. CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
  6221. // Work around floating point types that contain unused padding bytes. This
  6222. // is really just `long double` on x86, which is the only fundamental type
  6223. // with padding bytes.
  6224. if (T->isRealFloatingType()) {
  6225. const llvm::fltSemantics &Semantics =
  6226. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  6227. unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
  6228. assert(NumBits % 8 == 0);
  6229. CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
  6230. if (NumBytes != SizeOf)
  6231. SizeOf = NumBytes;
  6232. }
  6233. SmallVector<uint8_t, 8> Bytes;
  6234. if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
  6235. // If this is std::byte or unsigned char, then its okay to store an
  6236. // indeterminate value.
  6237. bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
  6238. bool IsUChar =
  6239. !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
  6240. T->isSpecificBuiltinType(BuiltinType::Char_U));
  6241. if (!IsStdByte && !IsUChar) {
  6242. QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
  6243. Info.FFDiag(BCE->getExprLoc(),
  6244. diag::note_constexpr_bit_cast_indet_dest)
  6245. << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
  6246. return None;
  6247. }
  6248. return APValue::IndeterminateValue();
  6249. }
  6250. APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
  6251. llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
  6252. if (T->isIntegralOrEnumerationType()) {
  6253. Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
  6254. unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
  6255. if (IntWidth != Val.getBitWidth()) {
  6256. APSInt Truncated = Val.trunc(IntWidth);
  6257. if (Truncated.extend(Val.getBitWidth()) != Val)
  6258. return unrepresentableValue(QualType(T, 0), Val);
  6259. Val = Truncated;
  6260. }
  6261. return APValue(Val);
  6262. }
  6263. if (T->isRealFloatingType()) {
  6264. const llvm::fltSemantics &Semantics =
  6265. Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
  6266. return APValue(APFloat(Semantics, Val));
  6267. }
  6268. return unsupportedType(QualType(T, 0));
  6269. }
  6270. Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
  6271. const RecordDecl *RD = RTy->getAsRecordDecl();
  6272. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6273. unsigned NumBases = 0;
  6274. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  6275. NumBases = CXXRD->getNumBases();
  6276. APValue ResultVal(APValue::UninitStruct(), NumBases,
  6277. std::distance(RD->field_begin(), RD->field_end()));
  6278. // Visit the base classes.
  6279. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  6280. for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
  6281. const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
  6282. CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
  6283. if (BaseDecl->isEmpty() ||
  6284. Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
  6285. continue;
  6286. Optional<APValue> SubObj = visitType(
  6287. BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
  6288. if (!SubObj)
  6289. return None;
  6290. ResultVal.getStructBase(I) = *SubObj;
  6291. }
  6292. }
  6293. // Visit the fields.
  6294. unsigned FieldIdx = 0;
  6295. for (FieldDecl *FD : RD->fields()) {
  6296. // FIXME: We don't currently support bit-fields. A lot of the logic for
  6297. // this is in CodeGen, so we need to factor it around.
  6298. if (FD->isBitField()) {
  6299. Info.FFDiag(BCE->getBeginLoc(),
  6300. diag::note_constexpr_bit_cast_unsupported_bitfield);
  6301. return None;
  6302. }
  6303. uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
  6304. assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
  6305. CharUnits FieldOffset =
  6306. CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
  6307. Offset;
  6308. QualType FieldTy = FD->getType();
  6309. Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
  6310. if (!SubObj)
  6311. return None;
  6312. ResultVal.getStructField(FieldIdx) = *SubObj;
  6313. ++FieldIdx;
  6314. }
  6315. return ResultVal;
  6316. }
  6317. Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
  6318. QualType RepresentationType = Ty->getDecl()->getIntegerType();
  6319. assert(!RepresentationType.isNull() &&
  6320. "enum forward decl should be caught by Sema");
  6321. const auto *AsBuiltin =
  6322. RepresentationType.getCanonicalType()->castAs<BuiltinType>();
  6323. // Recurse into the underlying type. Treat std::byte transparently as
  6324. // unsigned char.
  6325. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
  6326. }
  6327. Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
  6328. size_t Size = Ty->getSize().getLimitedValue();
  6329. CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
  6330. APValue ArrayValue(APValue::UninitArray(), Size, Size);
  6331. for (size_t I = 0; I != Size; ++I) {
  6332. Optional<APValue> ElementValue =
  6333. visitType(Ty->getElementType(), Offset + I * ElementWidth);
  6334. if (!ElementValue)
  6335. return None;
  6336. ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
  6337. }
  6338. return ArrayValue;
  6339. }
  6340. Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
  6341. return unsupportedType(QualType(Ty, 0));
  6342. }
  6343. Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
  6344. QualType Can = Ty.getCanonicalType();
  6345. switch (Can->getTypeClass()) {
  6346. #define TYPE(Class, Base) \
  6347. case Type::Class: \
  6348. return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
  6349. #define ABSTRACT_TYPE(Class, Base)
  6350. #define NON_CANONICAL_TYPE(Class, Base) \
  6351. case Type::Class: \
  6352. llvm_unreachable("non-canonical type should be impossible!");
  6353. #define DEPENDENT_TYPE(Class, Base) \
  6354. case Type::Class: \
  6355. llvm_unreachable( \
  6356. "dependent types aren't supported in the constant evaluator!");
  6357. #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
  6358. case Type::Class: \
  6359. llvm_unreachable("either dependent or not canonical!");
  6360. #include "clang/AST/TypeNodes.inc"
  6361. }
  6362. llvm_unreachable("Unhandled Type::TypeClass");
  6363. }
  6364. public:
  6365. // Pull out a full value of type DstType.
  6366. static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
  6367. const CastExpr *BCE) {
  6368. BufferToAPValueConverter Converter(Info, Buffer, BCE);
  6369. return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
  6370. }
  6371. };
  6372. static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
  6373. QualType Ty, EvalInfo *Info,
  6374. const ASTContext &Ctx,
  6375. bool CheckingDest) {
  6376. Ty = Ty.getCanonicalType();
  6377. auto diag = [&](int Reason) {
  6378. if (Info)
  6379. Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
  6380. << CheckingDest << (Reason == 4) << Reason;
  6381. return false;
  6382. };
  6383. auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
  6384. if (Info)
  6385. Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
  6386. << NoteTy << Construct << Ty;
  6387. return false;
  6388. };
  6389. if (Ty->isUnionType())
  6390. return diag(0);
  6391. if (Ty->isPointerType())
  6392. return diag(1);
  6393. if (Ty->isMemberPointerType())
  6394. return diag(2);
  6395. if (Ty.isVolatileQualified())
  6396. return diag(3);
  6397. if (RecordDecl *Record = Ty->getAsRecordDecl()) {
  6398. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
  6399. for (CXXBaseSpecifier &BS : CXXRD->bases())
  6400. if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
  6401. CheckingDest))
  6402. return note(1, BS.getType(), BS.getBeginLoc());
  6403. }
  6404. for (FieldDecl *FD : Record->fields()) {
  6405. if (FD->getType()->isReferenceType())
  6406. return diag(4);
  6407. if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
  6408. CheckingDest))
  6409. return note(0, FD->getType(), FD->getBeginLoc());
  6410. }
  6411. }
  6412. if (Ty->isArrayType() &&
  6413. !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
  6414. Info, Ctx, CheckingDest))
  6415. return false;
  6416. return true;
  6417. }
  6418. static bool checkBitCastConstexprEligibility(EvalInfo *Info,
  6419. const ASTContext &Ctx,
  6420. const CastExpr *BCE) {
  6421. bool DestOK = checkBitCastConstexprEligibilityType(
  6422. BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
  6423. bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
  6424. BCE->getBeginLoc(),
  6425. BCE->getSubExpr()->getType(), Info, Ctx, false);
  6426. return SourceOK;
  6427. }
  6428. static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
  6429. APValue &SourceValue,
  6430. const CastExpr *BCE) {
  6431. assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
  6432. "no host or target supports non 8-bit chars");
  6433. assert(SourceValue.isLValue() &&
  6434. "LValueToRValueBitcast requires an lvalue operand!");
  6435. if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
  6436. return false;
  6437. LValue SourceLValue;
  6438. APValue SourceRValue;
  6439. SourceLValue.setFrom(Info.Ctx, SourceValue);
  6440. if (!handleLValueToRValueConversion(
  6441. Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
  6442. SourceRValue, /*WantObjectRepresentation=*/true))
  6443. return false;
  6444. // Read out SourceValue into a char buffer.
  6445. Optional<BitCastBuffer> Buffer =
  6446. APValueToBufferConverter::convert(Info, SourceRValue, BCE);
  6447. if (!Buffer)
  6448. return false;
  6449. // Write out the buffer into a new APValue.
  6450. Optional<APValue> MaybeDestValue =
  6451. BufferToAPValueConverter::convert(Info, *Buffer, BCE);
  6452. if (!MaybeDestValue)
  6453. return false;
  6454. DestValue = std::move(*MaybeDestValue);
  6455. return true;
  6456. }
  6457. template <class Derived>
  6458. class ExprEvaluatorBase
  6459. : public ConstStmtVisitor<Derived, bool> {
  6460. private:
  6461. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6462. bool DerivedSuccess(const APValue &V, const Expr *E) {
  6463. return getDerived().Success(V, E);
  6464. }
  6465. bool DerivedZeroInitialization(const Expr *E) {
  6466. return getDerived().ZeroInitialization(E);
  6467. }
  6468. // Check whether a conditional operator with a non-constant condition is a
  6469. // potential constant expression. If neither arm is a potential constant
  6470. // expression, then the conditional operator is not either.
  6471. template<typename ConditionalOperator>
  6472. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  6473. assert(Info.checkingPotentialConstantExpression());
  6474. // Speculatively evaluate both arms.
  6475. SmallVector<PartialDiagnosticAt, 8> Diag;
  6476. {
  6477. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  6478. StmtVisitorTy::Visit(E->getFalseExpr());
  6479. if (Diag.empty())
  6480. return;
  6481. }
  6482. {
  6483. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  6484. Diag.clear();
  6485. StmtVisitorTy::Visit(E->getTrueExpr());
  6486. if (Diag.empty())
  6487. return;
  6488. }
  6489. Error(E, diag::note_constexpr_conditional_never_const);
  6490. }
  6491. template<typename ConditionalOperator>
  6492. bool HandleConditionalOperator(const ConditionalOperator *E) {
  6493. bool BoolResult;
  6494. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  6495. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  6496. CheckPotentialConstantConditional(E);
  6497. return false;
  6498. }
  6499. if (Info.noteFailure()) {
  6500. StmtVisitorTy::Visit(E->getTrueExpr());
  6501. StmtVisitorTy::Visit(E->getFalseExpr());
  6502. }
  6503. return false;
  6504. }
  6505. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  6506. return StmtVisitorTy::Visit(EvalExpr);
  6507. }
  6508. protected:
  6509. EvalInfo &Info;
  6510. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  6511. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  6512. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  6513. return Info.CCEDiag(E, D);
  6514. }
  6515. bool ZeroInitialization(const Expr *E) { return Error(E); }
  6516. public:
  6517. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  6518. EvalInfo &getEvalInfo() { return Info; }
  6519. /// Report an evaluation error. This should only be called when an error is
  6520. /// first discovered. When propagating an error, just return false.
  6521. bool Error(const Expr *E, diag::kind D) {
  6522. Info.FFDiag(E, D);
  6523. return false;
  6524. }
  6525. bool Error(const Expr *E) {
  6526. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  6527. }
  6528. bool VisitStmt(const Stmt *) {
  6529. llvm_unreachable("Expression evaluator should not be called on stmts");
  6530. }
  6531. bool VisitExpr(const Expr *E) {
  6532. return Error(E);
  6533. }
  6534. bool VisitConstantExpr(const ConstantExpr *E) {
  6535. if (E->hasAPValueResult())
  6536. return DerivedSuccess(E->getAPValueResult(), E);
  6537. return StmtVisitorTy::Visit(E->getSubExpr());
  6538. }
  6539. bool VisitParenExpr(const ParenExpr *E)
  6540. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  6541. bool VisitUnaryExtension(const UnaryOperator *E)
  6542. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  6543. bool VisitUnaryPlus(const UnaryOperator *E)
  6544. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  6545. bool VisitChooseExpr(const ChooseExpr *E)
  6546. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  6547. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  6548. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  6549. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  6550. { return StmtVisitorTy::Visit(E->getReplacement()); }
  6551. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  6552. TempVersionRAII RAII(*Info.CurrentCall);
  6553. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  6554. return StmtVisitorTy::Visit(E->getExpr());
  6555. }
  6556. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  6557. TempVersionRAII RAII(*Info.CurrentCall);
  6558. // The initializer may not have been parsed yet, or might be erroneous.
  6559. if (!E->getExpr())
  6560. return Error(E);
  6561. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  6562. return StmtVisitorTy::Visit(E->getExpr());
  6563. }
  6564. bool VisitExprWithCleanups(const ExprWithCleanups *E) {
  6565. FullExpressionRAII Scope(Info);
  6566. return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
  6567. }
  6568. // Temporaries are registered when created, so we don't care about
  6569. // CXXBindTemporaryExpr.
  6570. bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  6571. return StmtVisitorTy::Visit(E->getSubExpr());
  6572. }
  6573. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  6574. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  6575. return static_cast<Derived*>(this)->VisitCastExpr(E);
  6576. }
  6577. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  6578. if (!Info.Ctx.getLangOpts().CPlusPlus20)
  6579. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  6580. return static_cast<Derived*>(this)->VisitCastExpr(E);
  6581. }
  6582. bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
  6583. return static_cast<Derived*>(this)->VisitCastExpr(E);
  6584. }
  6585. bool VisitBinaryOperator(const BinaryOperator *E) {
  6586. switch (E->getOpcode()) {
  6587. default:
  6588. return Error(E);
  6589. case BO_Comma:
  6590. VisitIgnoredValue(E->getLHS());
  6591. return StmtVisitorTy::Visit(E->getRHS());
  6592. case BO_PtrMemD:
  6593. case BO_PtrMemI: {
  6594. LValue Obj;
  6595. if (!HandleMemberPointerAccess(Info, E, Obj))
  6596. return false;
  6597. APValue Result;
  6598. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  6599. return false;
  6600. return DerivedSuccess(Result, E);
  6601. }
  6602. }
  6603. }
  6604. bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
  6605. return StmtVisitorTy::Visit(E->getSemanticForm());
  6606. }
  6607. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  6608. // Evaluate and cache the common expression. We treat it as a temporary,
  6609. // even though it's not quite the same thing.
  6610. LValue CommonLV;
  6611. if (!Evaluate(Info.CurrentCall->createTemporary(
  6612. E->getOpaqueValue(),
  6613. getStorageType(Info.Ctx, E->getOpaqueValue()),
  6614. ScopeKind::FullExpression, CommonLV),
  6615. Info, E->getCommon()))
  6616. return false;
  6617. return HandleConditionalOperator(E);
  6618. }
  6619. bool VisitConditionalOperator(const ConditionalOperator *E) {
  6620. bool IsBcpCall = false;
  6621. // If the condition (ignoring parens) is a __builtin_constant_p call,
  6622. // the result is a constant expression if it can be folded without
  6623. // side-effects. This is an important GNU extension. See GCC PR38377
  6624. // for discussion.
  6625. if (const CallExpr *CallCE =
  6626. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  6627. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  6628. IsBcpCall = true;
  6629. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  6630. // constant expression; we can't check whether it's potentially foldable.
  6631. // FIXME: We should instead treat __builtin_constant_p as non-constant if
  6632. // it would return 'false' in this mode.
  6633. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  6634. return false;
  6635. FoldConstant Fold(Info, IsBcpCall);
  6636. if (!HandleConditionalOperator(E)) {
  6637. Fold.keepDiagnostics();
  6638. return false;
  6639. }
  6640. return true;
  6641. }
  6642. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  6643. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  6644. return DerivedSuccess(*Value, E);
  6645. const Expr *Source = E->getSourceExpr();
  6646. if (!Source)
  6647. return Error(E);
  6648. if (Source == E) {
  6649. assert(0 && "OpaqueValueExpr recursively refers to itself");
  6650. return Error(E);
  6651. }
  6652. return StmtVisitorTy::Visit(Source);
  6653. }
  6654. bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
  6655. for (const Expr *SemE : E->semantics()) {
  6656. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
  6657. // FIXME: We can't handle the case where an OpaqueValueExpr is also the
  6658. // result expression: there could be two different LValues that would
  6659. // refer to the same object in that case, and we can't model that.
  6660. if (SemE == E->getResultExpr())
  6661. return Error(E);
  6662. // Unique OVEs get evaluated if and when we encounter them when
  6663. // emitting the rest of the semantic form, rather than eagerly.
  6664. if (OVE->isUnique())
  6665. continue;
  6666. LValue LV;
  6667. if (!Evaluate(Info.CurrentCall->createTemporary(
  6668. OVE, getStorageType(Info.Ctx, OVE),
  6669. ScopeKind::FullExpression, LV),
  6670. Info, OVE->getSourceExpr()))
  6671. return false;
  6672. } else if (SemE == E->getResultExpr()) {
  6673. if (!StmtVisitorTy::Visit(SemE))
  6674. return false;
  6675. } else {
  6676. if (!EvaluateIgnoredValue(Info, SemE))
  6677. return false;
  6678. }
  6679. }
  6680. return true;
  6681. }
  6682. bool VisitCallExpr(const CallExpr *E) {
  6683. APValue Result;
  6684. if (!handleCallExpr(E, Result, nullptr))
  6685. return false;
  6686. return DerivedSuccess(Result, E);
  6687. }
  6688. bool handleCallExpr(const CallExpr *E, APValue &Result,
  6689. const LValue *ResultSlot) {
  6690. CallScopeRAII CallScope(Info);
  6691. const Expr *Callee = E->getCallee()->IgnoreParens();
  6692. QualType CalleeType = Callee->getType();
  6693. const FunctionDecl *FD = nullptr;
  6694. LValue *This = nullptr, ThisVal;
  6695. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  6696. bool HasQualifier = false;
  6697. CallRef Call;
  6698. // Extract function decl and 'this' pointer from the callee.
  6699. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  6700. const CXXMethodDecl *Member = nullptr;
  6701. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  6702. // Explicit bound member calls, such as x.f() or p->g();
  6703. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  6704. return false;
  6705. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  6706. if (!Member)
  6707. return Error(Callee);
  6708. This = &ThisVal;
  6709. HasQualifier = ME->hasQualifier();
  6710. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  6711. // Indirect bound member calls ('.*' or '->*').
  6712. const ValueDecl *D =
  6713. HandleMemberPointerAccess(Info, BE, ThisVal, false);
  6714. if (!D)
  6715. return false;
  6716. Member = dyn_cast<CXXMethodDecl>(D);
  6717. if (!Member)
  6718. return Error(Callee);
  6719. This = &ThisVal;
  6720. } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
  6721. if (!Info.getLangOpts().CPlusPlus20)
  6722. Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
  6723. return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
  6724. HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
  6725. } else
  6726. return Error(Callee);
  6727. FD = Member;
  6728. } else if (CalleeType->isFunctionPointerType()) {
  6729. LValue CalleeLV;
  6730. if (!EvaluatePointer(Callee, CalleeLV, Info))
  6731. return false;
  6732. if (!CalleeLV.getLValueOffset().isZero())
  6733. return Error(Callee);
  6734. FD = dyn_cast_or_null<FunctionDecl>(
  6735. CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
  6736. if (!FD)
  6737. return Error(Callee);
  6738. // Don't call function pointers which have been cast to some other type.
  6739. // Per DR (no number yet), the caller and callee can differ in noexcept.
  6740. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  6741. CalleeType->getPointeeType(), FD->getType())) {
  6742. return Error(E);
  6743. }
  6744. // For an (overloaded) assignment expression, evaluate the RHS before the
  6745. // LHS.
  6746. auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
  6747. if (OCE && OCE->isAssignmentOp()) {
  6748. assert(Args.size() == 2 && "wrong number of arguments in assignment");
  6749. Call = Info.CurrentCall->createCall(FD);
  6750. if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
  6751. Info, FD, /*RightToLeft=*/true))
  6752. return false;
  6753. }
  6754. // Overloaded operator calls to member functions are represented as normal
  6755. // calls with '*this' as the first argument.
  6756. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6757. if (MD && !MD->isStatic()) {
  6758. // FIXME: When selecting an implicit conversion for an overloaded
  6759. // operator delete, we sometimes try to evaluate calls to conversion
  6760. // operators without a 'this' parameter!
  6761. if (Args.empty())
  6762. return Error(E);
  6763. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  6764. return false;
  6765. This = &ThisVal;
  6766. // If this is syntactically a simple assignment using a trivial
  6767. // assignment operator, start the lifetimes of union members as needed,
  6768. // per C++20 [class.union]5.
  6769. if (Info.getLangOpts().CPlusPlus20 && OCE &&
  6770. OCE->getOperator() == OO_Equal && MD->isTrivial() &&
  6771. !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
  6772. return false;
  6773. Args = Args.slice(1);
  6774. } else if (MD && MD->isLambdaStaticInvoker()) {
  6775. // Map the static invoker for the lambda back to the call operator.
  6776. // Conveniently, we don't have to slice out the 'this' argument (as is
  6777. // being done for the non-static case), since a static member function
  6778. // doesn't have an implicit argument passed in.
  6779. const CXXRecordDecl *ClosureClass = MD->getParent();
  6780. assert(
  6781. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  6782. "Number of captures must be zero for conversion to function-ptr");
  6783. const CXXMethodDecl *LambdaCallOp =
  6784. ClosureClass->getLambdaCallOperator();
  6785. // Set 'FD', the function that will be called below, to the call
  6786. // operator. If the closure object represents a generic lambda, find
  6787. // the corresponding specialization of the call operator.
  6788. if (ClosureClass->isGenericLambda()) {
  6789. assert(MD->isFunctionTemplateSpecialization() &&
  6790. "A generic lambda's static-invoker function must be a "
  6791. "template specialization");
  6792. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  6793. FunctionTemplateDecl *CallOpTemplate =
  6794. LambdaCallOp->getDescribedFunctionTemplate();
  6795. void *InsertPos = nullptr;
  6796. FunctionDecl *CorrespondingCallOpSpecialization =
  6797. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  6798. assert(CorrespondingCallOpSpecialization &&
  6799. "We must always have a function call operator specialization "
  6800. "that corresponds to our static invoker specialization");
  6801. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  6802. } else
  6803. FD = LambdaCallOp;
  6804. } else if (FD->isReplaceableGlobalAllocationFunction()) {
  6805. if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
  6806. FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
  6807. LValue Ptr;
  6808. if (!HandleOperatorNewCall(Info, E, Ptr))
  6809. return false;
  6810. Ptr.moveInto(Result);
  6811. return CallScope.destroy();
  6812. } else {
  6813. return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
  6814. }
  6815. }
  6816. } else
  6817. return Error(E);
  6818. // Evaluate the arguments now if we've not already done so.
  6819. if (!Call) {
  6820. Call = Info.CurrentCall->createCall(FD);
  6821. if (!EvaluateArgs(Args, Call, Info, FD))
  6822. return false;
  6823. }
  6824. SmallVector<QualType, 4> CovariantAdjustmentPath;
  6825. if (This) {
  6826. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  6827. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  6828. // Perform virtual dispatch, if necessary.
  6829. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  6830. CovariantAdjustmentPath);
  6831. if (!FD)
  6832. return false;
  6833. } else {
  6834. // Check that the 'this' pointer points to an object of the right type.
  6835. // FIXME: If this is an assignment operator call, we may need to change
  6836. // the active union member before we check this.
  6837. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
  6838. return false;
  6839. }
  6840. }
  6841. // Destructor calls are different enough that they have their own codepath.
  6842. if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
  6843. assert(This && "no 'this' pointer for destructor call");
  6844. return HandleDestruction(Info, E, *This,
  6845. Info.Ctx.getRecordType(DD->getParent())) &&
  6846. CallScope.destroy();
  6847. }
  6848. const FunctionDecl *Definition = nullptr;
  6849. Stmt *Body = FD->getBody(Definition);
  6850. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  6851. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
  6852. Body, Info, Result, ResultSlot))
  6853. return false;
  6854. if (!CovariantAdjustmentPath.empty() &&
  6855. !HandleCovariantReturnAdjustment(Info, E, Result,
  6856. CovariantAdjustmentPath))
  6857. return false;
  6858. return CallScope.destroy();
  6859. }
  6860. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  6861. return StmtVisitorTy::Visit(E->getInitializer());
  6862. }
  6863. bool VisitInitListExpr(const InitListExpr *E) {
  6864. if (E->getNumInits() == 0)
  6865. return DerivedZeroInitialization(E);
  6866. if (E->getNumInits() == 1)
  6867. return StmtVisitorTy::Visit(E->getInit(0));
  6868. return Error(E);
  6869. }
  6870. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  6871. return DerivedZeroInitialization(E);
  6872. }
  6873. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  6874. return DerivedZeroInitialization(E);
  6875. }
  6876. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  6877. return DerivedZeroInitialization(E);
  6878. }
  6879. /// A member expression where the object is a prvalue is itself a prvalue.
  6880. bool VisitMemberExpr(const MemberExpr *E) {
  6881. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  6882. "missing temporary materialization conversion");
  6883. assert(!E->isArrow() && "missing call to bound member function?");
  6884. APValue Val;
  6885. if (!Evaluate(Val, Info, E->getBase()))
  6886. return false;
  6887. QualType BaseTy = E->getBase()->getType();
  6888. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  6889. if (!FD) return Error(E);
  6890. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  6891. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  6892. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  6893. // Note: there is no lvalue base here. But this case should only ever
  6894. // happen in C or in C++98, where we cannot be evaluating a constexpr
  6895. // constructor, which is the only case the base matters.
  6896. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  6897. SubobjectDesignator Designator(BaseTy);
  6898. Designator.addDeclUnchecked(FD);
  6899. APValue Result;
  6900. return extractSubobject(Info, E, Obj, Designator, Result) &&
  6901. DerivedSuccess(Result, E);
  6902. }
  6903. bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  6904. APValue Val;
  6905. if (!Evaluate(Val, Info, E->getBase()))
  6906. return false;
  6907. if (Val.isVector()) {
  6908. SmallVector<uint32_t, 4> Indices;
  6909. E->getEncodedElementAccess(Indices);
  6910. if (Indices.size() == 1) {
  6911. // Return scalar.
  6912. return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
  6913. } else {
  6914. // Construct new APValue vector.
  6915. SmallVector<APValue, 4> Elts;
  6916. for (unsigned I = 0; I < Indices.size(); ++I) {
  6917. Elts.push_back(Val.getVectorElt(Indices[I]));
  6918. }
  6919. APValue VecResult(Elts.data(), Indices.size());
  6920. return DerivedSuccess(VecResult, E);
  6921. }
  6922. }
  6923. return false;
  6924. }
  6925. bool VisitCastExpr(const CastExpr *E) {
  6926. switch (E->getCastKind()) {
  6927. default:
  6928. break;
  6929. case CK_AtomicToNonAtomic: {
  6930. APValue AtomicVal;
  6931. // This does not need to be done in place even for class/array types:
  6932. // atomic-to-non-atomic conversion implies copying the object
  6933. // representation.
  6934. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  6935. return false;
  6936. return DerivedSuccess(AtomicVal, E);
  6937. }
  6938. case CK_NoOp:
  6939. case CK_UserDefinedConversion:
  6940. return StmtVisitorTy::Visit(E->getSubExpr());
  6941. case CK_LValueToRValue: {
  6942. LValue LVal;
  6943. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  6944. return false;
  6945. APValue RVal;
  6946. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  6947. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  6948. LVal, RVal))
  6949. return false;
  6950. return DerivedSuccess(RVal, E);
  6951. }
  6952. case CK_LValueToRValueBitCast: {
  6953. APValue DestValue, SourceValue;
  6954. if (!Evaluate(SourceValue, Info, E->getSubExpr()))
  6955. return false;
  6956. if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
  6957. return false;
  6958. return DerivedSuccess(DestValue, E);
  6959. }
  6960. case CK_AddressSpaceConversion: {
  6961. APValue Value;
  6962. if (!Evaluate(Value, Info, E->getSubExpr()))
  6963. return false;
  6964. return DerivedSuccess(Value, E);
  6965. }
  6966. }
  6967. return Error(E);
  6968. }
  6969. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  6970. return VisitUnaryPostIncDec(UO);
  6971. }
  6972. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  6973. return VisitUnaryPostIncDec(UO);
  6974. }
  6975. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  6976. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  6977. return Error(UO);
  6978. LValue LVal;
  6979. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  6980. return false;
  6981. APValue RVal;
  6982. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  6983. UO->isIncrementOp(), &RVal))
  6984. return false;
  6985. return DerivedSuccess(RVal, UO);
  6986. }
  6987. bool VisitStmtExpr(const StmtExpr *E) {
  6988. // We will have checked the full-expressions inside the statement expression
  6989. // when they were completed, and don't need to check them again now.
  6990. llvm::SaveAndRestore<bool> NotCheckingForUB(
  6991. Info.CheckingForUndefinedBehavior, false);
  6992. const CompoundStmt *CS = E->getSubStmt();
  6993. if (CS->body_empty())
  6994. return true;
  6995. BlockScopeRAII Scope(Info);
  6996. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  6997. BE = CS->body_end();
  6998. /**/; ++BI) {
  6999. if (BI + 1 == BE) {
  7000. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  7001. if (!FinalExpr) {
  7002. Info.FFDiag((*BI)->getBeginLoc(),
  7003. diag::note_constexpr_stmt_expr_unsupported);
  7004. return false;
  7005. }
  7006. return this->Visit(FinalExpr) && Scope.destroy();
  7007. }
  7008. APValue ReturnValue;
  7009. StmtResult Result = { ReturnValue, nullptr };
  7010. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  7011. if (ESR != ESR_Succeeded) {
  7012. // FIXME: If the statement-expression terminated due to 'return',
  7013. // 'break', or 'continue', it would be nice to propagate that to
  7014. // the outer statement evaluation rather than bailing out.
  7015. if (ESR != ESR_Failed)
  7016. Info.FFDiag((*BI)->getBeginLoc(),
  7017. diag::note_constexpr_stmt_expr_unsupported);
  7018. return false;
  7019. }
  7020. }
  7021. llvm_unreachable("Return from function from the loop above.");
  7022. }
  7023. /// Visit a value which is evaluated, but whose value is ignored.
  7024. void VisitIgnoredValue(const Expr *E) {
  7025. EvaluateIgnoredValue(Info, E);
  7026. }
  7027. /// Potentially visit a MemberExpr's base expression.
  7028. void VisitIgnoredBaseExpression(const Expr *E) {
  7029. // While MSVC doesn't evaluate the base expression, it does diagnose the
  7030. // presence of side-effecting behavior.
  7031. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  7032. return;
  7033. VisitIgnoredValue(E);
  7034. }
  7035. };
  7036. } // namespace
  7037. //===----------------------------------------------------------------------===//
  7038. // Common base class for lvalue and temporary evaluation.
  7039. //===----------------------------------------------------------------------===//
  7040. namespace {
  7041. template<class Derived>
  7042. class LValueExprEvaluatorBase
  7043. : public ExprEvaluatorBase<Derived> {
  7044. protected:
  7045. LValue &Result;
  7046. bool InvalidBaseOK;
  7047. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  7048. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  7049. bool Success(APValue::LValueBase B) {
  7050. Result.set(B);
  7051. return true;
  7052. }
  7053. bool evaluatePointer(const Expr *E, LValue &Result) {
  7054. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  7055. }
  7056. public:
  7057. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  7058. : ExprEvaluatorBaseTy(Info), Result(Result),
  7059. InvalidBaseOK(InvalidBaseOK) {}
  7060. bool Success(const APValue &V, const Expr *E) {
  7061. Result.setFrom(this->Info.Ctx, V);
  7062. return true;
  7063. }
  7064. bool VisitMemberExpr(const MemberExpr *E) {
  7065. // Handle non-static data members.
  7066. QualType BaseTy;
  7067. bool EvalOK;
  7068. if (E->isArrow()) {
  7069. EvalOK = evaluatePointer(E->getBase(), Result);
  7070. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  7071. } else if (E->getBase()->isPRValue()) {
  7072. assert(E->getBase()->getType()->isRecordType());
  7073. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  7074. BaseTy = E->getBase()->getType();
  7075. } else {
  7076. EvalOK = this->Visit(E->getBase());
  7077. BaseTy = E->getBase()->getType();
  7078. }
  7079. if (!EvalOK) {
  7080. if (!InvalidBaseOK)
  7081. return false;
  7082. Result.setInvalid(E);
  7083. return true;
  7084. }
  7085. const ValueDecl *MD = E->getMemberDecl();
  7086. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  7087. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  7088. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  7089. (void)BaseTy;
  7090. if (!HandleLValueMember(this->Info, E, Result, FD))
  7091. return false;
  7092. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  7093. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  7094. return false;
  7095. } else
  7096. return this->Error(E);
  7097. if (MD->getType()->isReferenceType()) {
  7098. APValue RefValue;
  7099. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  7100. RefValue))
  7101. return false;
  7102. return Success(RefValue, E);
  7103. }
  7104. return true;
  7105. }
  7106. bool VisitBinaryOperator(const BinaryOperator *E) {
  7107. switch (E->getOpcode()) {
  7108. default:
  7109. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7110. case BO_PtrMemD:
  7111. case BO_PtrMemI:
  7112. return HandleMemberPointerAccess(this->Info, E, Result);
  7113. }
  7114. }
  7115. bool VisitCastExpr(const CastExpr *E) {
  7116. switch (E->getCastKind()) {
  7117. default:
  7118. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7119. case CK_DerivedToBase:
  7120. case CK_UncheckedDerivedToBase:
  7121. if (!this->Visit(E->getSubExpr()))
  7122. return false;
  7123. // Now figure out the necessary offset to add to the base LV to get from
  7124. // the derived class to the base class.
  7125. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  7126. Result);
  7127. }
  7128. }
  7129. };
  7130. }
  7131. //===----------------------------------------------------------------------===//
  7132. // LValue Evaluation
  7133. //
  7134. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  7135. // function designators (in C), decl references to void objects (in C), and
  7136. // temporaries (if building with -Wno-address-of-temporary).
  7137. //
  7138. // LValue evaluation produces values comprising a base expression of one of the
  7139. // following types:
  7140. // - Declarations
  7141. // * VarDecl
  7142. // * FunctionDecl
  7143. // - Literals
  7144. // * CompoundLiteralExpr in C (and in global scope in C++)
  7145. // * StringLiteral
  7146. // * PredefinedExpr
  7147. // * ObjCStringLiteralExpr
  7148. // * ObjCEncodeExpr
  7149. // * AddrLabelExpr
  7150. // * BlockExpr
  7151. // * CallExpr for a MakeStringConstant builtin
  7152. // - typeid(T) expressions, as TypeInfoLValues
  7153. // - Locals and temporaries
  7154. // * MaterializeTemporaryExpr
  7155. // * Any Expr, with a CallIndex indicating the function in which the temporary
  7156. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  7157. // from the AST (FIXME).
  7158. // * A MaterializeTemporaryExpr that has static storage duration, with no
  7159. // CallIndex, for a lifetime-extended temporary.
  7160. // * The ConstantExpr that is currently being evaluated during evaluation of an
  7161. // immediate invocation.
  7162. // plus an offset in bytes.
  7163. //===----------------------------------------------------------------------===//
  7164. namespace {
  7165. class LValueExprEvaluator
  7166. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  7167. public:
  7168. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  7169. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  7170. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  7171. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  7172. bool VisitDeclRefExpr(const DeclRefExpr *E);
  7173. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  7174. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  7175. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  7176. bool VisitMemberExpr(const MemberExpr *E);
  7177. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  7178. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  7179. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  7180. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  7181. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  7182. bool VisitUnaryDeref(const UnaryOperator *E);
  7183. bool VisitUnaryReal(const UnaryOperator *E);
  7184. bool VisitUnaryImag(const UnaryOperator *E);
  7185. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  7186. return VisitUnaryPreIncDec(UO);
  7187. }
  7188. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  7189. return VisitUnaryPreIncDec(UO);
  7190. }
  7191. bool VisitBinAssign(const BinaryOperator *BO);
  7192. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  7193. bool VisitCastExpr(const CastExpr *E) {
  7194. switch (E->getCastKind()) {
  7195. default:
  7196. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  7197. case CK_LValueBitCast:
  7198. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7199. if (!Visit(E->getSubExpr()))
  7200. return false;
  7201. Result.Designator.setInvalid();
  7202. return true;
  7203. case CK_BaseToDerived:
  7204. if (!Visit(E->getSubExpr()))
  7205. return false;
  7206. return HandleBaseToDerivedCast(Info, E, Result);
  7207. case CK_Dynamic:
  7208. if (!Visit(E->getSubExpr()))
  7209. return false;
  7210. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  7211. }
  7212. }
  7213. };
  7214. } // end anonymous namespace
  7215. /// Evaluate an expression as an lvalue. This can be legitimately called on
  7216. /// expressions which are not glvalues, in three cases:
  7217. /// * function designators in C, and
  7218. /// * "extern void" objects
  7219. /// * @selector() expressions in Objective-C
  7220. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  7221. bool InvalidBaseOK) {
  7222. assert(!E->isValueDependent());
  7223. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  7224. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  7225. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  7226. }
  7227. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  7228. const NamedDecl *D = E->getDecl();
  7229. if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
  7230. return Success(cast<ValueDecl>(D));
  7231. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  7232. return VisitVarDecl(E, VD);
  7233. if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
  7234. return Visit(BD->getBinding());
  7235. return Error(E);
  7236. }
  7237. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  7238. // If we are within a lambda's call operator, check whether the 'VD' referred
  7239. // to within 'E' actually represents a lambda-capture that maps to a
  7240. // data-member/field within the closure object, and if so, evaluate to the
  7241. // field or what the field refers to.
  7242. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  7243. isa<DeclRefExpr>(E) &&
  7244. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  7245. // We don't always have a complete capture-map when checking or inferring if
  7246. // the function call operator meets the requirements of a constexpr function
  7247. // - but we don't need to evaluate the captures to determine constexprness
  7248. // (dcl.constexpr C++17).
  7249. if (Info.checkingPotentialConstantExpression())
  7250. return false;
  7251. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  7252. // Start with 'Result' referring to the complete closure object...
  7253. Result = *Info.CurrentCall->This;
  7254. // ... then update it to refer to the field of the closure object
  7255. // that represents the capture.
  7256. if (!HandleLValueMember(Info, E, Result, FD))
  7257. return false;
  7258. // And if the field is of reference type, update 'Result' to refer to what
  7259. // the field refers to.
  7260. if (FD->getType()->isReferenceType()) {
  7261. APValue RVal;
  7262. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  7263. RVal))
  7264. return false;
  7265. Result.setFrom(Info.Ctx, RVal);
  7266. }
  7267. return true;
  7268. }
  7269. }
  7270. CallStackFrame *Frame = nullptr;
  7271. unsigned Version = 0;
  7272. if (VD->hasLocalStorage()) {
  7273. // Only if a local variable was declared in the function currently being
  7274. // evaluated, do we expect to be able to find its value in the current
  7275. // frame. (Otherwise it was likely declared in an enclosing context and
  7276. // could either have a valid evaluatable value (for e.g. a constexpr
  7277. // variable) or be ill-formed (and trigger an appropriate evaluation
  7278. // diagnostic)).
  7279. CallStackFrame *CurrFrame = Info.CurrentCall;
  7280. if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
  7281. // Function parameters are stored in some caller's frame. (Usually the
  7282. // immediate caller, but for an inherited constructor they may be more
  7283. // distant.)
  7284. if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
  7285. if (CurrFrame->Arguments) {
  7286. VD = CurrFrame->Arguments.getOrigParam(PVD);
  7287. Frame =
  7288. Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
  7289. Version = CurrFrame->Arguments.Version;
  7290. }
  7291. } else {
  7292. Frame = CurrFrame;
  7293. Version = CurrFrame->getCurrentTemporaryVersion(VD);
  7294. }
  7295. }
  7296. }
  7297. if (!VD->getType()->isReferenceType()) {
  7298. if (Frame) {
  7299. Result.set({VD, Frame->Index, Version});
  7300. return true;
  7301. }
  7302. return Success(VD);
  7303. }
  7304. if (!Info.getLangOpts().CPlusPlus11) {
  7305. Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
  7306. << VD << VD->getType();
  7307. Info.Note(VD->getLocation(), diag::note_declared_at);
  7308. }
  7309. APValue *V;
  7310. if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
  7311. return false;
  7312. if (!V->hasValue()) {
  7313. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  7314. // adjust the diagnostic to say that.
  7315. if (!Info.checkingPotentialConstantExpression())
  7316. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  7317. return false;
  7318. }
  7319. return Success(*V, E);
  7320. }
  7321. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  7322. const MaterializeTemporaryExpr *E) {
  7323. // Walk through the expression to find the materialized temporary itself.
  7324. SmallVector<const Expr *, 2> CommaLHSs;
  7325. SmallVector<SubobjectAdjustment, 2> Adjustments;
  7326. const Expr *Inner =
  7327. E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  7328. // If we passed any comma operators, evaluate their LHSs.
  7329. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  7330. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  7331. return false;
  7332. // A materialized temporary with static storage duration can appear within the
  7333. // result of a constant expression evaluation, so we need to preserve its
  7334. // value for use outside this evaluation.
  7335. APValue *Value;
  7336. if (E->getStorageDuration() == SD_Static) {
  7337. // FIXME: What about SD_Thread?
  7338. Value = E->getOrCreateValue(true);
  7339. *Value = APValue();
  7340. Result.set(E);
  7341. } else {
  7342. Value = &Info.CurrentCall->createTemporary(
  7343. E, E->getType(),
  7344. E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
  7345. : ScopeKind::Block,
  7346. Result);
  7347. }
  7348. QualType Type = Inner->getType();
  7349. // Materialize the temporary itself.
  7350. if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
  7351. *Value = APValue();
  7352. return false;
  7353. }
  7354. // Adjust our lvalue to refer to the desired subobject.
  7355. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  7356. --I;
  7357. switch (Adjustments[I].Kind) {
  7358. case SubobjectAdjustment::DerivedToBaseAdjustment:
  7359. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  7360. Type, Result))
  7361. return false;
  7362. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  7363. break;
  7364. case SubobjectAdjustment::FieldAdjustment:
  7365. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  7366. return false;
  7367. Type = Adjustments[I].Field->getType();
  7368. break;
  7369. case SubobjectAdjustment::MemberPointerAdjustment:
  7370. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  7371. Adjustments[I].Ptr.RHS))
  7372. return false;
  7373. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  7374. break;
  7375. }
  7376. }
  7377. return true;
  7378. }
  7379. bool
  7380. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  7381. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  7382. "lvalue compound literal in c++?");
  7383. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  7384. // only see this when folding in C, so there's no standard to follow here.
  7385. return Success(E);
  7386. }
  7387. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  7388. TypeInfoLValue TypeInfo;
  7389. if (!E->isPotentiallyEvaluated()) {
  7390. if (E->isTypeOperand())
  7391. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  7392. else
  7393. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  7394. } else {
  7395. if (!Info.Ctx.getLangOpts().CPlusPlus20) {
  7396. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  7397. << E->getExprOperand()->getType()
  7398. << E->getExprOperand()->getSourceRange();
  7399. }
  7400. if (!Visit(E->getExprOperand()))
  7401. return false;
  7402. Optional<DynamicType> DynType =
  7403. ComputeDynamicType(Info, E, Result, AK_TypeId);
  7404. if (!DynType)
  7405. return false;
  7406. TypeInfo =
  7407. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  7408. }
  7409. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  7410. }
  7411. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  7412. return Success(E->getGuidDecl());
  7413. }
  7414. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  7415. // Handle static data members.
  7416. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  7417. VisitIgnoredBaseExpression(E->getBase());
  7418. return VisitVarDecl(E, VD);
  7419. }
  7420. // Handle static member functions.
  7421. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  7422. if (MD->isStatic()) {
  7423. VisitIgnoredBaseExpression(E->getBase());
  7424. return Success(MD);
  7425. }
  7426. }
  7427. // Handle non-static data members.
  7428. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  7429. }
  7430. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  7431. // FIXME: Deal with vectors as array subscript bases.
  7432. if (E->getBase()->getType()->isVectorType())
  7433. return Error(E);
  7434. APSInt Index;
  7435. bool Success = true;
  7436. // C++17's rules require us to evaluate the LHS first, regardless of which
  7437. // side is the base.
  7438. for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
  7439. if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
  7440. : !EvaluateInteger(SubExpr, Index, Info)) {
  7441. if (!Info.noteFailure())
  7442. return false;
  7443. Success = false;
  7444. }
  7445. }
  7446. return Success &&
  7447. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  7448. }
  7449. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  7450. return evaluatePointer(E->getSubExpr(), Result);
  7451. }
  7452. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  7453. if (!Visit(E->getSubExpr()))
  7454. return false;
  7455. // __real is a no-op on scalar lvalues.
  7456. if (E->getSubExpr()->getType()->isAnyComplexType())
  7457. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  7458. return true;
  7459. }
  7460. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7461. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  7462. "lvalue __imag__ on scalar?");
  7463. if (!Visit(E->getSubExpr()))
  7464. return false;
  7465. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  7466. return true;
  7467. }
  7468. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  7469. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7470. return Error(UO);
  7471. if (!this->Visit(UO->getSubExpr()))
  7472. return false;
  7473. return handleIncDec(
  7474. this->Info, UO, Result, UO->getSubExpr()->getType(),
  7475. UO->isIncrementOp(), nullptr);
  7476. }
  7477. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  7478. const CompoundAssignOperator *CAO) {
  7479. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7480. return Error(CAO);
  7481. bool Success = true;
  7482. // C++17 onwards require that we evaluate the RHS first.
  7483. APValue RHS;
  7484. if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
  7485. if (!Info.noteFailure())
  7486. return false;
  7487. Success = false;
  7488. }
  7489. // The overall lvalue result is the result of evaluating the LHS.
  7490. if (!this->Visit(CAO->getLHS()) || !Success)
  7491. return false;
  7492. return handleCompoundAssignment(
  7493. this->Info, CAO,
  7494. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  7495. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  7496. }
  7497. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  7498. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  7499. return Error(E);
  7500. bool Success = true;
  7501. // C++17 onwards require that we evaluate the RHS first.
  7502. APValue NewVal;
  7503. if (!Evaluate(NewVal, this->Info, E->getRHS())) {
  7504. if (!Info.noteFailure())
  7505. return false;
  7506. Success = false;
  7507. }
  7508. if (!this->Visit(E->getLHS()) || !Success)
  7509. return false;
  7510. if (Info.getLangOpts().CPlusPlus20 &&
  7511. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  7512. return false;
  7513. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  7514. NewVal);
  7515. }
  7516. //===----------------------------------------------------------------------===//
  7517. // Pointer Evaluation
  7518. //===----------------------------------------------------------------------===//
  7519. /// Attempts to compute the number of bytes available at the pointer
  7520. /// returned by a function with the alloc_size attribute. Returns true if we
  7521. /// were successful. Places an unsigned number into `Result`.
  7522. ///
  7523. /// This expects the given CallExpr to be a call to a function with an
  7524. /// alloc_size attribute.
  7525. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  7526. const CallExpr *Call,
  7527. llvm::APInt &Result) {
  7528. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  7529. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  7530. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  7531. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  7532. if (Call->getNumArgs() <= SizeArgNo)
  7533. return false;
  7534. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  7535. Expr::EvalResult ExprResult;
  7536. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  7537. return false;
  7538. Into = ExprResult.Val.getInt();
  7539. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  7540. return false;
  7541. Into = Into.zextOrSelf(BitsInSizeT);
  7542. return true;
  7543. };
  7544. APSInt SizeOfElem;
  7545. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  7546. return false;
  7547. if (!AllocSize->getNumElemsParam().isValid()) {
  7548. Result = std::move(SizeOfElem);
  7549. return true;
  7550. }
  7551. APSInt NumberOfElems;
  7552. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  7553. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  7554. return false;
  7555. bool Overflow;
  7556. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  7557. if (Overflow)
  7558. return false;
  7559. Result = std::move(BytesAvailable);
  7560. return true;
  7561. }
  7562. /// Convenience function. LVal's base must be a call to an alloc_size
  7563. /// function.
  7564. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  7565. const LValue &LVal,
  7566. llvm::APInt &Result) {
  7567. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7568. "Can't get the size of a non alloc_size function");
  7569. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  7570. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  7571. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  7572. }
  7573. /// Attempts to evaluate the given LValueBase as the result of a call to
  7574. /// a function with the alloc_size attribute. If it was possible to do so, this
  7575. /// function will return true, make Result's Base point to said function call,
  7576. /// and mark Result's Base as invalid.
  7577. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  7578. LValue &Result) {
  7579. if (Base.isNull())
  7580. return false;
  7581. // Because we do no form of static analysis, we only support const variables.
  7582. //
  7583. // Additionally, we can't support parameters, nor can we support static
  7584. // variables (in the latter case, use-before-assign isn't UB; in the former,
  7585. // we have no clue what they'll be assigned to).
  7586. const auto *VD =
  7587. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  7588. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  7589. return false;
  7590. const Expr *Init = VD->getAnyInitializer();
  7591. if (!Init)
  7592. return false;
  7593. const Expr *E = Init->IgnoreParens();
  7594. if (!tryUnwrapAllocSizeCall(E))
  7595. return false;
  7596. // Store E instead of E unwrapped so that the type of the LValue's base is
  7597. // what the user wanted.
  7598. Result.setInvalid(E);
  7599. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  7600. Result.addUnsizedArray(Info, E, Pointee);
  7601. return true;
  7602. }
  7603. namespace {
  7604. class PointerExprEvaluator
  7605. : public ExprEvaluatorBase<PointerExprEvaluator> {
  7606. LValue &Result;
  7607. bool InvalidBaseOK;
  7608. bool Success(const Expr *E) {
  7609. Result.set(E);
  7610. return true;
  7611. }
  7612. bool evaluateLValue(const Expr *E, LValue &Result) {
  7613. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  7614. }
  7615. bool evaluatePointer(const Expr *E, LValue &Result) {
  7616. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  7617. }
  7618. bool visitNonBuiltinCallExpr(const CallExpr *E);
  7619. public:
  7620. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  7621. : ExprEvaluatorBaseTy(info), Result(Result),
  7622. InvalidBaseOK(InvalidBaseOK) {}
  7623. bool Success(const APValue &V, const Expr *E) {
  7624. Result.setFrom(Info.Ctx, V);
  7625. return true;
  7626. }
  7627. bool ZeroInitialization(const Expr *E) {
  7628. Result.setNull(Info.Ctx, E->getType());
  7629. return true;
  7630. }
  7631. bool VisitBinaryOperator(const BinaryOperator *E);
  7632. bool VisitCastExpr(const CastExpr* E);
  7633. bool VisitUnaryAddrOf(const UnaryOperator *E);
  7634. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  7635. { return Success(E); }
  7636. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  7637. if (E->isExpressibleAsConstantInitializer())
  7638. return Success(E);
  7639. if (Info.noteFailure())
  7640. EvaluateIgnoredValue(Info, E->getSubExpr());
  7641. return Error(E);
  7642. }
  7643. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  7644. { return Success(E); }
  7645. bool VisitCallExpr(const CallExpr *E);
  7646. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  7647. bool VisitBlockExpr(const BlockExpr *E) {
  7648. if (!E->getBlockDecl()->hasCaptures())
  7649. return Success(E);
  7650. return Error(E);
  7651. }
  7652. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  7653. // Can't look at 'this' when checking a potential constant expression.
  7654. if (Info.checkingPotentialConstantExpression())
  7655. return false;
  7656. if (!Info.CurrentCall->This) {
  7657. if (Info.getLangOpts().CPlusPlus11)
  7658. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  7659. else
  7660. Info.FFDiag(E);
  7661. return false;
  7662. }
  7663. Result = *Info.CurrentCall->This;
  7664. // If we are inside a lambda's call operator, the 'this' expression refers
  7665. // to the enclosing '*this' object (either by value or reference) which is
  7666. // either copied into the closure object's field that represents the '*this'
  7667. // or refers to '*this'.
  7668. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  7669. // Ensure we actually have captured 'this'. (an error will have
  7670. // been previously reported if not).
  7671. if (!Info.CurrentCall->LambdaThisCaptureField)
  7672. return false;
  7673. // Update 'Result' to refer to the data member/field of the closure object
  7674. // that represents the '*this' capture.
  7675. if (!HandleLValueMember(Info, E, Result,
  7676. Info.CurrentCall->LambdaThisCaptureField))
  7677. return false;
  7678. // If we captured '*this' by reference, replace the field with its referent.
  7679. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  7680. ->isPointerType()) {
  7681. APValue RVal;
  7682. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  7683. RVal))
  7684. return false;
  7685. Result.setFrom(Info.Ctx, RVal);
  7686. }
  7687. }
  7688. return true;
  7689. }
  7690. bool VisitCXXNewExpr(const CXXNewExpr *E);
  7691. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  7692. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  7693. APValue LValResult = E->EvaluateInContext(
  7694. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  7695. Result.setFrom(Info.Ctx, LValResult);
  7696. return true;
  7697. }
  7698. bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
  7699. std::string ResultStr = E->ComputeName(Info.Ctx);
  7700. QualType CharTy = Info.Ctx.CharTy.withConst();
  7701. APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
  7702. ResultStr.size() + 1);
  7703. QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
  7704. ArrayType::Normal, 0);
  7705. StringLiteral *SL =
  7706. StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
  7707. /*Pascal*/ false, ArrayTy, E->getLocation());
  7708. evaluateLValue(SL, Result);
  7709. Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
  7710. return true;
  7711. }
  7712. // FIXME: Missing: @protocol, @selector
  7713. };
  7714. } // end anonymous namespace
  7715. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  7716. bool InvalidBaseOK) {
  7717. assert(!E->isValueDependent());
  7718. assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
  7719. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  7720. }
  7721. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7722. if (E->getOpcode() != BO_Add &&
  7723. E->getOpcode() != BO_Sub)
  7724. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7725. const Expr *PExp = E->getLHS();
  7726. const Expr *IExp = E->getRHS();
  7727. if (IExp->getType()->isPointerType())
  7728. std::swap(PExp, IExp);
  7729. bool EvalPtrOK = evaluatePointer(PExp, Result);
  7730. if (!EvalPtrOK && !Info.noteFailure())
  7731. return false;
  7732. llvm::APSInt Offset;
  7733. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  7734. return false;
  7735. if (E->getOpcode() == BO_Sub)
  7736. negateAsSigned(Offset);
  7737. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  7738. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  7739. }
  7740. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  7741. return evaluateLValue(E->getSubExpr(), Result);
  7742. }
  7743. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7744. const Expr *SubExpr = E->getSubExpr();
  7745. switch (E->getCastKind()) {
  7746. default:
  7747. break;
  7748. case CK_BitCast:
  7749. case CK_CPointerToObjCPointerCast:
  7750. case CK_BlockPointerToObjCPointerCast:
  7751. case CK_AnyPointerToBlockPointerCast:
  7752. case CK_AddressSpaceConversion:
  7753. if (!Visit(SubExpr))
  7754. return false;
  7755. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  7756. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  7757. // also static_casts, but we disallow them as a resolution to DR1312.
  7758. if (!E->getType()->isVoidPointerType()) {
  7759. if (!Result.InvalidBase && !Result.Designator.Invalid &&
  7760. !Result.IsNullPtr &&
  7761. Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
  7762. E->getType()->getPointeeType()) &&
  7763. Info.getStdAllocatorCaller("allocate")) {
  7764. // Inside a call to std::allocator::allocate and friends, we permit
  7765. // casting from void* back to cv1 T* for a pointer that points to a
  7766. // cv2 T.
  7767. } else {
  7768. Result.Designator.setInvalid();
  7769. if (SubExpr->getType()->isVoidPointerType())
  7770. CCEDiag(E, diag::note_constexpr_invalid_cast)
  7771. << 3 << SubExpr->getType();
  7772. else
  7773. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7774. }
  7775. }
  7776. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  7777. ZeroInitialization(E);
  7778. return true;
  7779. case CK_DerivedToBase:
  7780. case CK_UncheckedDerivedToBase:
  7781. if (!evaluatePointer(E->getSubExpr(), Result))
  7782. return false;
  7783. if (!Result.Base && Result.Offset.isZero())
  7784. return true;
  7785. // Now figure out the necessary offset to add to the base LV to get from
  7786. // the derived class to the base class.
  7787. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  7788. castAs<PointerType>()->getPointeeType(),
  7789. Result);
  7790. case CK_BaseToDerived:
  7791. if (!Visit(E->getSubExpr()))
  7792. return false;
  7793. if (!Result.Base && Result.Offset.isZero())
  7794. return true;
  7795. return HandleBaseToDerivedCast(Info, E, Result);
  7796. case CK_Dynamic:
  7797. if (!Visit(E->getSubExpr()))
  7798. return false;
  7799. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  7800. case CK_NullToPointer:
  7801. VisitIgnoredValue(E->getSubExpr());
  7802. return ZeroInitialization(E);
  7803. case CK_IntegralToPointer: {
  7804. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7805. APValue Value;
  7806. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  7807. break;
  7808. if (Value.isInt()) {
  7809. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  7810. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  7811. Result.Base = (Expr*)nullptr;
  7812. Result.InvalidBase = false;
  7813. Result.Offset = CharUnits::fromQuantity(N);
  7814. Result.Designator.setInvalid();
  7815. Result.IsNullPtr = false;
  7816. return true;
  7817. } else {
  7818. // Cast is of an lvalue, no need to change value.
  7819. Result.setFrom(Info.Ctx, Value);
  7820. return true;
  7821. }
  7822. }
  7823. case CK_ArrayToPointerDecay: {
  7824. if (SubExpr->isGLValue()) {
  7825. if (!evaluateLValue(SubExpr, Result))
  7826. return false;
  7827. } else {
  7828. APValue &Value = Info.CurrentCall->createTemporary(
  7829. SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
  7830. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  7831. return false;
  7832. }
  7833. // The result is a pointer to the first element of the array.
  7834. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  7835. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  7836. Result.addArray(Info, E, CAT);
  7837. else
  7838. Result.addUnsizedArray(Info, E, AT->getElementType());
  7839. return true;
  7840. }
  7841. case CK_FunctionToPointerDecay:
  7842. return evaluateLValue(SubExpr, Result);
  7843. case CK_LValueToRValue: {
  7844. LValue LVal;
  7845. if (!evaluateLValue(E->getSubExpr(), LVal))
  7846. return false;
  7847. APValue RVal;
  7848. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  7849. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  7850. LVal, RVal))
  7851. return InvalidBaseOK &&
  7852. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  7853. return Success(RVal, E);
  7854. }
  7855. }
  7856. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7857. }
  7858. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  7859. UnaryExprOrTypeTrait ExprKind) {
  7860. // C++ [expr.alignof]p3:
  7861. // When alignof is applied to a reference type, the result is the
  7862. // alignment of the referenced type.
  7863. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  7864. T = Ref->getPointeeType();
  7865. if (T.getQualifiers().hasUnaligned())
  7866. return CharUnits::One();
  7867. const bool AlignOfReturnsPreferred =
  7868. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  7869. // __alignof is defined to return the preferred alignment.
  7870. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  7871. // as well.
  7872. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  7873. return Info.Ctx.toCharUnitsFromBits(
  7874. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  7875. // alignof and _Alignof are defined to return the ABI alignment.
  7876. else if (ExprKind == UETT_AlignOf)
  7877. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  7878. else
  7879. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  7880. }
  7881. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  7882. UnaryExprOrTypeTrait ExprKind) {
  7883. E = E->IgnoreParens();
  7884. // The kinds of expressions that we have special-case logic here for
  7885. // should be kept up to date with the special checks for those
  7886. // expressions in Sema.
  7887. // alignof decl is always accepted, even if it doesn't make sense: we default
  7888. // to 1 in those cases.
  7889. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  7890. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  7891. /*RefAsPointee*/true);
  7892. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  7893. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  7894. /*RefAsPointee*/true);
  7895. return GetAlignOfType(Info, E->getType(), ExprKind);
  7896. }
  7897. static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
  7898. if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
  7899. return Info.Ctx.getDeclAlign(VD);
  7900. if (const auto *E = Value.Base.dyn_cast<const Expr *>())
  7901. return GetAlignOfExpr(Info, E, UETT_AlignOf);
  7902. return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
  7903. }
  7904. /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
  7905. /// __builtin_is_aligned and __builtin_assume_aligned.
  7906. static bool getAlignmentArgument(const Expr *E, QualType ForType,
  7907. EvalInfo &Info, APSInt &Alignment) {
  7908. if (!EvaluateInteger(E, Alignment, Info))
  7909. return false;
  7910. if (Alignment < 0 || !Alignment.isPowerOf2()) {
  7911. Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
  7912. return false;
  7913. }
  7914. unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
  7915. APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
  7916. if (APSInt::compareValues(Alignment, MaxValue) > 0) {
  7917. Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
  7918. << MaxValue << ForType << Alignment;
  7919. return false;
  7920. }
  7921. // Ensure both alignment and source value have the same bit width so that we
  7922. // don't assert when computing the resulting value.
  7923. APSInt ExtAlignment =
  7924. APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
  7925. assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
  7926. "Alignment should not be changed by ext/trunc");
  7927. Alignment = ExtAlignment;
  7928. assert(Alignment.getBitWidth() == SrcWidth);
  7929. return true;
  7930. }
  7931. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  7932. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  7933. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  7934. return true;
  7935. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  7936. return false;
  7937. Result.setInvalid(E);
  7938. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  7939. Result.addUnsizedArray(Info, E, PointeeTy);
  7940. return true;
  7941. }
  7942. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7943. if (IsConstantCall(E))
  7944. return Success(E);
  7945. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7946. return VisitBuiltinCallExpr(E, BuiltinOp);
  7947. return visitNonBuiltinCallExpr(E);
  7948. }
  7949. // Determine if T is a character type for which we guarantee that
  7950. // sizeof(T) == 1.
  7951. static bool isOneByteCharacterType(QualType T) {
  7952. return T->isCharType() || T->isChar8Type();
  7953. }
  7954. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7955. unsigned BuiltinOp) {
  7956. switch (BuiltinOp) {
  7957. case Builtin::BI__builtin_addressof:
  7958. return evaluateLValue(E->getArg(0), Result);
  7959. case Builtin::BI__builtin_assume_aligned: {
  7960. // We need to be very careful here because: if the pointer does not have the
  7961. // asserted alignment, then the behavior is undefined, and undefined
  7962. // behavior is non-constant.
  7963. if (!evaluatePointer(E->getArg(0), Result))
  7964. return false;
  7965. LValue OffsetResult(Result);
  7966. APSInt Alignment;
  7967. if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
  7968. Alignment))
  7969. return false;
  7970. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  7971. if (E->getNumArgs() > 2) {
  7972. APSInt Offset;
  7973. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  7974. return false;
  7975. int64_t AdditionalOffset = -Offset.getZExtValue();
  7976. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  7977. }
  7978. // If there is a base object, then it must have the correct alignment.
  7979. if (OffsetResult.Base) {
  7980. CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
  7981. if (BaseAlignment < Align) {
  7982. Result.Designator.setInvalid();
  7983. // FIXME: Add support to Diagnostic for long / long long.
  7984. CCEDiag(E->getArg(0),
  7985. diag::note_constexpr_baa_insufficient_alignment) << 0
  7986. << (unsigned)BaseAlignment.getQuantity()
  7987. << (unsigned)Align.getQuantity();
  7988. return false;
  7989. }
  7990. }
  7991. // The offset must also have the correct alignment.
  7992. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  7993. Result.Designator.setInvalid();
  7994. (OffsetResult.Base
  7995. ? CCEDiag(E->getArg(0),
  7996. diag::note_constexpr_baa_insufficient_alignment) << 1
  7997. : CCEDiag(E->getArg(0),
  7998. diag::note_constexpr_baa_value_insufficient_alignment))
  7999. << (int)OffsetResult.Offset.getQuantity()
  8000. << (unsigned)Align.getQuantity();
  8001. return false;
  8002. }
  8003. return true;
  8004. }
  8005. case Builtin::BI__builtin_align_up:
  8006. case Builtin::BI__builtin_align_down: {
  8007. if (!evaluatePointer(E->getArg(0), Result))
  8008. return false;
  8009. APSInt Alignment;
  8010. if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
  8011. Alignment))
  8012. return false;
  8013. CharUnits BaseAlignment = getBaseAlignment(Info, Result);
  8014. CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
  8015. // For align_up/align_down, we can return the same value if the alignment
  8016. // is known to be greater or equal to the requested value.
  8017. if (PtrAlign.getQuantity() >= Alignment)
  8018. return true;
  8019. // The alignment could be greater than the minimum at run-time, so we cannot
  8020. // infer much about the resulting pointer value. One case is possible:
  8021. // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
  8022. // can infer the correct index if the requested alignment is smaller than
  8023. // the base alignment so we can perform the computation on the offset.
  8024. if (BaseAlignment.getQuantity() >= Alignment) {
  8025. assert(Alignment.getBitWidth() <= 64 &&
  8026. "Cannot handle > 64-bit address-space");
  8027. uint64_t Alignment64 = Alignment.getZExtValue();
  8028. CharUnits NewOffset = CharUnits::fromQuantity(
  8029. BuiltinOp == Builtin::BI__builtin_align_down
  8030. ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
  8031. : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
  8032. Result.adjustOffset(NewOffset - Result.Offset);
  8033. // TODO: diagnose out-of-bounds values/only allow for arrays?
  8034. return true;
  8035. }
  8036. // Otherwise, we cannot constant-evaluate the result.
  8037. Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
  8038. << Alignment;
  8039. return false;
  8040. }
  8041. case Builtin::BI__builtin_operator_new:
  8042. return HandleOperatorNewCall(Info, E, Result);
  8043. case Builtin::BI__builtin_launder:
  8044. return evaluatePointer(E->getArg(0), Result);
  8045. case Builtin::BIstrchr:
  8046. case Builtin::BIwcschr:
  8047. case Builtin::BImemchr:
  8048. case Builtin::BIwmemchr:
  8049. if (Info.getLangOpts().CPlusPlus11)
  8050. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8051. << /*isConstexpr*/0 << /*isConstructor*/0
  8052. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8053. else
  8054. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8055. LLVM_FALLTHROUGH;
  8056. case Builtin::BI__builtin_strchr:
  8057. case Builtin::BI__builtin_wcschr:
  8058. case Builtin::BI__builtin_memchr:
  8059. case Builtin::BI__builtin_char_memchr:
  8060. case Builtin::BI__builtin_wmemchr: {
  8061. if (!Visit(E->getArg(0)))
  8062. return false;
  8063. APSInt Desired;
  8064. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  8065. return false;
  8066. uint64_t MaxLength = uint64_t(-1);
  8067. if (BuiltinOp != Builtin::BIstrchr &&
  8068. BuiltinOp != Builtin::BIwcschr &&
  8069. BuiltinOp != Builtin::BI__builtin_strchr &&
  8070. BuiltinOp != Builtin::BI__builtin_wcschr) {
  8071. APSInt N;
  8072. if (!EvaluateInteger(E->getArg(2), N, Info))
  8073. return false;
  8074. MaxLength = N.getExtValue();
  8075. }
  8076. // We cannot find the value if there are no candidates to match against.
  8077. if (MaxLength == 0u)
  8078. return ZeroInitialization(E);
  8079. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8080. Result.Designator.Invalid)
  8081. return false;
  8082. QualType CharTy = Result.Designator.getType(Info.Ctx);
  8083. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  8084. BuiltinOp == Builtin::BI__builtin_memchr;
  8085. assert(IsRawByte ||
  8086. Info.Ctx.hasSameUnqualifiedType(
  8087. CharTy, E->getArg(0)->getType()->getPointeeType()));
  8088. // Pointers to const void may point to objects of incomplete type.
  8089. if (IsRawByte && CharTy->isIncompleteType()) {
  8090. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  8091. return false;
  8092. }
  8093. // Give up on byte-oriented matching against multibyte elements.
  8094. // FIXME: We can compare the bytes in the correct order.
  8095. if (IsRawByte && !isOneByteCharacterType(CharTy)) {
  8096. Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
  8097. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
  8098. << CharTy;
  8099. return false;
  8100. }
  8101. // Figure out what value we're actually looking for (after converting to
  8102. // the corresponding unsigned type if necessary).
  8103. uint64_t DesiredVal;
  8104. bool StopAtNull = false;
  8105. switch (BuiltinOp) {
  8106. case Builtin::BIstrchr:
  8107. case Builtin::BI__builtin_strchr:
  8108. // strchr compares directly to the passed integer, and therefore
  8109. // always fails if given an int that is not a char.
  8110. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  8111. E->getArg(1)->getType(),
  8112. Desired),
  8113. Desired))
  8114. return ZeroInitialization(E);
  8115. StopAtNull = true;
  8116. LLVM_FALLTHROUGH;
  8117. case Builtin::BImemchr:
  8118. case Builtin::BI__builtin_memchr:
  8119. case Builtin::BI__builtin_char_memchr:
  8120. // memchr compares by converting both sides to unsigned char. That's also
  8121. // correct for strchr if we get this far (to cope with plain char being
  8122. // unsigned in the strchr case).
  8123. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  8124. break;
  8125. case Builtin::BIwcschr:
  8126. case Builtin::BI__builtin_wcschr:
  8127. StopAtNull = true;
  8128. LLVM_FALLTHROUGH;
  8129. case Builtin::BIwmemchr:
  8130. case Builtin::BI__builtin_wmemchr:
  8131. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  8132. DesiredVal = Desired.getZExtValue();
  8133. break;
  8134. }
  8135. for (; MaxLength; --MaxLength) {
  8136. APValue Char;
  8137. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  8138. !Char.isInt())
  8139. return false;
  8140. if (Char.getInt().getZExtValue() == DesiredVal)
  8141. return true;
  8142. if (StopAtNull && !Char.getInt())
  8143. break;
  8144. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  8145. return false;
  8146. }
  8147. // Not found: return nullptr.
  8148. return ZeroInitialization(E);
  8149. }
  8150. case Builtin::BImemcpy:
  8151. case Builtin::BImemmove:
  8152. case Builtin::BIwmemcpy:
  8153. case Builtin::BIwmemmove:
  8154. if (Info.getLangOpts().CPlusPlus11)
  8155. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8156. << /*isConstexpr*/0 << /*isConstructor*/0
  8157. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8158. else
  8159. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8160. LLVM_FALLTHROUGH;
  8161. case Builtin::BI__builtin_memcpy:
  8162. case Builtin::BI__builtin_memmove:
  8163. case Builtin::BI__builtin_wmemcpy:
  8164. case Builtin::BI__builtin_wmemmove: {
  8165. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  8166. BuiltinOp == Builtin::BIwmemmove ||
  8167. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  8168. BuiltinOp == Builtin::BI__builtin_wmemmove;
  8169. bool Move = BuiltinOp == Builtin::BImemmove ||
  8170. BuiltinOp == Builtin::BIwmemmove ||
  8171. BuiltinOp == Builtin::BI__builtin_memmove ||
  8172. BuiltinOp == Builtin::BI__builtin_wmemmove;
  8173. // The result of mem* is the first argument.
  8174. if (!Visit(E->getArg(0)))
  8175. return false;
  8176. LValue Dest = Result;
  8177. LValue Src;
  8178. if (!EvaluatePointer(E->getArg(1), Src, Info))
  8179. return false;
  8180. APSInt N;
  8181. if (!EvaluateInteger(E->getArg(2), N, Info))
  8182. return false;
  8183. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  8184. // If the size is zero, we treat this as always being a valid no-op.
  8185. // (Even if one of the src and dest pointers is null.)
  8186. if (!N)
  8187. return true;
  8188. // Otherwise, if either of the operands is null, we can't proceed. Don't
  8189. // try to determine the type of the copied objects, because there aren't
  8190. // any.
  8191. if (!Src.Base || !Dest.Base) {
  8192. APValue Val;
  8193. (!Src.Base ? Src : Dest).moveInto(Val);
  8194. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  8195. << Move << WChar << !!Src.Base
  8196. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  8197. return false;
  8198. }
  8199. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  8200. return false;
  8201. // We require that Src and Dest are both pointers to arrays of
  8202. // trivially-copyable type. (For the wide version, the designator will be
  8203. // invalid if the designated object is not a wchar_t.)
  8204. QualType T = Dest.Designator.getType(Info.Ctx);
  8205. QualType SrcT = Src.Designator.getType(Info.Ctx);
  8206. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  8207. // FIXME: Consider using our bit_cast implementation to support this.
  8208. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  8209. return false;
  8210. }
  8211. if (T->isIncompleteType()) {
  8212. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  8213. return false;
  8214. }
  8215. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  8216. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  8217. return false;
  8218. }
  8219. // Figure out how many T's we're copying.
  8220. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  8221. if (!WChar) {
  8222. uint64_t Remainder;
  8223. llvm::APInt OrigN = N;
  8224. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  8225. if (Remainder) {
  8226. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  8227. << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
  8228. << (unsigned)TSize;
  8229. return false;
  8230. }
  8231. }
  8232. // Check that the copying will remain within the arrays, just so that we
  8233. // can give a more meaningful diagnostic. This implicitly also checks that
  8234. // N fits into 64 bits.
  8235. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  8236. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  8237. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  8238. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  8239. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  8240. << toString(N, 10, /*Signed*/false);
  8241. return false;
  8242. }
  8243. uint64_t NElems = N.getZExtValue();
  8244. uint64_t NBytes = NElems * TSize;
  8245. // Check for overlap.
  8246. int Direction = 1;
  8247. if (HasSameBase(Src, Dest)) {
  8248. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  8249. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  8250. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  8251. // Dest is inside the source region.
  8252. if (!Move) {
  8253. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  8254. return false;
  8255. }
  8256. // For memmove and friends, copy backwards.
  8257. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  8258. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  8259. return false;
  8260. Direction = -1;
  8261. } else if (!Move && SrcOffset >= DestOffset &&
  8262. SrcOffset - DestOffset < NBytes) {
  8263. // Src is inside the destination region for memcpy: invalid.
  8264. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  8265. return false;
  8266. }
  8267. }
  8268. while (true) {
  8269. APValue Val;
  8270. // FIXME: Set WantObjectRepresentation to true if we're copying a
  8271. // char-like type?
  8272. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  8273. !handleAssignment(Info, E, Dest, T, Val))
  8274. return false;
  8275. // Do not iterate past the last element; if we're copying backwards, that
  8276. // might take us off the start of the array.
  8277. if (--NElems == 0)
  8278. return true;
  8279. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  8280. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  8281. return false;
  8282. }
  8283. }
  8284. default:
  8285. break;
  8286. }
  8287. return visitNonBuiltinCallExpr(E);
  8288. }
  8289. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  8290. APValue &Result, const InitListExpr *ILE,
  8291. QualType AllocType);
  8292. static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
  8293. APValue &Result,
  8294. const CXXConstructExpr *CCE,
  8295. QualType AllocType);
  8296. bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
  8297. if (!Info.getLangOpts().CPlusPlus20)
  8298. Info.CCEDiag(E, diag::note_constexpr_new);
  8299. // We cannot speculatively evaluate a delete expression.
  8300. if (Info.SpeculativeEvaluationDepth)
  8301. return false;
  8302. FunctionDecl *OperatorNew = E->getOperatorNew();
  8303. bool IsNothrow = false;
  8304. bool IsPlacement = false;
  8305. if (OperatorNew->isReservedGlobalPlacementOperator() &&
  8306. Info.CurrentCall->isStdFunction() && !E->isArray()) {
  8307. // FIXME Support array placement new.
  8308. assert(E->getNumPlacementArgs() == 1);
  8309. if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
  8310. return false;
  8311. if (Result.Designator.Invalid)
  8312. return false;
  8313. IsPlacement = true;
  8314. } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
  8315. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  8316. << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
  8317. return false;
  8318. } else if (E->getNumPlacementArgs()) {
  8319. // The only new-placement list we support is of the form (std::nothrow).
  8320. //
  8321. // FIXME: There is no restriction on this, but it's not clear that any
  8322. // other form makes any sense. We get here for cases such as:
  8323. //
  8324. // new (std::align_val_t{N}) X(int)
  8325. //
  8326. // (which should presumably be valid only if N is a multiple of
  8327. // alignof(int), and in any case can't be deallocated unless N is
  8328. // alignof(X) and X has new-extended alignment).
  8329. if (E->getNumPlacementArgs() != 1 ||
  8330. !E->getPlacementArg(0)->getType()->isNothrowT())
  8331. return Error(E, diag::note_constexpr_new_placement);
  8332. LValue Nothrow;
  8333. if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
  8334. return false;
  8335. IsNothrow = true;
  8336. }
  8337. const Expr *Init = E->getInitializer();
  8338. const InitListExpr *ResizedArrayILE = nullptr;
  8339. const CXXConstructExpr *ResizedArrayCCE = nullptr;
  8340. bool ValueInit = false;
  8341. QualType AllocType = E->getAllocatedType();
  8342. if (Optional<const Expr*> ArraySize = E->getArraySize()) {
  8343. const Expr *Stripped = *ArraySize;
  8344. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
  8345. Stripped = ICE->getSubExpr())
  8346. if (ICE->getCastKind() != CK_NoOp &&
  8347. ICE->getCastKind() != CK_IntegralCast)
  8348. break;
  8349. llvm::APSInt ArrayBound;
  8350. if (!EvaluateInteger(Stripped, ArrayBound, Info))
  8351. return false;
  8352. // C++ [expr.new]p9:
  8353. // The expression is erroneous if:
  8354. // -- [...] its value before converting to size_t [or] applying the
  8355. // second standard conversion sequence is less than zero
  8356. if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
  8357. if (IsNothrow)
  8358. return ZeroInitialization(E);
  8359. Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
  8360. << ArrayBound << (*ArraySize)->getSourceRange();
  8361. return false;
  8362. }
  8363. // -- its value is such that the size of the allocated object would
  8364. // exceed the implementation-defined limit
  8365. if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
  8366. ArrayBound) >
  8367. ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
  8368. if (IsNothrow)
  8369. return ZeroInitialization(E);
  8370. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
  8371. << ArrayBound << (*ArraySize)->getSourceRange();
  8372. return false;
  8373. }
  8374. // -- the new-initializer is a braced-init-list and the number of
  8375. // array elements for which initializers are provided [...]
  8376. // exceeds the number of elements to initialize
  8377. if (!Init) {
  8378. // No initialization is performed.
  8379. } else if (isa<CXXScalarValueInitExpr>(Init) ||
  8380. isa<ImplicitValueInitExpr>(Init)) {
  8381. ValueInit = true;
  8382. } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  8383. ResizedArrayCCE = CCE;
  8384. } else {
  8385. auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
  8386. assert(CAT && "unexpected type for array initializer");
  8387. unsigned Bits =
  8388. std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
  8389. llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
  8390. llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
  8391. if (InitBound.ugt(AllocBound)) {
  8392. if (IsNothrow)
  8393. return ZeroInitialization(E);
  8394. Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
  8395. << toString(AllocBound, 10, /*Signed=*/false)
  8396. << toString(InitBound, 10, /*Signed=*/false)
  8397. << (*ArraySize)->getSourceRange();
  8398. return false;
  8399. }
  8400. // If the sizes differ, we must have an initializer list, and we need
  8401. // special handling for this case when we initialize.
  8402. if (InitBound != AllocBound)
  8403. ResizedArrayILE = cast<InitListExpr>(Init);
  8404. }
  8405. AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
  8406. ArrayType::Normal, 0);
  8407. } else {
  8408. assert(!AllocType->isArrayType() &&
  8409. "array allocation with non-array new");
  8410. }
  8411. APValue *Val;
  8412. if (IsPlacement) {
  8413. AccessKinds AK = AK_Construct;
  8414. struct FindObjectHandler {
  8415. EvalInfo &Info;
  8416. const Expr *E;
  8417. QualType AllocType;
  8418. const AccessKinds AccessKind;
  8419. APValue *Value;
  8420. typedef bool result_type;
  8421. bool failed() { return false; }
  8422. bool found(APValue &Subobj, QualType SubobjType) {
  8423. // FIXME: Reject the cases where [basic.life]p8 would not permit the
  8424. // old name of the object to be used to name the new object.
  8425. if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
  8426. Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
  8427. SubobjType << AllocType;
  8428. return false;
  8429. }
  8430. Value = &Subobj;
  8431. return true;
  8432. }
  8433. bool found(APSInt &Value, QualType SubobjType) {
  8434. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  8435. return false;
  8436. }
  8437. bool found(APFloat &Value, QualType SubobjType) {
  8438. Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
  8439. return false;
  8440. }
  8441. } Handler = {Info, E, AllocType, AK, nullptr};
  8442. CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
  8443. if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
  8444. return false;
  8445. Val = Handler.Value;
  8446. // [basic.life]p1:
  8447. // The lifetime of an object o of type T ends when [...] the storage
  8448. // which the object occupies is [...] reused by an object that is not
  8449. // nested within o (6.6.2).
  8450. *Val = APValue();
  8451. } else {
  8452. // Perform the allocation and obtain a pointer to the resulting object.
  8453. Val = Info.createHeapAlloc(E, AllocType, Result);
  8454. if (!Val)
  8455. return false;
  8456. }
  8457. if (ValueInit) {
  8458. ImplicitValueInitExpr VIE(AllocType);
  8459. if (!EvaluateInPlace(*Val, Info, Result, &VIE))
  8460. return false;
  8461. } else if (ResizedArrayILE) {
  8462. if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
  8463. AllocType))
  8464. return false;
  8465. } else if (ResizedArrayCCE) {
  8466. if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
  8467. AllocType))
  8468. return false;
  8469. } else if (Init) {
  8470. if (!EvaluateInPlace(*Val, Info, Result, Init))
  8471. return false;
  8472. } else if (!getDefaultInitValue(AllocType, *Val)) {
  8473. return false;
  8474. }
  8475. // Array new returns a pointer to the first element, not a pointer to the
  8476. // array.
  8477. if (auto *AT = AllocType->getAsArrayTypeUnsafe())
  8478. Result.addArray(Info, E, cast<ConstantArrayType>(AT));
  8479. return true;
  8480. }
  8481. //===----------------------------------------------------------------------===//
  8482. // Member Pointer Evaluation
  8483. //===----------------------------------------------------------------------===//
  8484. namespace {
  8485. class MemberPointerExprEvaluator
  8486. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  8487. MemberPtr &Result;
  8488. bool Success(const ValueDecl *D) {
  8489. Result = MemberPtr(D);
  8490. return true;
  8491. }
  8492. public:
  8493. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  8494. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  8495. bool Success(const APValue &V, const Expr *E) {
  8496. Result.setFrom(V);
  8497. return true;
  8498. }
  8499. bool ZeroInitialization(const Expr *E) {
  8500. return Success((const ValueDecl*)nullptr);
  8501. }
  8502. bool VisitCastExpr(const CastExpr *E);
  8503. bool VisitUnaryAddrOf(const UnaryOperator *E);
  8504. };
  8505. } // end anonymous namespace
  8506. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  8507. EvalInfo &Info) {
  8508. assert(!E->isValueDependent());
  8509. assert(E->isPRValue() && E->getType()->isMemberPointerType());
  8510. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  8511. }
  8512. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8513. switch (E->getCastKind()) {
  8514. default:
  8515. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8516. case CK_NullToMemberPointer:
  8517. VisitIgnoredValue(E->getSubExpr());
  8518. return ZeroInitialization(E);
  8519. case CK_BaseToDerivedMemberPointer: {
  8520. if (!Visit(E->getSubExpr()))
  8521. return false;
  8522. if (E->path_empty())
  8523. return true;
  8524. // Base-to-derived member pointer casts store the path in derived-to-base
  8525. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  8526. // the wrong end of the derived->base arc, so stagger the path by one class.
  8527. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  8528. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  8529. PathI != PathE; ++PathI) {
  8530. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  8531. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  8532. if (!Result.castToDerived(Derived))
  8533. return Error(E);
  8534. }
  8535. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  8536. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  8537. return Error(E);
  8538. return true;
  8539. }
  8540. case CK_DerivedToBaseMemberPointer:
  8541. if (!Visit(E->getSubExpr()))
  8542. return false;
  8543. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  8544. PathE = E->path_end(); PathI != PathE; ++PathI) {
  8545. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  8546. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  8547. if (!Result.castToBase(Base))
  8548. return Error(E);
  8549. }
  8550. return true;
  8551. }
  8552. }
  8553. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  8554. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  8555. // member can be formed.
  8556. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  8557. }
  8558. //===----------------------------------------------------------------------===//
  8559. // Record Evaluation
  8560. //===----------------------------------------------------------------------===//
  8561. namespace {
  8562. class RecordExprEvaluator
  8563. : public ExprEvaluatorBase<RecordExprEvaluator> {
  8564. const LValue &This;
  8565. APValue &Result;
  8566. public:
  8567. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  8568. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  8569. bool Success(const APValue &V, const Expr *E) {
  8570. Result = V;
  8571. return true;
  8572. }
  8573. bool ZeroInitialization(const Expr *E) {
  8574. return ZeroInitialization(E, E->getType());
  8575. }
  8576. bool ZeroInitialization(const Expr *E, QualType T);
  8577. bool VisitCallExpr(const CallExpr *E) {
  8578. return handleCallExpr(E, Result, &This);
  8579. }
  8580. bool VisitCastExpr(const CastExpr *E);
  8581. bool VisitInitListExpr(const InitListExpr *E);
  8582. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8583. return VisitCXXConstructExpr(E, E->getType());
  8584. }
  8585. bool VisitLambdaExpr(const LambdaExpr *E);
  8586. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  8587. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  8588. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  8589. bool VisitBinCmp(const BinaryOperator *E);
  8590. };
  8591. }
  8592. /// Perform zero-initialization on an object of non-union class type.
  8593. /// C++11 [dcl.init]p5:
  8594. /// To zero-initialize an object or reference of type T means:
  8595. /// [...]
  8596. /// -- if T is a (possibly cv-qualified) non-union class type,
  8597. /// each non-static data member and each base-class subobject is
  8598. /// zero-initialized
  8599. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  8600. const RecordDecl *RD,
  8601. const LValue &This, APValue &Result) {
  8602. assert(!RD->isUnion() && "Expected non-union class type");
  8603. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  8604. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  8605. std::distance(RD->field_begin(), RD->field_end()));
  8606. if (RD->isInvalidDecl()) return false;
  8607. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  8608. if (CD) {
  8609. unsigned Index = 0;
  8610. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  8611. End = CD->bases_end(); I != End; ++I, ++Index) {
  8612. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  8613. LValue Subobject = This;
  8614. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  8615. return false;
  8616. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  8617. Result.getStructBase(Index)))
  8618. return false;
  8619. }
  8620. }
  8621. for (const auto *I : RD->fields()) {
  8622. // -- if T is a reference type, no initialization is performed.
  8623. if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
  8624. continue;
  8625. LValue Subobject = This;
  8626. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  8627. return false;
  8628. ImplicitValueInitExpr VIE(I->getType());
  8629. if (!EvaluateInPlace(
  8630. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  8631. return false;
  8632. }
  8633. return true;
  8634. }
  8635. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  8636. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  8637. if (RD->isInvalidDecl()) return false;
  8638. if (RD->isUnion()) {
  8639. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  8640. // object's first non-static named data member is zero-initialized
  8641. RecordDecl::field_iterator I = RD->field_begin();
  8642. while (I != RD->field_end() && (*I)->isUnnamedBitfield())
  8643. ++I;
  8644. if (I == RD->field_end()) {
  8645. Result = APValue((const FieldDecl*)nullptr);
  8646. return true;
  8647. }
  8648. LValue Subobject = This;
  8649. if (!HandleLValueMember(Info, E, Subobject, *I))
  8650. return false;
  8651. Result = APValue(*I);
  8652. ImplicitValueInitExpr VIE(I->getType());
  8653. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  8654. }
  8655. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  8656. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  8657. return false;
  8658. }
  8659. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  8660. }
  8661. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8662. switch (E->getCastKind()) {
  8663. default:
  8664. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8665. case CK_ConstructorConversion:
  8666. return Visit(E->getSubExpr());
  8667. case CK_DerivedToBase:
  8668. case CK_UncheckedDerivedToBase: {
  8669. APValue DerivedObject;
  8670. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  8671. return false;
  8672. if (!DerivedObject.isStruct())
  8673. return Error(E->getSubExpr());
  8674. // Derived-to-base rvalue conversion: just slice off the derived part.
  8675. APValue *Value = &DerivedObject;
  8676. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  8677. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  8678. PathE = E->path_end(); PathI != PathE; ++PathI) {
  8679. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  8680. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  8681. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  8682. RD = Base;
  8683. }
  8684. Result = *Value;
  8685. return true;
  8686. }
  8687. }
  8688. }
  8689. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  8690. if (E->isTransparent())
  8691. return Visit(E->getInit(0));
  8692. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  8693. if (RD->isInvalidDecl()) return false;
  8694. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  8695. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  8696. EvalInfo::EvaluatingConstructorRAII EvalObj(
  8697. Info,
  8698. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  8699. CXXRD && CXXRD->getNumBases());
  8700. if (RD->isUnion()) {
  8701. const FieldDecl *Field = E->getInitializedFieldInUnion();
  8702. Result = APValue(Field);
  8703. if (!Field)
  8704. return true;
  8705. // If the initializer list for a union does not contain any elements, the
  8706. // first element of the union is value-initialized.
  8707. // FIXME: The element should be initialized from an initializer list.
  8708. // Is this difference ever observable for initializer lists which
  8709. // we don't build?
  8710. ImplicitValueInitExpr VIE(Field->getType());
  8711. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  8712. LValue Subobject = This;
  8713. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  8714. return false;
  8715. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  8716. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  8717. isa<CXXDefaultInitExpr>(InitExpr));
  8718. if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
  8719. if (Field->isBitField())
  8720. return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
  8721. Field);
  8722. return true;
  8723. }
  8724. return false;
  8725. }
  8726. if (!Result.hasValue())
  8727. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  8728. std::distance(RD->field_begin(), RD->field_end()));
  8729. unsigned ElementNo = 0;
  8730. bool Success = true;
  8731. // Initialize base classes.
  8732. if (CXXRD && CXXRD->getNumBases()) {
  8733. for (const auto &Base : CXXRD->bases()) {
  8734. assert(ElementNo < E->getNumInits() && "missing init for base class");
  8735. const Expr *Init = E->getInit(ElementNo);
  8736. LValue Subobject = This;
  8737. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  8738. return false;
  8739. APValue &FieldVal = Result.getStructBase(ElementNo);
  8740. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  8741. if (!Info.noteFailure())
  8742. return false;
  8743. Success = false;
  8744. }
  8745. ++ElementNo;
  8746. }
  8747. EvalObj.finishedConstructingBases();
  8748. }
  8749. // Initialize members.
  8750. for (const auto *Field : RD->fields()) {
  8751. // Anonymous bit-fields are not considered members of the class for
  8752. // purposes of aggregate initialization.
  8753. if (Field->isUnnamedBitfield())
  8754. continue;
  8755. LValue Subobject = This;
  8756. bool HaveInit = ElementNo < E->getNumInits();
  8757. // FIXME: Diagnostics here should point to the end of the initializer
  8758. // list, not the start.
  8759. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  8760. Subobject, Field, &Layout))
  8761. return false;
  8762. // Perform an implicit value-initialization for members beyond the end of
  8763. // the initializer list.
  8764. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  8765. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  8766. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  8767. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  8768. isa<CXXDefaultInitExpr>(Init));
  8769. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  8770. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  8771. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  8772. FieldVal, Field))) {
  8773. if (!Info.noteFailure())
  8774. return false;
  8775. Success = false;
  8776. }
  8777. }
  8778. EvalObj.finishedConstructingFields();
  8779. return Success;
  8780. }
  8781. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  8782. QualType T) {
  8783. // Note that E's type is not necessarily the type of our class here; we might
  8784. // be initializing an array element instead.
  8785. const CXXConstructorDecl *FD = E->getConstructor();
  8786. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  8787. bool ZeroInit = E->requiresZeroInitialization();
  8788. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  8789. // If we've already performed zero-initialization, we're already done.
  8790. if (Result.hasValue())
  8791. return true;
  8792. if (ZeroInit)
  8793. return ZeroInitialization(E, T);
  8794. return getDefaultInitValue(T, Result);
  8795. }
  8796. const FunctionDecl *Definition = nullptr;
  8797. auto Body = FD->getBody(Definition);
  8798. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  8799. return false;
  8800. // Avoid materializing a temporary for an elidable copy/move constructor.
  8801. if (E->isElidable() && !ZeroInit) {
  8802. // FIXME: This only handles the simplest case, where the source object
  8803. // is passed directly as the first argument to the constructor.
  8804. // This should also handle stepping though implicit casts and
  8805. // and conversion sequences which involve two steps, with a
  8806. // conversion operator followed by a converting constructor.
  8807. const Expr *SrcObj = E->getArg(0);
  8808. assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
  8809. assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
  8810. if (const MaterializeTemporaryExpr *ME =
  8811. dyn_cast<MaterializeTemporaryExpr>(SrcObj))
  8812. return Visit(ME->getSubExpr());
  8813. }
  8814. if (ZeroInit && !ZeroInitialization(E, T))
  8815. return false;
  8816. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  8817. return HandleConstructorCall(E, This, Args,
  8818. cast<CXXConstructorDecl>(Definition), Info,
  8819. Result);
  8820. }
  8821. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  8822. const CXXInheritedCtorInitExpr *E) {
  8823. if (!Info.CurrentCall) {
  8824. assert(Info.checkingPotentialConstantExpression());
  8825. return false;
  8826. }
  8827. const CXXConstructorDecl *FD = E->getConstructor();
  8828. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  8829. return false;
  8830. const FunctionDecl *Definition = nullptr;
  8831. auto Body = FD->getBody(Definition);
  8832. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  8833. return false;
  8834. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  8835. cast<CXXConstructorDecl>(Definition), Info,
  8836. Result);
  8837. }
  8838. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  8839. const CXXStdInitializerListExpr *E) {
  8840. const ConstantArrayType *ArrayType =
  8841. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  8842. LValue Array;
  8843. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  8844. return false;
  8845. // Get a pointer to the first element of the array.
  8846. Array.addArray(Info, E, ArrayType);
  8847. auto InvalidType = [&] {
  8848. Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
  8849. << E->getType();
  8850. return false;
  8851. };
  8852. // FIXME: Perform the checks on the field types in SemaInit.
  8853. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  8854. RecordDecl::field_iterator Field = Record->field_begin();
  8855. if (Field == Record->field_end())
  8856. return InvalidType();
  8857. // Start pointer.
  8858. if (!Field->getType()->isPointerType() ||
  8859. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  8860. ArrayType->getElementType()))
  8861. return InvalidType();
  8862. // FIXME: What if the initializer_list type has base classes, etc?
  8863. Result = APValue(APValue::UninitStruct(), 0, 2);
  8864. Array.moveInto(Result.getStructField(0));
  8865. if (++Field == Record->field_end())
  8866. return InvalidType();
  8867. if (Field->getType()->isPointerType() &&
  8868. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  8869. ArrayType->getElementType())) {
  8870. // End pointer.
  8871. if (!HandleLValueArrayAdjustment(Info, E, Array,
  8872. ArrayType->getElementType(),
  8873. ArrayType->getSize().getZExtValue()))
  8874. return false;
  8875. Array.moveInto(Result.getStructField(1));
  8876. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  8877. // Length.
  8878. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  8879. else
  8880. return InvalidType();
  8881. if (++Field != Record->field_end())
  8882. return InvalidType();
  8883. return true;
  8884. }
  8885. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  8886. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  8887. if (ClosureClass->isInvalidDecl())
  8888. return false;
  8889. const size_t NumFields =
  8890. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  8891. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  8892. E->capture_init_end()) &&
  8893. "The number of lambda capture initializers should equal the number of "
  8894. "fields within the closure type");
  8895. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  8896. // Iterate through all the lambda's closure object's fields and initialize
  8897. // them.
  8898. auto *CaptureInitIt = E->capture_init_begin();
  8899. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  8900. bool Success = true;
  8901. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
  8902. for (const auto *Field : ClosureClass->fields()) {
  8903. assert(CaptureInitIt != E->capture_init_end());
  8904. // Get the initializer for this field
  8905. Expr *const CurFieldInit = *CaptureInitIt++;
  8906. // If there is no initializer, either this is a VLA or an error has
  8907. // occurred.
  8908. if (!CurFieldInit)
  8909. return Error(E);
  8910. LValue Subobject = This;
  8911. if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
  8912. return false;
  8913. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  8914. if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
  8915. if (!Info.keepEvaluatingAfterFailure())
  8916. return false;
  8917. Success = false;
  8918. }
  8919. ++CaptureIt;
  8920. }
  8921. return Success;
  8922. }
  8923. static bool EvaluateRecord(const Expr *E, const LValue &This,
  8924. APValue &Result, EvalInfo &Info) {
  8925. assert(!E->isValueDependent());
  8926. assert(E->isPRValue() && E->getType()->isRecordType() &&
  8927. "can't evaluate expression as a record rvalue");
  8928. return RecordExprEvaluator(Info, This, Result).Visit(E);
  8929. }
  8930. //===----------------------------------------------------------------------===//
  8931. // Temporary Evaluation
  8932. //
  8933. // Temporaries are represented in the AST as rvalues, but generally behave like
  8934. // lvalues. The full-object of which the temporary is a subobject is implicitly
  8935. // materialized so that a reference can bind to it.
  8936. //===----------------------------------------------------------------------===//
  8937. namespace {
  8938. class TemporaryExprEvaluator
  8939. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  8940. public:
  8941. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  8942. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  8943. /// Visit an expression which constructs the value of this temporary.
  8944. bool VisitConstructExpr(const Expr *E) {
  8945. APValue &Value = Info.CurrentCall->createTemporary(
  8946. E, E->getType(), ScopeKind::FullExpression, Result);
  8947. return EvaluateInPlace(Value, Info, Result, E);
  8948. }
  8949. bool VisitCastExpr(const CastExpr *E) {
  8950. switch (E->getCastKind()) {
  8951. default:
  8952. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  8953. case CK_ConstructorConversion:
  8954. return VisitConstructExpr(E->getSubExpr());
  8955. }
  8956. }
  8957. bool VisitInitListExpr(const InitListExpr *E) {
  8958. return VisitConstructExpr(E);
  8959. }
  8960. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  8961. return VisitConstructExpr(E);
  8962. }
  8963. bool VisitCallExpr(const CallExpr *E) {
  8964. return VisitConstructExpr(E);
  8965. }
  8966. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  8967. return VisitConstructExpr(E);
  8968. }
  8969. bool VisitLambdaExpr(const LambdaExpr *E) {
  8970. return VisitConstructExpr(E);
  8971. }
  8972. };
  8973. } // end anonymous namespace
  8974. /// Evaluate an expression of record type as a temporary.
  8975. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  8976. assert(!E->isValueDependent());
  8977. assert(E->isPRValue() && E->getType()->isRecordType());
  8978. return TemporaryExprEvaluator(Info, Result).Visit(E);
  8979. }
  8980. //===----------------------------------------------------------------------===//
  8981. // Vector Evaluation
  8982. //===----------------------------------------------------------------------===//
  8983. namespace {
  8984. class VectorExprEvaluator
  8985. : public ExprEvaluatorBase<VectorExprEvaluator> {
  8986. APValue &Result;
  8987. public:
  8988. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  8989. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8990. bool Success(ArrayRef<APValue> V, const Expr *E) {
  8991. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  8992. // FIXME: remove this APValue copy.
  8993. Result = APValue(V.data(), V.size());
  8994. return true;
  8995. }
  8996. bool Success(const APValue &V, const Expr *E) {
  8997. assert(V.isVector());
  8998. Result = V;
  8999. return true;
  9000. }
  9001. bool ZeroInitialization(const Expr *E);
  9002. bool VisitUnaryReal(const UnaryOperator *E)
  9003. { return Visit(E->getSubExpr()); }
  9004. bool VisitCastExpr(const CastExpr* E);
  9005. bool VisitInitListExpr(const InitListExpr *E);
  9006. bool VisitUnaryImag(const UnaryOperator *E);
  9007. bool VisitBinaryOperator(const BinaryOperator *E);
  9008. bool VisitUnaryOperator(const UnaryOperator *E);
  9009. // FIXME: Missing: conditional operator (for GNU
  9010. // conditional select), shufflevector, ExtVectorElementExpr
  9011. };
  9012. } // end anonymous namespace
  9013. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  9014. assert(E->isPRValue() && E->getType()->isVectorType() &&
  9015. "not a vector prvalue");
  9016. return VectorExprEvaluator(Info, Result).Visit(E);
  9017. }
  9018. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9019. const VectorType *VTy = E->getType()->castAs<VectorType>();
  9020. unsigned NElts = VTy->getNumElements();
  9021. const Expr *SE = E->getSubExpr();
  9022. QualType SETy = SE->getType();
  9023. switch (E->getCastKind()) {
  9024. case CK_VectorSplat: {
  9025. APValue Val = APValue();
  9026. if (SETy->isIntegerType()) {
  9027. APSInt IntResult;
  9028. if (!EvaluateInteger(SE, IntResult, Info))
  9029. return false;
  9030. Val = APValue(std::move(IntResult));
  9031. } else if (SETy->isRealFloatingType()) {
  9032. APFloat FloatResult(0.0);
  9033. if (!EvaluateFloat(SE, FloatResult, Info))
  9034. return false;
  9035. Val = APValue(std::move(FloatResult));
  9036. } else {
  9037. return Error(E);
  9038. }
  9039. // Splat and create vector APValue.
  9040. SmallVector<APValue, 4> Elts(NElts, Val);
  9041. return Success(Elts, E);
  9042. }
  9043. case CK_BitCast: {
  9044. // Evaluate the operand into an APInt we can extract from.
  9045. llvm::APInt SValInt;
  9046. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  9047. return false;
  9048. // Extract the elements
  9049. QualType EltTy = VTy->getElementType();
  9050. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  9051. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  9052. SmallVector<APValue, 4> Elts;
  9053. if (EltTy->isRealFloatingType()) {
  9054. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  9055. unsigned FloatEltSize = EltSize;
  9056. if (&Sem == &APFloat::x87DoubleExtended())
  9057. FloatEltSize = 80;
  9058. for (unsigned i = 0; i < NElts; i++) {
  9059. llvm::APInt Elt;
  9060. if (BigEndian)
  9061. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  9062. else
  9063. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  9064. Elts.push_back(APValue(APFloat(Sem, Elt)));
  9065. }
  9066. } else if (EltTy->isIntegerType()) {
  9067. for (unsigned i = 0; i < NElts; i++) {
  9068. llvm::APInt Elt;
  9069. if (BigEndian)
  9070. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  9071. else
  9072. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  9073. Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
  9074. }
  9075. } else {
  9076. return Error(E);
  9077. }
  9078. return Success(Elts, E);
  9079. }
  9080. default:
  9081. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9082. }
  9083. }
  9084. bool
  9085. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9086. const VectorType *VT = E->getType()->castAs<VectorType>();
  9087. unsigned NumInits = E->getNumInits();
  9088. unsigned NumElements = VT->getNumElements();
  9089. QualType EltTy = VT->getElementType();
  9090. SmallVector<APValue, 4> Elements;
  9091. // The number of initializers can be less than the number of
  9092. // vector elements. For OpenCL, this can be due to nested vector
  9093. // initialization. For GCC compatibility, missing trailing elements
  9094. // should be initialized with zeroes.
  9095. unsigned CountInits = 0, CountElts = 0;
  9096. while (CountElts < NumElements) {
  9097. // Handle nested vector initialization.
  9098. if (CountInits < NumInits
  9099. && E->getInit(CountInits)->getType()->isVectorType()) {
  9100. APValue v;
  9101. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  9102. return Error(E);
  9103. unsigned vlen = v.getVectorLength();
  9104. for (unsigned j = 0; j < vlen; j++)
  9105. Elements.push_back(v.getVectorElt(j));
  9106. CountElts += vlen;
  9107. } else if (EltTy->isIntegerType()) {
  9108. llvm::APSInt sInt(32);
  9109. if (CountInits < NumInits) {
  9110. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  9111. return false;
  9112. } else // trailing integer zero.
  9113. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  9114. Elements.push_back(APValue(sInt));
  9115. CountElts++;
  9116. } else {
  9117. llvm::APFloat f(0.0);
  9118. if (CountInits < NumInits) {
  9119. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  9120. return false;
  9121. } else // trailing float zero.
  9122. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  9123. Elements.push_back(APValue(f));
  9124. CountElts++;
  9125. }
  9126. CountInits++;
  9127. }
  9128. return Success(Elements, E);
  9129. }
  9130. bool
  9131. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  9132. const auto *VT = E->getType()->castAs<VectorType>();
  9133. QualType EltTy = VT->getElementType();
  9134. APValue ZeroElement;
  9135. if (EltTy->isIntegerType())
  9136. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  9137. else
  9138. ZeroElement =
  9139. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  9140. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  9141. return Success(Elements, E);
  9142. }
  9143. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9144. VisitIgnoredValue(E->getSubExpr());
  9145. return ZeroInitialization(E);
  9146. }
  9147. bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9148. BinaryOperatorKind Op = E->getOpcode();
  9149. assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
  9150. "Operation not supported on vector types");
  9151. if (Op == BO_Comma)
  9152. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9153. Expr *LHS = E->getLHS();
  9154. Expr *RHS = E->getRHS();
  9155. assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
  9156. "Must both be vector types");
  9157. // Checking JUST the types are the same would be fine, except shifts don't
  9158. // need to have their types be the same (since you always shift by an int).
  9159. assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
  9160. E->getType()->castAs<VectorType>()->getNumElements() &&
  9161. RHS->getType()->castAs<VectorType>()->getNumElements() ==
  9162. E->getType()->castAs<VectorType>()->getNumElements() &&
  9163. "All operands must be the same size.");
  9164. APValue LHSValue;
  9165. APValue RHSValue;
  9166. bool LHSOK = Evaluate(LHSValue, Info, LHS);
  9167. if (!LHSOK && !Info.noteFailure())
  9168. return false;
  9169. if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
  9170. return false;
  9171. if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
  9172. return false;
  9173. return Success(LHSValue, E);
  9174. }
  9175. static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
  9176. QualType ResultTy,
  9177. UnaryOperatorKind Op,
  9178. APValue Elt) {
  9179. switch (Op) {
  9180. case UO_Plus:
  9181. // Nothing to do here.
  9182. return Elt;
  9183. case UO_Minus:
  9184. if (Elt.getKind() == APValue::Int) {
  9185. Elt.getInt().negate();
  9186. } else {
  9187. assert(Elt.getKind() == APValue::Float &&
  9188. "Vector can only be int or float type");
  9189. Elt.getFloat().changeSign();
  9190. }
  9191. return Elt;
  9192. case UO_Not:
  9193. // This is only valid for integral types anyway, so we don't have to handle
  9194. // float here.
  9195. assert(Elt.getKind() == APValue::Int &&
  9196. "Vector operator ~ can only be int");
  9197. Elt.getInt().flipAllBits();
  9198. return Elt;
  9199. case UO_LNot: {
  9200. if (Elt.getKind() == APValue::Int) {
  9201. Elt.getInt() = !Elt.getInt();
  9202. // operator ! on vectors returns -1 for 'truth', so negate it.
  9203. Elt.getInt().negate();
  9204. return Elt;
  9205. }
  9206. assert(Elt.getKind() == APValue::Float &&
  9207. "Vector can only be int or float type");
  9208. // Float types result in an int of the same size, but -1 for true, or 0 for
  9209. // false.
  9210. APSInt EltResult{Ctx.getIntWidth(ResultTy),
  9211. ResultTy->isUnsignedIntegerType()};
  9212. if (Elt.getFloat().isZero())
  9213. EltResult.setAllBits();
  9214. else
  9215. EltResult.clearAllBits();
  9216. return APValue{EltResult};
  9217. }
  9218. default:
  9219. // FIXME: Implement the rest of the unary operators.
  9220. return llvm::None;
  9221. }
  9222. }
  9223. bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9224. Expr *SubExpr = E->getSubExpr();
  9225. const auto *VD = SubExpr->getType()->castAs<VectorType>();
  9226. // This result element type differs in the case of negating a floating point
  9227. // vector, since the result type is the a vector of the equivilant sized
  9228. // integer.
  9229. const QualType ResultEltTy = VD->getElementType();
  9230. UnaryOperatorKind Op = E->getOpcode();
  9231. APValue SubExprValue;
  9232. if (!Evaluate(SubExprValue, Info, SubExpr))
  9233. return false;
  9234. // FIXME: This vector evaluator someday needs to be changed to be LValue
  9235. // aware/keep LValue information around, rather than dealing with just vector
  9236. // types directly. Until then, we cannot handle cases where the operand to
  9237. // these unary operators is an LValue. The only case I've been able to see
  9238. // cause this is operator++ assigning to a member expression (only valid in
  9239. // altivec compilations) in C mode, so this shouldn't limit us too much.
  9240. if (SubExprValue.isLValue())
  9241. return false;
  9242. assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
  9243. "Vector length doesn't match type?");
  9244. SmallVector<APValue, 4> ResultElements;
  9245. for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
  9246. llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
  9247. Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
  9248. if (!Elt)
  9249. return false;
  9250. ResultElements.push_back(*Elt);
  9251. }
  9252. return Success(APValue(ResultElements.data(), ResultElements.size()), E);
  9253. }
  9254. //===----------------------------------------------------------------------===//
  9255. // Array Evaluation
  9256. //===----------------------------------------------------------------------===//
  9257. namespace {
  9258. class ArrayExprEvaluator
  9259. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  9260. const LValue &This;
  9261. APValue &Result;
  9262. public:
  9263. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  9264. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9265. bool Success(const APValue &V, const Expr *E) {
  9266. assert(V.isArray() && "expected array");
  9267. Result = V;
  9268. return true;
  9269. }
  9270. bool ZeroInitialization(const Expr *E) {
  9271. const ConstantArrayType *CAT =
  9272. Info.Ctx.getAsConstantArrayType(E->getType());
  9273. if (!CAT) {
  9274. if (E->getType()->isIncompleteArrayType()) {
  9275. // We can be asked to zero-initialize a flexible array member; this
  9276. // is represented as an ImplicitValueInitExpr of incomplete array
  9277. // type. In this case, the array has zero elements.
  9278. Result = APValue(APValue::UninitArray(), 0, 0);
  9279. return true;
  9280. }
  9281. // FIXME: We could handle VLAs here.
  9282. return Error(E);
  9283. }
  9284. Result = APValue(APValue::UninitArray(), 0,
  9285. CAT->getSize().getZExtValue());
  9286. if (!Result.hasArrayFiller())
  9287. return true;
  9288. // Zero-initialize all elements.
  9289. LValue Subobject = This;
  9290. Subobject.addArray(Info, E, CAT);
  9291. ImplicitValueInitExpr VIE(CAT->getElementType());
  9292. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  9293. }
  9294. bool VisitCallExpr(const CallExpr *E) {
  9295. return handleCallExpr(E, Result, &This);
  9296. }
  9297. bool VisitInitListExpr(const InitListExpr *E,
  9298. QualType AllocType = QualType());
  9299. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  9300. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  9301. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  9302. const LValue &Subobject,
  9303. APValue *Value, QualType Type);
  9304. bool VisitStringLiteral(const StringLiteral *E,
  9305. QualType AllocType = QualType()) {
  9306. expandStringLiteral(Info, E, Result, AllocType);
  9307. return true;
  9308. }
  9309. };
  9310. } // end anonymous namespace
  9311. static bool EvaluateArray(const Expr *E, const LValue &This,
  9312. APValue &Result, EvalInfo &Info) {
  9313. assert(!E->isValueDependent());
  9314. assert(E->isPRValue() && E->getType()->isArrayType() &&
  9315. "not an array prvalue");
  9316. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  9317. }
  9318. static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
  9319. APValue &Result, const InitListExpr *ILE,
  9320. QualType AllocType) {
  9321. assert(!ILE->isValueDependent());
  9322. assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
  9323. "not an array prvalue");
  9324. return ArrayExprEvaluator(Info, This, Result)
  9325. .VisitInitListExpr(ILE, AllocType);
  9326. }
  9327. static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
  9328. APValue &Result,
  9329. const CXXConstructExpr *CCE,
  9330. QualType AllocType) {
  9331. assert(!CCE->isValueDependent());
  9332. assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
  9333. "not an array prvalue");
  9334. return ArrayExprEvaluator(Info, This, Result)
  9335. .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
  9336. }
  9337. // Return true iff the given array filler may depend on the element index.
  9338. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  9339. // For now, just allow non-class value-initialization and initialization
  9340. // lists comprised of them.
  9341. if (isa<ImplicitValueInitExpr>(FillerExpr))
  9342. return false;
  9343. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  9344. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  9345. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  9346. return true;
  9347. }
  9348. return false;
  9349. }
  9350. return true;
  9351. }
  9352. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
  9353. QualType AllocType) {
  9354. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
  9355. AllocType.isNull() ? E->getType() : AllocType);
  9356. if (!CAT)
  9357. return Error(E);
  9358. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  9359. // an appropriately-typed string literal enclosed in braces.
  9360. if (E->isStringLiteralInit()) {
  9361. auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
  9362. // FIXME: Support ObjCEncodeExpr here once we support it in
  9363. // ArrayExprEvaluator generally.
  9364. if (!SL)
  9365. return Error(E);
  9366. return VisitStringLiteral(SL, AllocType);
  9367. }
  9368. // Any other transparent list init will need proper handling of the
  9369. // AllocType; we can't just recurse to the inner initializer.
  9370. assert(!E->isTransparent() &&
  9371. "transparent array list initialization is not string literal init?");
  9372. bool Success = true;
  9373. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  9374. "zero-initialized array shouldn't have any initialized elts");
  9375. APValue Filler;
  9376. if (Result.isArray() && Result.hasArrayFiller())
  9377. Filler = Result.getArrayFiller();
  9378. unsigned NumEltsToInit = E->getNumInits();
  9379. unsigned NumElts = CAT->getSize().getZExtValue();
  9380. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  9381. // If the initializer might depend on the array index, run it for each
  9382. // array element.
  9383. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  9384. NumEltsToInit = NumElts;
  9385. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  9386. << NumEltsToInit << ".\n");
  9387. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  9388. // If the array was previously zero-initialized, preserve the
  9389. // zero-initialized values.
  9390. if (Filler.hasValue()) {
  9391. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  9392. Result.getArrayInitializedElt(I) = Filler;
  9393. if (Result.hasArrayFiller())
  9394. Result.getArrayFiller() = Filler;
  9395. }
  9396. LValue Subobject = This;
  9397. Subobject.addArray(Info, E, CAT);
  9398. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  9399. const Expr *Init =
  9400. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  9401. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  9402. Info, Subobject, Init) ||
  9403. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  9404. CAT->getElementType(), 1)) {
  9405. if (!Info.noteFailure())
  9406. return false;
  9407. Success = false;
  9408. }
  9409. }
  9410. if (!Result.hasArrayFiller())
  9411. return Success;
  9412. // If we get here, we have a trivial filler, which we can just evaluate
  9413. // once and splat over the rest of the array elements.
  9414. assert(FillerExpr && "no array filler for incomplete init list");
  9415. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  9416. FillerExpr) && Success;
  9417. }
  9418. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  9419. LValue CommonLV;
  9420. if (E->getCommonExpr() &&
  9421. !Evaluate(Info.CurrentCall->createTemporary(
  9422. E->getCommonExpr(),
  9423. getStorageType(Info.Ctx, E->getCommonExpr()),
  9424. ScopeKind::FullExpression, CommonLV),
  9425. Info, E->getCommonExpr()->getSourceExpr()))
  9426. return false;
  9427. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  9428. uint64_t Elements = CAT->getSize().getZExtValue();
  9429. Result = APValue(APValue::UninitArray(), Elements, Elements);
  9430. LValue Subobject = This;
  9431. Subobject.addArray(Info, E, CAT);
  9432. bool Success = true;
  9433. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  9434. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  9435. Info, Subobject, E->getSubExpr()) ||
  9436. !HandleLValueArrayAdjustment(Info, E, Subobject,
  9437. CAT->getElementType(), 1)) {
  9438. if (!Info.noteFailure())
  9439. return false;
  9440. Success = false;
  9441. }
  9442. }
  9443. return Success;
  9444. }
  9445. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  9446. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  9447. }
  9448. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  9449. const LValue &Subobject,
  9450. APValue *Value,
  9451. QualType Type) {
  9452. bool HadZeroInit = Value->hasValue();
  9453. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  9454. unsigned FinalSize = CAT->getSize().getZExtValue();
  9455. // Preserve the array filler if we had prior zero-initialization.
  9456. APValue Filler =
  9457. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  9458. : APValue();
  9459. *Value = APValue(APValue::UninitArray(), 0, FinalSize);
  9460. if (FinalSize == 0)
  9461. return true;
  9462. LValue ArrayElt = Subobject;
  9463. ArrayElt.addArray(Info, E, CAT);
  9464. // We do the whole initialization in two passes, first for just one element,
  9465. // then for the whole array. It's possible we may find out we can't do const
  9466. // init in the first pass, in which case we avoid allocating a potentially
  9467. // large array. We don't do more passes because expanding array requires
  9468. // copying the data, which is wasteful.
  9469. for (const unsigned N : {1u, FinalSize}) {
  9470. unsigned OldElts = Value->getArrayInitializedElts();
  9471. if (OldElts == N)
  9472. break;
  9473. // Expand the array to appropriate size.
  9474. APValue NewValue(APValue::UninitArray(), N, FinalSize);
  9475. for (unsigned I = 0; I < OldElts; ++I)
  9476. NewValue.getArrayInitializedElt(I).swap(
  9477. Value->getArrayInitializedElt(I));
  9478. Value->swap(NewValue);
  9479. if (HadZeroInit)
  9480. for (unsigned I = OldElts; I < N; ++I)
  9481. Value->getArrayInitializedElt(I) = Filler;
  9482. // Initialize the elements.
  9483. for (unsigned I = OldElts; I < N; ++I) {
  9484. if (!VisitCXXConstructExpr(E, ArrayElt,
  9485. &Value->getArrayInitializedElt(I),
  9486. CAT->getElementType()) ||
  9487. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  9488. CAT->getElementType(), 1))
  9489. return false;
  9490. // When checking for const initilization any diagnostic is considered
  9491. // an error.
  9492. if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
  9493. !Info.keepEvaluatingAfterFailure())
  9494. return false;
  9495. }
  9496. }
  9497. return true;
  9498. }
  9499. if (!Type->isRecordType())
  9500. return Error(E);
  9501. return RecordExprEvaluator(Info, Subobject, *Value)
  9502. .VisitCXXConstructExpr(E, Type);
  9503. }
  9504. //===----------------------------------------------------------------------===//
  9505. // Integer Evaluation
  9506. //
  9507. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  9508. // types and back in constant folding. Integer values are thus represented
  9509. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  9510. //===----------------------------------------------------------------------===//
  9511. namespace {
  9512. class IntExprEvaluator
  9513. : public ExprEvaluatorBase<IntExprEvaluator> {
  9514. APValue &Result;
  9515. public:
  9516. IntExprEvaluator(EvalInfo &info, APValue &result)
  9517. : ExprEvaluatorBaseTy(info), Result(result) {}
  9518. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  9519. assert(E->getType()->isIntegralOrEnumerationType() &&
  9520. "Invalid evaluation result.");
  9521. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  9522. "Invalid evaluation result.");
  9523. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  9524. "Invalid evaluation result.");
  9525. Result = APValue(SI);
  9526. return true;
  9527. }
  9528. bool Success(const llvm::APSInt &SI, const Expr *E) {
  9529. return Success(SI, E, Result);
  9530. }
  9531. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  9532. assert(E->getType()->isIntegralOrEnumerationType() &&
  9533. "Invalid evaluation result.");
  9534. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  9535. "Invalid evaluation result.");
  9536. Result = APValue(APSInt(I));
  9537. Result.getInt().setIsUnsigned(
  9538. E->getType()->isUnsignedIntegerOrEnumerationType());
  9539. return true;
  9540. }
  9541. bool Success(const llvm::APInt &I, const Expr *E) {
  9542. return Success(I, E, Result);
  9543. }
  9544. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  9545. assert(E->getType()->isIntegralOrEnumerationType() &&
  9546. "Invalid evaluation result.");
  9547. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  9548. return true;
  9549. }
  9550. bool Success(uint64_t Value, const Expr *E) {
  9551. return Success(Value, E, Result);
  9552. }
  9553. bool Success(CharUnits Size, const Expr *E) {
  9554. return Success(Size.getQuantity(), E);
  9555. }
  9556. bool Success(const APValue &V, const Expr *E) {
  9557. if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
  9558. Result = V;
  9559. return true;
  9560. }
  9561. return Success(V.getInt(), E);
  9562. }
  9563. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  9564. //===--------------------------------------------------------------------===//
  9565. // Visitor Methods
  9566. //===--------------------------------------------------------------------===//
  9567. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  9568. return Success(E->getValue(), E);
  9569. }
  9570. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  9571. return Success(E->getValue(), E);
  9572. }
  9573. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  9574. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  9575. if (CheckReferencedDecl(E, E->getDecl()))
  9576. return true;
  9577. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  9578. }
  9579. bool VisitMemberExpr(const MemberExpr *E) {
  9580. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  9581. VisitIgnoredBaseExpression(E->getBase());
  9582. return true;
  9583. }
  9584. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  9585. }
  9586. bool VisitCallExpr(const CallExpr *E);
  9587. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  9588. bool VisitBinaryOperator(const BinaryOperator *E);
  9589. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  9590. bool VisitUnaryOperator(const UnaryOperator *E);
  9591. bool VisitCastExpr(const CastExpr* E);
  9592. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  9593. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  9594. return Success(E->getValue(), E);
  9595. }
  9596. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  9597. return Success(E->getValue(), E);
  9598. }
  9599. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  9600. if (Info.ArrayInitIndex == uint64_t(-1)) {
  9601. // We were asked to evaluate this subexpression independent of the
  9602. // enclosing ArrayInitLoopExpr. We can't do that.
  9603. Info.FFDiag(E);
  9604. return false;
  9605. }
  9606. return Success(Info.ArrayInitIndex, E);
  9607. }
  9608. // Note, GNU defines __null as an integer, not a pointer.
  9609. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  9610. return ZeroInitialization(E);
  9611. }
  9612. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  9613. return Success(E->getValue(), E);
  9614. }
  9615. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  9616. return Success(E->getValue(), E);
  9617. }
  9618. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  9619. return Success(E->getValue(), E);
  9620. }
  9621. bool VisitUnaryReal(const UnaryOperator *E);
  9622. bool VisitUnaryImag(const UnaryOperator *E);
  9623. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  9624. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  9625. bool VisitSourceLocExpr(const SourceLocExpr *E);
  9626. bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
  9627. bool VisitRequiresExpr(const RequiresExpr *E);
  9628. // FIXME: Missing: array subscript of vector, member of vector
  9629. };
  9630. class FixedPointExprEvaluator
  9631. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  9632. APValue &Result;
  9633. public:
  9634. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  9635. : ExprEvaluatorBaseTy(info), Result(result) {}
  9636. bool Success(const llvm::APInt &I, const Expr *E) {
  9637. return Success(
  9638. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  9639. }
  9640. bool Success(uint64_t Value, const Expr *E) {
  9641. return Success(
  9642. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  9643. }
  9644. bool Success(const APValue &V, const Expr *E) {
  9645. return Success(V.getFixedPoint(), E);
  9646. }
  9647. bool Success(const APFixedPoint &V, const Expr *E) {
  9648. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  9649. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  9650. "Invalid evaluation result.");
  9651. Result = APValue(V);
  9652. return true;
  9653. }
  9654. //===--------------------------------------------------------------------===//
  9655. // Visitor Methods
  9656. //===--------------------------------------------------------------------===//
  9657. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  9658. return Success(E->getValue(), E);
  9659. }
  9660. bool VisitCastExpr(const CastExpr *E);
  9661. bool VisitUnaryOperator(const UnaryOperator *E);
  9662. bool VisitBinaryOperator(const BinaryOperator *E);
  9663. };
  9664. } // end anonymous namespace
  9665. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  9666. /// produce either the integer value or a pointer.
  9667. ///
  9668. /// GCC has a heinous extension which folds casts between pointer types and
  9669. /// pointer-sized integral types. We support this by allowing the evaluation of
  9670. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  9671. /// Some simple arithmetic on such values is supported (they are treated much
  9672. /// like char*).
  9673. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  9674. EvalInfo &Info) {
  9675. assert(!E->isValueDependent());
  9676. assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
  9677. return IntExprEvaluator(Info, Result).Visit(E);
  9678. }
  9679. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  9680. assert(!E->isValueDependent());
  9681. APValue Val;
  9682. if (!EvaluateIntegerOrLValue(E, Val, Info))
  9683. return false;
  9684. if (!Val.isInt()) {
  9685. // FIXME: It would be better to produce the diagnostic for casting
  9686. // a pointer to an integer.
  9687. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9688. return false;
  9689. }
  9690. Result = Val.getInt();
  9691. return true;
  9692. }
  9693. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  9694. APValue Evaluated = E->EvaluateInContext(
  9695. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  9696. return Success(Evaluated, E);
  9697. }
  9698. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  9699. EvalInfo &Info) {
  9700. assert(!E->isValueDependent());
  9701. if (E->getType()->isFixedPointType()) {
  9702. APValue Val;
  9703. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  9704. return false;
  9705. if (!Val.isFixedPoint())
  9706. return false;
  9707. Result = Val.getFixedPoint();
  9708. return true;
  9709. }
  9710. return false;
  9711. }
  9712. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  9713. EvalInfo &Info) {
  9714. assert(!E->isValueDependent());
  9715. if (E->getType()->isIntegerType()) {
  9716. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  9717. APSInt Val;
  9718. if (!EvaluateInteger(E, Val, Info))
  9719. return false;
  9720. Result = APFixedPoint(Val, FXSema);
  9721. return true;
  9722. } else if (E->getType()->isFixedPointType()) {
  9723. return EvaluateFixedPoint(E, Result, Info);
  9724. }
  9725. return false;
  9726. }
  9727. /// Check whether the given declaration can be directly converted to an integral
  9728. /// rvalue. If not, no diagnostic is produced; there are other things we can
  9729. /// try.
  9730. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  9731. // Enums are integer constant exprs.
  9732. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  9733. // Check for signedness/width mismatches between E type and ECD value.
  9734. bool SameSign = (ECD->getInitVal().isSigned()
  9735. == E->getType()->isSignedIntegerOrEnumerationType());
  9736. bool SameWidth = (ECD->getInitVal().getBitWidth()
  9737. == Info.Ctx.getIntWidth(E->getType()));
  9738. if (SameSign && SameWidth)
  9739. return Success(ECD->getInitVal(), E);
  9740. else {
  9741. // Get rid of mismatch (otherwise Success assertions will fail)
  9742. // by computing a new value matching the type of E.
  9743. llvm::APSInt Val = ECD->getInitVal();
  9744. if (!SameSign)
  9745. Val.setIsSigned(!ECD->getInitVal().isSigned());
  9746. if (!SameWidth)
  9747. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  9748. return Success(Val, E);
  9749. }
  9750. }
  9751. return false;
  9752. }
  9753. /// Values returned by __builtin_classify_type, chosen to match the values
  9754. /// produced by GCC's builtin.
  9755. enum class GCCTypeClass {
  9756. None = -1,
  9757. Void = 0,
  9758. Integer = 1,
  9759. // GCC reserves 2 for character types, but instead classifies them as
  9760. // integers.
  9761. Enum = 3,
  9762. Bool = 4,
  9763. Pointer = 5,
  9764. // GCC reserves 6 for references, but appears to never use it (because
  9765. // expressions never have reference type, presumably).
  9766. PointerToDataMember = 7,
  9767. RealFloat = 8,
  9768. Complex = 9,
  9769. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  9770. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  9771. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  9772. // uses 12 for that purpose, same as for a class or struct. Maybe it
  9773. // internally implements a pointer to member as a struct? Who knows.
  9774. PointerToMemberFunction = 12, // Not a bug, see above.
  9775. ClassOrStruct = 12,
  9776. Union = 13,
  9777. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  9778. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  9779. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  9780. // literals.
  9781. };
  9782. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  9783. /// as GCC.
  9784. static GCCTypeClass
  9785. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  9786. assert(!T->isDependentType() && "unexpected dependent type");
  9787. QualType CanTy = T.getCanonicalType();
  9788. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  9789. switch (CanTy->getTypeClass()) {
  9790. #define TYPE(ID, BASE)
  9791. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  9792. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  9793. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  9794. #include "clang/AST/TypeNodes.inc"
  9795. case Type::Auto:
  9796. case Type::DeducedTemplateSpecialization:
  9797. llvm_unreachable("unexpected non-canonical or dependent type");
  9798. case Type::Builtin:
  9799. switch (BT->getKind()) {
  9800. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  9801. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  9802. case BuiltinType::ID: return GCCTypeClass::Integer;
  9803. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  9804. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  9805. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  9806. case BuiltinType::ID: break;
  9807. #include "clang/AST/BuiltinTypes.def"
  9808. case BuiltinType::Void:
  9809. return GCCTypeClass::Void;
  9810. case BuiltinType::Bool:
  9811. return GCCTypeClass::Bool;
  9812. case BuiltinType::Char_U:
  9813. case BuiltinType::UChar:
  9814. case BuiltinType::WChar_U:
  9815. case BuiltinType::Char8:
  9816. case BuiltinType::Char16:
  9817. case BuiltinType::Char32:
  9818. case BuiltinType::UShort:
  9819. case BuiltinType::UInt:
  9820. case BuiltinType::ULong:
  9821. case BuiltinType::ULongLong:
  9822. case BuiltinType::UInt128:
  9823. return GCCTypeClass::Integer;
  9824. case BuiltinType::UShortAccum:
  9825. case BuiltinType::UAccum:
  9826. case BuiltinType::ULongAccum:
  9827. case BuiltinType::UShortFract:
  9828. case BuiltinType::UFract:
  9829. case BuiltinType::ULongFract:
  9830. case BuiltinType::SatUShortAccum:
  9831. case BuiltinType::SatUAccum:
  9832. case BuiltinType::SatULongAccum:
  9833. case BuiltinType::SatUShortFract:
  9834. case BuiltinType::SatUFract:
  9835. case BuiltinType::SatULongFract:
  9836. return GCCTypeClass::None;
  9837. case BuiltinType::NullPtr:
  9838. case BuiltinType::ObjCId:
  9839. case BuiltinType::ObjCClass:
  9840. case BuiltinType::ObjCSel:
  9841. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  9842. case BuiltinType::Id:
  9843. #include "clang/Basic/OpenCLImageTypes.def"
  9844. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  9845. case BuiltinType::Id:
  9846. #include "clang/Basic/OpenCLExtensionTypes.def"
  9847. case BuiltinType::OCLSampler:
  9848. case BuiltinType::OCLEvent:
  9849. case BuiltinType::OCLClkEvent:
  9850. case BuiltinType::OCLQueue:
  9851. case BuiltinType::OCLReserveID:
  9852. #define SVE_TYPE(Name, Id, SingletonId) \
  9853. case BuiltinType::Id:
  9854. #include "clang/Basic/AArch64SVEACLETypes.def"
  9855. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  9856. case BuiltinType::Id:
  9857. #include "clang/Basic/PPCTypes.def"
  9858. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  9859. #include "clang/Basic/RISCVVTypes.def"
  9860. return GCCTypeClass::None;
  9861. case BuiltinType::Dependent:
  9862. llvm_unreachable("unexpected dependent type");
  9863. };
  9864. llvm_unreachable("unexpected placeholder type");
  9865. case Type::Enum:
  9866. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  9867. case Type::Pointer:
  9868. case Type::ConstantArray:
  9869. case Type::VariableArray:
  9870. case Type::IncompleteArray:
  9871. case Type::FunctionNoProto:
  9872. case Type::FunctionProto:
  9873. return GCCTypeClass::Pointer;
  9874. case Type::MemberPointer:
  9875. return CanTy->isMemberDataPointerType()
  9876. ? GCCTypeClass::PointerToDataMember
  9877. : GCCTypeClass::PointerToMemberFunction;
  9878. case Type::Complex:
  9879. return GCCTypeClass::Complex;
  9880. case Type::Record:
  9881. return CanTy->isUnionType() ? GCCTypeClass::Union
  9882. : GCCTypeClass::ClassOrStruct;
  9883. case Type::Atomic:
  9884. // GCC classifies _Atomic T the same as T.
  9885. return EvaluateBuiltinClassifyType(
  9886. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  9887. case Type::BlockPointer:
  9888. case Type::Vector:
  9889. case Type::ExtVector:
  9890. case Type::ConstantMatrix:
  9891. case Type::ObjCObject:
  9892. case Type::ObjCInterface:
  9893. case Type::ObjCObjectPointer:
  9894. case Type::Pipe:
  9895. case Type::BitInt:
  9896. // GCC classifies vectors as None. We follow its lead and classify all
  9897. // other types that don't fit into the regular classification the same way.
  9898. return GCCTypeClass::None;
  9899. case Type::LValueReference:
  9900. case Type::RValueReference:
  9901. llvm_unreachable("invalid type for expression");
  9902. }
  9903. llvm_unreachable("unexpected type class");
  9904. }
  9905. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  9906. /// as GCC.
  9907. static GCCTypeClass
  9908. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  9909. // If no argument was supplied, default to None. This isn't
  9910. // ideal, however it is what gcc does.
  9911. if (E->getNumArgs() == 0)
  9912. return GCCTypeClass::None;
  9913. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  9914. // being an ICE, but still folds it to a constant using the type of the first
  9915. // argument.
  9916. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  9917. }
  9918. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  9919. /// __builtin_constant_p when applied to the given pointer.
  9920. ///
  9921. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  9922. /// or it points to the first character of a string literal.
  9923. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  9924. APValue::LValueBase Base = LV.getLValueBase();
  9925. if (Base.isNull()) {
  9926. // A null base is acceptable.
  9927. return true;
  9928. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  9929. if (!isa<StringLiteral>(E))
  9930. return false;
  9931. return LV.getLValueOffset().isZero();
  9932. } else if (Base.is<TypeInfoLValue>()) {
  9933. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  9934. // evaluate to true.
  9935. return true;
  9936. } else {
  9937. // Any other base is not constant enough for GCC.
  9938. return false;
  9939. }
  9940. }
  9941. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  9942. /// GCC as we can manage.
  9943. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  9944. // This evaluation is not permitted to have side-effects, so evaluate it in
  9945. // a speculative evaluation context.
  9946. SpeculativeEvaluationRAII SpeculativeEval(Info);
  9947. // Constant-folding is always enabled for the operand of __builtin_constant_p
  9948. // (even when the enclosing evaluation context otherwise requires a strict
  9949. // language-specific constant expression).
  9950. FoldConstant Fold(Info, true);
  9951. QualType ArgType = Arg->getType();
  9952. // __builtin_constant_p always has one operand. The rules which gcc follows
  9953. // are not precisely documented, but are as follows:
  9954. //
  9955. // - If the operand is of integral, floating, complex or enumeration type,
  9956. // and can be folded to a known value of that type, it returns 1.
  9957. // - If the operand can be folded to a pointer to the first character
  9958. // of a string literal (or such a pointer cast to an integral type)
  9959. // or to a null pointer or an integer cast to a pointer, it returns 1.
  9960. //
  9961. // Otherwise, it returns 0.
  9962. //
  9963. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  9964. // its support for this did not work prior to GCC 9 and is not yet well
  9965. // understood.
  9966. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  9967. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  9968. ArgType->isNullPtrType()) {
  9969. APValue V;
  9970. if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
  9971. Fold.keepDiagnostics();
  9972. return false;
  9973. }
  9974. // For a pointer (possibly cast to integer), there are special rules.
  9975. if (V.getKind() == APValue::LValue)
  9976. return EvaluateBuiltinConstantPForLValue(V);
  9977. // Otherwise, any constant value is good enough.
  9978. return V.hasValue();
  9979. }
  9980. // Anything else isn't considered to be sufficiently constant.
  9981. return false;
  9982. }
  9983. /// Retrieves the "underlying object type" of the given expression,
  9984. /// as used by __builtin_object_size.
  9985. static QualType getObjectType(APValue::LValueBase B) {
  9986. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  9987. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  9988. return VD->getType();
  9989. } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
  9990. if (isa<CompoundLiteralExpr>(E))
  9991. return E->getType();
  9992. } else if (B.is<TypeInfoLValue>()) {
  9993. return B.getTypeInfoType();
  9994. } else if (B.is<DynamicAllocLValue>()) {
  9995. return B.getDynamicAllocType();
  9996. }
  9997. return QualType();
  9998. }
  9999. /// A more selective version of E->IgnoreParenCasts for
  10000. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  10001. /// to change the type of E.
  10002. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  10003. ///
  10004. /// Always returns an RValue with a pointer representation.
  10005. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  10006. assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
  10007. auto *NoParens = E->IgnoreParens();
  10008. auto *Cast = dyn_cast<CastExpr>(NoParens);
  10009. if (Cast == nullptr)
  10010. return NoParens;
  10011. // We only conservatively allow a few kinds of casts, because this code is
  10012. // inherently a simple solution that seeks to support the common case.
  10013. auto CastKind = Cast->getCastKind();
  10014. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  10015. CastKind != CK_AddressSpaceConversion)
  10016. return NoParens;
  10017. auto *SubExpr = Cast->getSubExpr();
  10018. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
  10019. return NoParens;
  10020. return ignorePointerCastsAndParens(SubExpr);
  10021. }
  10022. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  10023. /// record layout. e.g.
  10024. /// struct { struct { int a, b; } fst, snd; } obj;
  10025. /// obj.fst // no
  10026. /// obj.snd // yes
  10027. /// obj.fst.a // no
  10028. /// obj.fst.b // no
  10029. /// obj.snd.a // no
  10030. /// obj.snd.b // yes
  10031. ///
  10032. /// Please note: this function is specialized for how __builtin_object_size
  10033. /// views "objects".
  10034. ///
  10035. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  10036. /// correct result, it will always return true.
  10037. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  10038. assert(!LVal.Designator.Invalid);
  10039. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  10040. const RecordDecl *Parent = FD->getParent();
  10041. Invalid = Parent->isInvalidDecl();
  10042. if (Invalid || Parent->isUnion())
  10043. return true;
  10044. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  10045. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  10046. };
  10047. auto &Base = LVal.getLValueBase();
  10048. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  10049. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  10050. bool Invalid;
  10051. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  10052. return Invalid;
  10053. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  10054. for (auto *FD : IFD->chain()) {
  10055. bool Invalid;
  10056. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  10057. return Invalid;
  10058. }
  10059. }
  10060. }
  10061. unsigned I = 0;
  10062. QualType BaseType = getType(Base);
  10063. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  10064. // If we don't know the array bound, conservatively assume we're looking at
  10065. // the final array element.
  10066. ++I;
  10067. if (BaseType->isIncompleteArrayType())
  10068. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  10069. else
  10070. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  10071. }
  10072. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  10073. const auto &Entry = LVal.Designator.Entries[I];
  10074. if (BaseType->isArrayType()) {
  10075. // Because __builtin_object_size treats arrays as objects, we can ignore
  10076. // the index iff this is the last array in the Designator.
  10077. if (I + 1 == E)
  10078. return true;
  10079. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  10080. uint64_t Index = Entry.getAsArrayIndex();
  10081. if (Index + 1 != CAT->getSize())
  10082. return false;
  10083. BaseType = CAT->getElementType();
  10084. } else if (BaseType->isAnyComplexType()) {
  10085. const auto *CT = BaseType->castAs<ComplexType>();
  10086. uint64_t Index = Entry.getAsArrayIndex();
  10087. if (Index != 1)
  10088. return false;
  10089. BaseType = CT->getElementType();
  10090. } else if (auto *FD = getAsField(Entry)) {
  10091. bool Invalid;
  10092. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  10093. return Invalid;
  10094. BaseType = FD->getType();
  10095. } else {
  10096. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  10097. return false;
  10098. }
  10099. }
  10100. return true;
  10101. }
  10102. /// Tests to see if the LValue has a user-specified designator (that isn't
  10103. /// necessarily valid). Note that this always returns 'true' if the LValue has
  10104. /// an unsized array as its first designator entry, because there's currently no
  10105. /// way to tell if the user typed *foo or foo[0].
  10106. static bool refersToCompleteObject(const LValue &LVal) {
  10107. if (LVal.Designator.Invalid)
  10108. return false;
  10109. if (!LVal.Designator.Entries.empty())
  10110. return LVal.Designator.isMostDerivedAnUnsizedArray();
  10111. if (!LVal.InvalidBase)
  10112. return true;
  10113. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  10114. // the LValueBase.
  10115. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  10116. return !E || !isa<MemberExpr>(E);
  10117. }
  10118. /// Attempts to detect a user writing into a piece of memory that's impossible
  10119. /// to figure out the size of by just using types.
  10120. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  10121. const SubobjectDesignator &Designator = LVal.Designator;
  10122. // Notes:
  10123. // - Users can only write off of the end when we have an invalid base. Invalid
  10124. // bases imply we don't know where the memory came from.
  10125. // - We used to be a bit more aggressive here; we'd only be conservative if
  10126. // the array at the end was flexible, or if it had 0 or 1 elements. This
  10127. // broke some common standard library extensions (PR30346), but was
  10128. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  10129. // with some sort of list. OTOH, it seems that GCC is always
  10130. // conservative with the last element in structs (if it's an array), so our
  10131. // current behavior is more compatible than an explicit list approach would
  10132. // be.
  10133. return LVal.InvalidBase &&
  10134. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  10135. Designator.MostDerivedIsArrayElement &&
  10136. isDesignatorAtObjectEnd(Ctx, LVal);
  10137. }
  10138. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  10139. /// Fails if the conversion would cause loss of precision.
  10140. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  10141. CharUnits &Result) {
  10142. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  10143. if (Int.ugt(CharUnitsMax))
  10144. return false;
  10145. Result = CharUnits::fromQuantity(Int.getZExtValue());
  10146. return true;
  10147. }
  10148. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  10149. /// determine how many bytes exist from the beginning of the object to either
  10150. /// the end of the current subobject, or the end of the object itself, depending
  10151. /// on what the LValue looks like + the value of Type.
  10152. ///
  10153. /// If this returns false, the value of Result is undefined.
  10154. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  10155. unsigned Type, const LValue &LVal,
  10156. CharUnits &EndOffset) {
  10157. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  10158. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  10159. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  10160. return false;
  10161. return HandleSizeof(Info, ExprLoc, Ty, Result);
  10162. };
  10163. // We want to evaluate the size of the entire object. This is a valid fallback
  10164. // for when Type=1 and the designator is invalid, because we're asked for an
  10165. // upper-bound.
  10166. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  10167. // Type=3 wants a lower bound, so we can't fall back to this.
  10168. if (Type == 3 && !DetermineForCompleteObject)
  10169. return false;
  10170. llvm::APInt APEndOffset;
  10171. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  10172. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  10173. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  10174. if (LVal.InvalidBase)
  10175. return false;
  10176. QualType BaseTy = getObjectType(LVal.getLValueBase());
  10177. return CheckedHandleSizeof(BaseTy, EndOffset);
  10178. }
  10179. // We want to evaluate the size of a subobject.
  10180. const SubobjectDesignator &Designator = LVal.Designator;
  10181. // The following is a moderately common idiom in C:
  10182. //
  10183. // struct Foo { int a; char c[1]; };
  10184. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  10185. // strcpy(&F->c[0], Bar);
  10186. //
  10187. // In order to not break too much legacy code, we need to support it.
  10188. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  10189. // If we can resolve this to an alloc_size call, we can hand that back,
  10190. // because we know for certain how many bytes there are to write to.
  10191. llvm::APInt APEndOffset;
  10192. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  10193. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  10194. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  10195. // If we cannot determine the size of the initial allocation, then we can't
  10196. // given an accurate upper-bound. However, we are still able to give
  10197. // conservative lower-bounds for Type=3.
  10198. if (Type == 1)
  10199. return false;
  10200. }
  10201. CharUnits BytesPerElem;
  10202. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  10203. return false;
  10204. // According to the GCC documentation, we want the size of the subobject
  10205. // denoted by the pointer. But that's not quite right -- what we actually
  10206. // want is the size of the immediately-enclosing array, if there is one.
  10207. int64_t ElemsRemaining;
  10208. if (Designator.MostDerivedIsArrayElement &&
  10209. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  10210. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  10211. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  10212. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  10213. } else {
  10214. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  10215. }
  10216. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  10217. return true;
  10218. }
  10219. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  10220. /// returns true and stores the result in @p Size.
  10221. ///
  10222. /// If @p WasError is non-null, this will report whether the failure to evaluate
  10223. /// is to be treated as an Error in IntExprEvaluator.
  10224. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  10225. EvalInfo &Info, uint64_t &Size) {
  10226. // Determine the denoted object.
  10227. LValue LVal;
  10228. {
  10229. // The operand of __builtin_object_size is never evaluated for side-effects.
  10230. // If there are any, but we can determine the pointed-to object anyway, then
  10231. // ignore the side-effects.
  10232. SpeculativeEvaluationRAII SpeculativeEval(Info);
  10233. IgnoreSideEffectsRAII Fold(Info);
  10234. if (E->isGLValue()) {
  10235. // It's possible for us to be given GLValues if we're called via
  10236. // Expr::tryEvaluateObjectSize.
  10237. APValue RVal;
  10238. if (!EvaluateAsRValue(Info, E, RVal))
  10239. return false;
  10240. LVal.setFrom(Info.Ctx, RVal);
  10241. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  10242. /*InvalidBaseOK=*/true))
  10243. return false;
  10244. }
  10245. // If we point to before the start of the object, there are no accessible
  10246. // bytes.
  10247. if (LVal.getLValueOffset().isNegative()) {
  10248. Size = 0;
  10249. return true;
  10250. }
  10251. CharUnits EndOffset;
  10252. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  10253. return false;
  10254. // If we've fallen outside of the end offset, just pretend there's nothing to
  10255. // write to/read from.
  10256. if (EndOffset <= LVal.getLValueOffset())
  10257. Size = 0;
  10258. else
  10259. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  10260. return true;
  10261. }
  10262. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  10263. if (unsigned BuiltinOp = E->getBuiltinCallee())
  10264. return VisitBuiltinCallExpr(E, BuiltinOp);
  10265. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10266. }
  10267. static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
  10268. APValue &Val, APSInt &Alignment) {
  10269. QualType SrcTy = E->getArg(0)->getType();
  10270. if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
  10271. return false;
  10272. // Even though we are evaluating integer expressions we could get a pointer
  10273. // argument for the __builtin_is_aligned() case.
  10274. if (SrcTy->isPointerType()) {
  10275. LValue Ptr;
  10276. if (!EvaluatePointer(E->getArg(0), Ptr, Info))
  10277. return false;
  10278. Ptr.moveInto(Val);
  10279. } else if (!SrcTy->isIntegralOrEnumerationType()) {
  10280. Info.FFDiag(E->getArg(0));
  10281. return false;
  10282. } else {
  10283. APSInt SrcInt;
  10284. if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
  10285. return false;
  10286. assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
  10287. "Bit widths must be the same");
  10288. Val = APValue(SrcInt);
  10289. }
  10290. assert(Val.hasValue());
  10291. return true;
  10292. }
  10293. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  10294. unsigned BuiltinOp) {
  10295. switch (BuiltinOp) {
  10296. default:
  10297. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10298. case Builtin::BI__builtin_dynamic_object_size:
  10299. case Builtin::BI__builtin_object_size: {
  10300. // The type was checked when we built the expression.
  10301. unsigned Type =
  10302. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  10303. assert(Type <= 3 && "unexpected type");
  10304. uint64_t Size;
  10305. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  10306. return Success(Size, E);
  10307. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  10308. return Success((Type & 2) ? 0 : -1, E);
  10309. // Expression had no side effects, but we couldn't statically determine the
  10310. // size of the referenced object.
  10311. switch (Info.EvalMode) {
  10312. case EvalInfo::EM_ConstantExpression:
  10313. case EvalInfo::EM_ConstantFold:
  10314. case EvalInfo::EM_IgnoreSideEffects:
  10315. // Leave it to IR generation.
  10316. return Error(E);
  10317. case EvalInfo::EM_ConstantExpressionUnevaluated:
  10318. // Reduce it to a constant now.
  10319. return Success((Type & 2) ? 0 : -1, E);
  10320. }
  10321. llvm_unreachable("unexpected EvalMode");
  10322. }
  10323. case Builtin::BI__builtin_os_log_format_buffer_size: {
  10324. analyze_os_log::OSLogBufferLayout Layout;
  10325. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  10326. return Success(Layout.size().getQuantity(), E);
  10327. }
  10328. case Builtin::BI__builtin_is_aligned: {
  10329. APValue Src;
  10330. APSInt Alignment;
  10331. if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
  10332. return false;
  10333. if (Src.isLValue()) {
  10334. // If we evaluated a pointer, check the minimum known alignment.
  10335. LValue Ptr;
  10336. Ptr.setFrom(Info.Ctx, Src);
  10337. CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
  10338. CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
  10339. // We can return true if the known alignment at the computed offset is
  10340. // greater than the requested alignment.
  10341. assert(PtrAlign.isPowerOfTwo());
  10342. assert(Alignment.isPowerOf2());
  10343. if (PtrAlign.getQuantity() >= Alignment)
  10344. return Success(1, E);
  10345. // If the alignment is not known to be sufficient, some cases could still
  10346. // be aligned at run time. However, if the requested alignment is less or
  10347. // equal to the base alignment and the offset is not aligned, we know that
  10348. // the run-time value can never be aligned.
  10349. if (BaseAlignment.getQuantity() >= Alignment &&
  10350. PtrAlign.getQuantity() < Alignment)
  10351. return Success(0, E);
  10352. // Otherwise we can't infer whether the value is sufficiently aligned.
  10353. // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
  10354. // in cases where we can't fully evaluate the pointer.
  10355. Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
  10356. << Alignment;
  10357. return false;
  10358. }
  10359. assert(Src.isInt());
  10360. return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
  10361. }
  10362. case Builtin::BI__builtin_align_up: {
  10363. APValue Src;
  10364. APSInt Alignment;
  10365. if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
  10366. return false;
  10367. if (!Src.isInt())
  10368. return Error(E);
  10369. APSInt AlignedVal =
  10370. APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
  10371. Src.getInt().isUnsigned());
  10372. assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
  10373. return Success(AlignedVal, E);
  10374. }
  10375. case Builtin::BI__builtin_align_down: {
  10376. APValue Src;
  10377. APSInt Alignment;
  10378. if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
  10379. return false;
  10380. if (!Src.isInt())
  10381. return Error(E);
  10382. APSInt AlignedVal =
  10383. APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
  10384. assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
  10385. return Success(AlignedVal, E);
  10386. }
  10387. case Builtin::BI__builtin_bitreverse8:
  10388. case Builtin::BI__builtin_bitreverse16:
  10389. case Builtin::BI__builtin_bitreverse32:
  10390. case Builtin::BI__builtin_bitreverse64: {
  10391. APSInt Val;
  10392. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10393. return false;
  10394. return Success(Val.reverseBits(), E);
  10395. }
  10396. case Builtin::BI__builtin_bswap16:
  10397. case Builtin::BI__builtin_bswap32:
  10398. case Builtin::BI__builtin_bswap64: {
  10399. APSInt Val;
  10400. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10401. return false;
  10402. return Success(Val.byteSwap(), E);
  10403. }
  10404. case Builtin::BI__builtin_classify_type:
  10405. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  10406. case Builtin::BI__builtin_clrsb:
  10407. case Builtin::BI__builtin_clrsbl:
  10408. case Builtin::BI__builtin_clrsbll: {
  10409. APSInt Val;
  10410. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10411. return false;
  10412. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  10413. }
  10414. case Builtin::BI__builtin_clz:
  10415. case Builtin::BI__builtin_clzl:
  10416. case Builtin::BI__builtin_clzll:
  10417. case Builtin::BI__builtin_clzs: {
  10418. APSInt Val;
  10419. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10420. return false;
  10421. if (!Val)
  10422. return Error(E);
  10423. return Success(Val.countLeadingZeros(), E);
  10424. }
  10425. case Builtin::BI__builtin_constant_p: {
  10426. const Expr *Arg = E->getArg(0);
  10427. if (EvaluateBuiltinConstantP(Info, Arg))
  10428. return Success(true, E);
  10429. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  10430. // Outside a constant context, eagerly evaluate to false in the presence
  10431. // of side-effects in order to avoid -Wunsequenced false-positives in
  10432. // a branch on __builtin_constant_p(expr).
  10433. return Success(false, E);
  10434. }
  10435. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10436. return false;
  10437. }
  10438. case Builtin::BI__builtin_is_constant_evaluated: {
  10439. const auto *Callee = Info.CurrentCall->getCallee();
  10440. if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
  10441. (Info.CallStackDepth == 1 ||
  10442. (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
  10443. Callee->getIdentifier() &&
  10444. Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
  10445. // FIXME: Find a better way to avoid duplicated diagnostics.
  10446. if (Info.EvalStatus.Diag)
  10447. Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
  10448. : Info.CurrentCall->CallLoc,
  10449. diag::warn_is_constant_evaluated_always_true_constexpr)
  10450. << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
  10451. : "std::is_constant_evaluated");
  10452. }
  10453. return Success(Info.InConstantContext, E);
  10454. }
  10455. case Builtin::BI__builtin_ctz:
  10456. case Builtin::BI__builtin_ctzl:
  10457. case Builtin::BI__builtin_ctzll:
  10458. case Builtin::BI__builtin_ctzs: {
  10459. APSInt Val;
  10460. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10461. return false;
  10462. if (!Val)
  10463. return Error(E);
  10464. return Success(Val.countTrailingZeros(), E);
  10465. }
  10466. case Builtin::BI__builtin_eh_return_data_regno: {
  10467. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  10468. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  10469. return Success(Operand, E);
  10470. }
  10471. case Builtin::BI__builtin_expect:
  10472. case Builtin::BI__builtin_expect_with_probability:
  10473. return Visit(E->getArg(0));
  10474. case Builtin::BI__builtin_ffs:
  10475. case Builtin::BI__builtin_ffsl:
  10476. case Builtin::BI__builtin_ffsll: {
  10477. APSInt Val;
  10478. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10479. return false;
  10480. unsigned N = Val.countTrailingZeros();
  10481. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  10482. }
  10483. case Builtin::BI__builtin_fpclassify: {
  10484. APFloat Val(0.0);
  10485. if (!EvaluateFloat(E->getArg(5), Val, Info))
  10486. return false;
  10487. unsigned Arg;
  10488. switch (Val.getCategory()) {
  10489. case APFloat::fcNaN: Arg = 0; break;
  10490. case APFloat::fcInfinity: Arg = 1; break;
  10491. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  10492. case APFloat::fcZero: Arg = 4; break;
  10493. }
  10494. return Visit(E->getArg(Arg));
  10495. }
  10496. case Builtin::BI__builtin_isinf_sign: {
  10497. APFloat Val(0.0);
  10498. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10499. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  10500. }
  10501. case Builtin::BI__builtin_isinf: {
  10502. APFloat Val(0.0);
  10503. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10504. Success(Val.isInfinity() ? 1 : 0, E);
  10505. }
  10506. case Builtin::BI__builtin_isfinite: {
  10507. APFloat Val(0.0);
  10508. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10509. Success(Val.isFinite() ? 1 : 0, E);
  10510. }
  10511. case Builtin::BI__builtin_isnan: {
  10512. APFloat Val(0.0);
  10513. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10514. Success(Val.isNaN() ? 1 : 0, E);
  10515. }
  10516. case Builtin::BI__builtin_isnormal: {
  10517. APFloat Val(0.0);
  10518. return EvaluateFloat(E->getArg(0), Val, Info) &&
  10519. Success(Val.isNormal() ? 1 : 0, E);
  10520. }
  10521. case Builtin::BI__builtin_parity:
  10522. case Builtin::BI__builtin_parityl:
  10523. case Builtin::BI__builtin_parityll: {
  10524. APSInt Val;
  10525. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10526. return false;
  10527. return Success(Val.countPopulation() % 2, E);
  10528. }
  10529. case Builtin::BI__builtin_popcount:
  10530. case Builtin::BI__builtin_popcountl:
  10531. case Builtin::BI__builtin_popcountll: {
  10532. APSInt Val;
  10533. if (!EvaluateInteger(E->getArg(0), Val, Info))
  10534. return false;
  10535. return Success(Val.countPopulation(), E);
  10536. }
  10537. case Builtin::BI__builtin_rotateleft8:
  10538. case Builtin::BI__builtin_rotateleft16:
  10539. case Builtin::BI__builtin_rotateleft32:
  10540. case Builtin::BI__builtin_rotateleft64:
  10541. case Builtin::BI_rotl8: // Microsoft variants of rotate right
  10542. case Builtin::BI_rotl16:
  10543. case Builtin::BI_rotl:
  10544. case Builtin::BI_lrotl:
  10545. case Builtin::BI_rotl64: {
  10546. APSInt Val, Amt;
  10547. if (!EvaluateInteger(E->getArg(0), Val, Info) ||
  10548. !EvaluateInteger(E->getArg(1), Amt, Info))
  10549. return false;
  10550. return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
  10551. }
  10552. case Builtin::BI__builtin_rotateright8:
  10553. case Builtin::BI__builtin_rotateright16:
  10554. case Builtin::BI__builtin_rotateright32:
  10555. case Builtin::BI__builtin_rotateright64:
  10556. case Builtin::BI_rotr8: // Microsoft variants of rotate right
  10557. case Builtin::BI_rotr16:
  10558. case Builtin::BI_rotr:
  10559. case Builtin::BI_lrotr:
  10560. case Builtin::BI_rotr64: {
  10561. APSInt Val, Amt;
  10562. if (!EvaluateInteger(E->getArg(0), Val, Info) ||
  10563. !EvaluateInteger(E->getArg(1), Amt, Info))
  10564. return false;
  10565. return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
  10566. }
  10567. case Builtin::BIstrlen:
  10568. case Builtin::BIwcslen:
  10569. // A call to strlen is not a constant expression.
  10570. if (Info.getLangOpts().CPlusPlus11)
  10571. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  10572. << /*isConstexpr*/0 << /*isConstructor*/0
  10573. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  10574. else
  10575. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10576. LLVM_FALLTHROUGH;
  10577. case Builtin::BI__builtin_strlen:
  10578. case Builtin::BI__builtin_wcslen: {
  10579. // As an extension, we support __builtin_strlen() as a constant expression,
  10580. // and support folding strlen() to a constant.
  10581. uint64_t StrLen;
  10582. if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
  10583. return Success(StrLen, E);
  10584. return false;
  10585. }
  10586. case Builtin::BIstrcmp:
  10587. case Builtin::BIwcscmp:
  10588. case Builtin::BIstrncmp:
  10589. case Builtin::BIwcsncmp:
  10590. case Builtin::BImemcmp:
  10591. case Builtin::BIbcmp:
  10592. case Builtin::BIwmemcmp:
  10593. // A call to strlen is not a constant expression.
  10594. if (Info.getLangOpts().CPlusPlus11)
  10595. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  10596. << /*isConstexpr*/0 << /*isConstructor*/0
  10597. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  10598. else
  10599. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10600. LLVM_FALLTHROUGH;
  10601. case Builtin::BI__builtin_strcmp:
  10602. case Builtin::BI__builtin_wcscmp:
  10603. case Builtin::BI__builtin_strncmp:
  10604. case Builtin::BI__builtin_wcsncmp:
  10605. case Builtin::BI__builtin_memcmp:
  10606. case Builtin::BI__builtin_bcmp:
  10607. case Builtin::BI__builtin_wmemcmp: {
  10608. LValue String1, String2;
  10609. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  10610. !EvaluatePointer(E->getArg(1), String2, Info))
  10611. return false;
  10612. uint64_t MaxLength = uint64_t(-1);
  10613. if (BuiltinOp != Builtin::BIstrcmp &&
  10614. BuiltinOp != Builtin::BIwcscmp &&
  10615. BuiltinOp != Builtin::BI__builtin_strcmp &&
  10616. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  10617. APSInt N;
  10618. if (!EvaluateInteger(E->getArg(2), N, Info))
  10619. return false;
  10620. MaxLength = N.getExtValue();
  10621. }
  10622. // Empty substrings compare equal by definition.
  10623. if (MaxLength == 0u)
  10624. return Success(0, E);
  10625. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  10626. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  10627. String1.Designator.Invalid || String2.Designator.Invalid)
  10628. return false;
  10629. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  10630. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  10631. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  10632. BuiltinOp == Builtin::BIbcmp ||
  10633. BuiltinOp == Builtin::BI__builtin_memcmp ||
  10634. BuiltinOp == Builtin::BI__builtin_bcmp;
  10635. assert(IsRawByte ||
  10636. (Info.Ctx.hasSameUnqualifiedType(
  10637. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  10638. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  10639. // For memcmp, allow comparing any arrays of '[[un]signed] char' or
  10640. // 'char8_t', but no other types.
  10641. if (IsRawByte &&
  10642. !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
  10643. // FIXME: Consider using our bit_cast implementation to support this.
  10644. Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
  10645. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
  10646. << CharTy1 << CharTy2;
  10647. return false;
  10648. }
  10649. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  10650. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  10651. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  10652. Char1.isInt() && Char2.isInt();
  10653. };
  10654. const auto &AdvanceElems = [&] {
  10655. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  10656. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  10657. };
  10658. bool StopAtNull =
  10659. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  10660. BuiltinOp != Builtin::BIwmemcmp &&
  10661. BuiltinOp != Builtin::BI__builtin_memcmp &&
  10662. BuiltinOp != Builtin::BI__builtin_bcmp &&
  10663. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  10664. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  10665. BuiltinOp == Builtin::BIwcsncmp ||
  10666. BuiltinOp == Builtin::BIwmemcmp ||
  10667. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  10668. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  10669. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  10670. for (; MaxLength; --MaxLength) {
  10671. APValue Char1, Char2;
  10672. if (!ReadCurElems(Char1, Char2))
  10673. return false;
  10674. if (Char1.getInt().ne(Char2.getInt())) {
  10675. if (IsWide) // wmemcmp compares with wchar_t signedness.
  10676. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  10677. // memcmp always compares unsigned chars.
  10678. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  10679. }
  10680. if (StopAtNull && !Char1.getInt())
  10681. return Success(0, E);
  10682. assert(!(StopAtNull && !Char2.getInt()));
  10683. if (!AdvanceElems())
  10684. return false;
  10685. }
  10686. // We hit the strncmp / memcmp limit.
  10687. return Success(0, E);
  10688. }
  10689. case Builtin::BI__atomic_always_lock_free:
  10690. case Builtin::BI__atomic_is_lock_free:
  10691. case Builtin::BI__c11_atomic_is_lock_free: {
  10692. APSInt SizeVal;
  10693. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  10694. return false;
  10695. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  10696. // of two less than or equal to the maximum inline atomic width, we know it
  10697. // is lock-free. If the size isn't a power of two, or greater than the
  10698. // maximum alignment where we promote atomics, we know it is not lock-free
  10699. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  10700. // the answer can only be determined at runtime; for example, 16-byte
  10701. // atomics have lock-free implementations on some, but not all,
  10702. // x86-64 processors.
  10703. // Check power-of-two.
  10704. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  10705. if (Size.isPowerOfTwo()) {
  10706. // Check against inlining width.
  10707. unsigned InlineWidthBits =
  10708. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  10709. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  10710. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  10711. Size == CharUnits::One() ||
  10712. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  10713. Expr::NPC_NeverValueDependent))
  10714. // OK, we will inline appropriately-aligned operations of this size,
  10715. // and _Atomic(T) is appropriately-aligned.
  10716. return Success(1, E);
  10717. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  10718. castAs<PointerType>()->getPointeeType();
  10719. if (!PointeeType->isIncompleteType() &&
  10720. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  10721. // OK, we will inline operations on this object.
  10722. return Success(1, E);
  10723. }
  10724. }
  10725. }
  10726. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  10727. Success(0, E) : Error(E);
  10728. }
  10729. case Builtin::BI__builtin_add_overflow:
  10730. case Builtin::BI__builtin_sub_overflow:
  10731. case Builtin::BI__builtin_mul_overflow:
  10732. case Builtin::BI__builtin_sadd_overflow:
  10733. case Builtin::BI__builtin_uadd_overflow:
  10734. case Builtin::BI__builtin_uaddl_overflow:
  10735. case Builtin::BI__builtin_uaddll_overflow:
  10736. case Builtin::BI__builtin_usub_overflow:
  10737. case Builtin::BI__builtin_usubl_overflow:
  10738. case Builtin::BI__builtin_usubll_overflow:
  10739. case Builtin::BI__builtin_umul_overflow:
  10740. case Builtin::BI__builtin_umull_overflow:
  10741. case Builtin::BI__builtin_umulll_overflow:
  10742. case Builtin::BI__builtin_saddl_overflow:
  10743. case Builtin::BI__builtin_saddll_overflow:
  10744. case Builtin::BI__builtin_ssub_overflow:
  10745. case Builtin::BI__builtin_ssubl_overflow:
  10746. case Builtin::BI__builtin_ssubll_overflow:
  10747. case Builtin::BI__builtin_smul_overflow:
  10748. case Builtin::BI__builtin_smull_overflow:
  10749. case Builtin::BI__builtin_smulll_overflow: {
  10750. LValue ResultLValue;
  10751. APSInt LHS, RHS;
  10752. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  10753. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  10754. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  10755. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  10756. return false;
  10757. APSInt Result;
  10758. bool DidOverflow = false;
  10759. // If the types don't have to match, enlarge all 3 to the largest of them.
  10760. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  10761. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  10762. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  10763. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  10764. ResultType->isSignedIntegerOrEnumerationType();
  10765. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  10766. ResultType->isSignedIntegerOrEnumerationType();
  10767. uint64_t LHSSize = LHS.getBitWidth();
  10768. uint64_t RHSSize = RHS.getBitWidth();
  10769. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  10770. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  10771. // Add an additional bit if the signedness isn't uniformly agreed to. We
  10772. // could do this ONLY if there is a signed and an unsigned that both have
  10773. // MaxBits, but the code to check that is pretty nasty. The issue will be
  10774. // caught in the shrink-to-result later anyway.
  10775. if (IsSigned && !AllSigned)
  10776. ++MaxBits;
  10777. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  10778. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  10779. Result = APSInt(MaxBits, !IsSigned);
  10780. }
  10781. // Find largest int.
  10782. switch (BuiltinOp) {
  10783. default:
  10784. llvm_unreachable("Invalid value for BuiltinOp");
  10785. case Builtin::BI__builtin_add_overflow:
  10786. case Builtin::BI__builtin_sadd_overflow:
  10787. case Builtin::BI__builtin_saddl_overflow:
  10788. case Builtin::BI__builtin_saddll_overflow:
  10789. case Builtin::BI__builtin_uadd_overflow:
  10790. case Builtin::BI__builtin_uaddl_overflow:
  10791. case Builtin::BI__builtin_uaddll_overflow:
  10792. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  10793. : LHS.uadd_ov(RHS, DidOverflow);
  10794. break;
  10795. case Builtin::BI__builtin_sub_overflow:
  10796. case Builtin::BI__builtin_ssub_overflow:
  10797. case Builtin::BI__builtin_ssubl_overflow:
  10798. case Builtin::BI__builtin_ssubll_overflow:
  10799. case Builtin::BI__builtin_usub_overflow:
  10800. case Builtin::BI__builtin_usubl_overflow:
  10801. case Builtin::BI__builtin_usubll_overflow:
  10802. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  10803. : LHS.usub_ov(RHS, DidOverflow);
  10804. break;
  10805. case Builtin::BI__builtin_mul_overflow:
  10806. case Builtin::BI__builtin_smul_overflow:
  10807. case Builtin::BI__builtin_smull_overflow:
  10808. case Builtin::BI__builtin_smulll_overflow:
  10809. case Builtin::BI__builtin_umul_overflow:
  10810. case Builtin::BI__builtin_umull_overflow:
  10811. case Builtin::BI__builtin_umulll_overflow:
  10812. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  10813. : LHS.umul_ov(RHS, DidOverflow);
  10814. break;
  10815. }
  10816. // In the case where multiple sizes are allowed, truncate and see if
  10817. // the values are the same.
  10818. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  10819. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  10820. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  10821. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  10822. // since it will give us the behavior of a TruncOrSelf in the case where
  10823. // its parameter <= its size. We previously set Result to be at least the
  10824. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  10825. // will work exactly like TruncOrSelf.
  10826. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  10827. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  10828. if (!APSInt::isSameValue(Temp, Result))
  10829. DidOverflow = true;
  10830. Result = Temp;
  10831. }
  10832. APValue APV{Result};
  10833. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  10834. return false;
  10835. return Success(DidOverflow, E);
  10836. }
  10837. }
  10838. }
  10839. /// Determine whether this is a pointer past the end of the complete
  10840. /// object referred to by the lvalue.
  10841. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  10842. const LValue &LV) {
  10843. // A null pointer can be viewed as being "past the end" but we don't
  10844. // choose to look at it that way here.
  10845. if (!LV.getLValueBase())
  10846. return false;
  10847. // If the designator is valid and refers to a subobject, we're not pointing
  10848. // past the end.
  10849. if (!LV.getLValueDesignator().Invalid &&
  10850. !LV.getLValueDesignator().isOnePastTheEnd())
  10851. return false;
  10852. // A pointer to an incomplete type might be past-the-end if the type's size is
  10853. // zero. We cannot tell because the type is incomplete.
  10854. QualType Ty = getType(LV.getLValueBase());
  10855. if (Ty->isIncompleteType())
  10856. return true;
  10857. // We're a past-the-end pointer if we point to the byte after the object,
  10858. // no matter what our type or path is.
  10859. auto Size = Ctx.getTypeSizeInChars(Ty);
  10860. return LV.getLValueOffset() == Size;
  10861. }
  10862. namespace {
  10863. /// Data recursive integer evaluator of certain binary operators.
  10864. ///
  10865. /// We use a data recursive algorithm for binary operators so that we are able
  10866. /// to handle extreme cases of chained binary operators without causing stack
  10867. /// overflow.
  10868. class DataRecursiveIntBinOpEvaluator {
  10869. struct EvalResult {
  10870. APValue Val;
  10871. bool Failed;
  10872. EvalResult() : Failed(false) { }
  10873. void swap(EvalResult &RHS) {
  10874. Val.swap(RHS.Val);
  10875. Failed = RHS.Failed;
  10876. RHS.Failed = false;
  10877. }
  10878. };
  10879. struct Job {
  10880. const Expr *E;
  10881. EvalResult LHSResult; // meaningful only for binary operator expression.
  10882. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  10883. Job() = default;
  10884. Job(Job &&) = default;
  10885. void startSpeculativeEval(EvalInfo &Info) {
  10886. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  10887. }
  10888. private:
  10889. SpeculativeEvaluationRAII SpecEvalRAII;
  10890. };
  10891. SmallVector<Job, 16> Queue;
  10892. IntExprEvaluator &IntEval;
  10893. EvalInfo &Info;
  10894. APValue &FinalResult;
  10895. public:
  10896. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  10897. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  10898. /// True if \param E is a binary operator that we are going to handle
  10899. /// data recursively.
  10900. /// We handle binary operators that are comma, logical, or that have operands
  10901. /// with integral or enumeration type.
  10902. static bool shouldEnqueue(const BinaryOperator *E) {
  10903. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  10904. (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
  10905. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  10906. E->getRHS()->getType()->isIntegralOrEnumerationType());
  10907. }
  10908. bool Traverse(const BinaryOperator *E) {
  10909. enqueue(E);
  10910. EvalResult PrevResult;
  10911. while (!Queue.empty())
  10912. process(PrevResult);
  10913. if (PrevResult.Failed) return false;
  10914. FinalResult.swap(PrevResult.Val);
  10915. return true;
  10916. }
  10917. private:
  10918. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  10919. return IntEval.Success(Value, E, Result);
  10920. }
  10921. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  10922. return IntEval.Success(Value, E, Result);
  10923. }
  10924. bool Error(const Expr *E) {
  10925. return IntEval.Error(E);
  10926. }
  10927. bool Error(const Expr *E, diag::kind D) {
  10928. return IntEval.Error(E, D);
  10929. }
  10930. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  10931. return Info.CCEDiag(E, D);
  10932. }
  10933. // Returns true if visiting the RHS is necessary, false otherwise.
  10934. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  10935. bool &SuppressRHSDiags);
  10936. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  10937. const BinaryOperator *E, APValue &Result);
  10938. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  10939. Result.Failed = !Evaluate(Result.Val, Info, E);
  10940. if (Result.Failed)
  10941. Result.Val = APValue();
  10942. }
  10943. void process(EvalResult &Result);
  10944. void enqueue(const Expr *E) {
  10945. E = E->IgnoreParens();
  10946. Queue.resize(Queue.size()+1);
  10947. Queue.back().E = E;
  10948. Queue.back().Kind = Job::AnyExprKind;
  10949. }
  10950. };
  10951. }
  10952. bool DataRecursiveIntBinOpEvaluator::
  10953. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  10954. bool &SuppressRHSDiags) {
  10955. if (E->getOpcode() == BO_Comma) {
  10956. // Ignore LHS but note if we could not evaluate it.
  10957. if (LHSResult.Failed)
  10958. return Info.noteSideEffect();
  10959. return true;
  10960. }
  10961. if (E->isLogicalOp()) {
  10962. bool LHSAsBool;
  10963. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  10964. // We were able to evaluate the LHS, see if we can get away with not
  10965. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  10966. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  10967. Success(LHSAsBool, E, LHSResult.Val);
  10968. return false; // Ignore RHS
  10969. }
  10970. } else {
  10971. LHSResult.Failed = true;
  10972. // Since we weren't able to evaluate the left hand side, it
  10973. // might have had side effects.
  10974. if (!Info.noteSideEffect())
  10975. return false;
  10976. // We can't evaluate the LHS; however, sometimes the result
  10977. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  10978. // Don't ignore RHS and suppress diagnostics from this arm.
  10979. SuppressRHSDiags = true;
  10980. }
  10981. return true;
  10982. }
  10983. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  10984. E->getRHS()->getType()->isIntegralOrEnumerationType());
  10985. if (LHSResult.Failed && !Info.noteFailure())
  10986. return false; // Ignore RHS;
  10987. return true;
  10988. }
  10989. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  10990. bool IsSub) {
  10991. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  10992. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  10993. // offsets.
  10994. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  10995. CharUnits &Offset = LVal.getLValueOffset();
  10996. uint64_t Offset64 = Offset.getQuantity();
  10997. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  10998. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  10999. : Offset64 + Index64);
  11000. }
  11001. bool DataRecursiveIntBinOpEvaluator::
  11002. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  11003. const BinaryOperator *E, APValue &Result) {
  11004. if (E->getOpcode() == BO_Comma) {
  11005. if (RHSResult.Failed)
  11006. return false;
  11007. Result = RHSResult.Val;
  11008. return true;
  11009. }
  11010. if (E->isLogicalOp()) {
  11011. bool lhsResult, rhsResult;
  11012. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  11013. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  11014. if (LHSIsOK) {
  11015. if (RHSIsOK) {
  11016. if (E->getOpcode() == BO_LOr)
  11017. return Success(lhsResult || rhsResult, E, Result);
  11018. else
  11019. return Success(lhsResult && rhsResult, E, Result);
  11020. }
  11021. } else {
  11022. if (RHSIsOK) {
  11023. // We can't evaluate the LHS; however, sometimes the result
  11024. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  11025. if (rhsResult == (E->getOpcode() == BO_LOr))
  11026. return Success(rhsResult, E, Result);
  11027. }
  11028. }
  11029. return false;
  11030. }
  11031. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  11032. E->getRHS()->getType()->isIntegralOrEnumerationType());
  11033. if (LHSResult.Failed || RHSResult.Failed)
  11034. return false;
  11035. const APValue &LHSVal = LHSResult.Val;
  11036. const APValue &RHSVal = RHSResult.Val;
  11037. // Handle cases like (unsigned long)&a + 4.
  11038. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  11039. Result = LHSVal;
  11040. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  11041. return true;
  11042. }
  11043. // Handle cases like 4 + (unsigned long)&a
  11044. if (E->getOpcode() == BO_Add &&
  11045. RHSVal.isLValue() && LHSVal.isInt()) {
  11046. Result = RHSVal;
  11047. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  11048. return true;
  11049. }
  11050. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  11051. // Handle (intptr_t)&&A - (intptr_t)&&B.
  11052. if (!LHSVal.getLValueOffset().isZero() ||
  11053. !RHSVal.getLValueOffset().isZero())
  11054. return false;
  11055. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  11056. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  11057. if (!LHSExpr || !RHSExpr)
  11058. return false;
  11059. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  11060. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  11061. if (!LHSAddrExpr || !RHSAddrExpr)
  11062. return false;
  11063. // Make sure both labels come from the same function.
  11064. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  11065. RHSAddrExpr->getLabel()->getDeclContext())
  11066. return false;
  11067. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  11068. return true;
  11069. }
  11070. // All the remaining cases expect both operands to be an integer
  11071. if (!LHSVal.isInt() || !RHSVal.isInt())
  11072. return Error(E);
  11073. // Set up the width and signedness manually, in case it can't be deduced
  11074. // from the operation we're performing.
  11075. // FIXME: Don't do this in the cases where we can deduce it.
  11076. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  11077. E->getType()->isUnsignedIntegerOrEnumerationType());
  11078. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  11079. RHSVal.getInt(), Value))
  11080. return false;
  11081. return Success(Value, E, Result);
  11082. }
  11083. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  11084. Job &job = Queue.back();
  11085. switch (job.Kind) {
  11086. case Job::AnyExprKind: {
  11087. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  11088. if (shouldEnqueue(Bop)) {
  11089. job.Kind = Job::BinOpKind;
  11090. enqueue(Bop->getLHS());
  11091. return;
  11092. }
  11093. }
  11094. EvaluateExpr(job.E, Result);
  11095. Queue.pop_back();
  11096. return;
  11097. }
  11098. case Job::BinOpKind: {
  11099. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  11100. bool SuppressRHSDiags = false;
  11101. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  11102. Queue.pop_back();
  11103. return;
  11104. }
  11105. if (SuppressRHSDiags)
  11106. job.startSpeculativeEval(Info);
  11107. job.LHSResult.swap(Result);
  11108. job.Kind = Job::BinOpVisitedLHSKind;
  11109. enqueue(Bop->getRHS());
  11110. return;
  11111. }
  11112. case Job::BinOpVisitedLHSKind: {
  11113. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  11114. EvalResult RHS;
  11115. RHS.swap(Result);
  11116. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  11117. Queue.pop_back();
  11118. return;
  11119. }
  11120. }
  11121. llvm_unreachable("Invalid Job::Kind!");
  11122. }
  11123. namespace {
  11124. enum class CmpResult {
  11125. Unequal,
  11126. Less,
  11127. Equal,
  11128. Greater,
  11129. Unordered,
  11130. };
  11131. }
  11132. template <class SuccessCB, class AfterCB>
  11133. static bool
  11134. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  11135. SuccessCB &&Success, AfterCB &&DoAfter) {
  11136. assert(!E->isValueDependent());
  11137. assert(E->isComparisonOp() && "expected comparison operator");
  11138. assert((E->getOpcode() == BO_Cmp ||
  11139. E->getType()->isIntegralOrEnumerationType()) &&
  11140. "unsupported binary expression evaluation");
  11141. auto Error = [&](const Expr *E) {
  11142. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  11143. return false;
  11144. };
  11145. bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
  11146. bool IsEquality = E->isEqualityOp();
  11147. QualType LHSTy = E->getLHS()->getType();
  11148. QualType RHSTy = E->getRHS()->getType();
  11149. if (LHSTy->isIntegralOrEnumerationType() &&
  11150. RHSTy->isIntegralOrEnumerationType()) {
  11151. APSInt LHS, RHS;
  11152. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  11153. if (!LHSOK && !Info.noteFailure())
  11154. return false;
  11155. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  11156. return false;
  11157. if (LHS < RHS)
  11158. return Success(CmpResult::Less, E);
  11159. if (LHS > RHS)
  11160. return Success(CmpResult::Greater, E);
  11161. return Success(CmpResult::Equal, E);
  11162. }
  11163. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  11164. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  11165. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  11166. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  11167. if (!LHSOK && !Info.noteFailure())
  11168. return false;
  11169. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  11170. return false;
  11171. if (LHSFX < RHSFX)
  11172. return Success(CmpResult::Less, E);
  11173. if (LHSFX > RHSFX)
  11174. return Success(CmpResult::Greater, E);
  11175. return Success(CmpResult::Equal, E);
  11176. }
  11177. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  11178. ComplexValue LHS, RHS;
  11179. bool LHSOK;
  11180. if (E->isAssignmentOp()) {
  11181. LValue LV;
  11182. EvaluateLValue(E->getLHS(), LV, Info);
  11183. LHSOK = false;
  11184. } else if (LHSTy->isRealFloatingType()) {
  11185. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  11186. if (LHSOK) {
  11187. LHS.makeComplexFloat();
  11188. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  11189. }
  11190. } else {
  11191. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  11192. }
  11193. if (!LHSOK && !Info.noteFailure())
  11194. return false;
  11195. if (E->getRHS()->getType()->isRealFloatingType()) {
  11196. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  11197. return false;
  11198. RHS.makeComplexFloat();
  11199. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  11200. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  11201. return false;
  11202. if (LHS.isComplexFloat()) {
  11203. APFloat::cmpResult CR_r =
  11204. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  11205. APFloat::cmpResult CR_i =
  11206. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  11207. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  11208. return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
  11209. } else {
  11210. assert(IsEquality && "invalid complex comparison");
  11211. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  11212. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  11213. return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
  11214. }
  11215. }
  11216. if (LHSTy->isRealFloatingType() &&
  11217. RHSTy->isRealFloatingType()) {
  11218. APFloat RHS(0.0), LHS(0.0);
  11219. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  11220. if (!LHSOK && !Info.noteFailure())
  11221. return false;
  11222. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  11223. return false;
  11224. assert(E->isComparisonOp() && "Invalid binary operator!");
  11225. llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
  11226. if (!Info.InConstantContext &&
  11227. APFloatCmpResult == APFloat::cmpUnordered &&
  11228. E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
  11229. // Note: Compares may raise invalid in some cases involving NaN or sNaN.
  11230. Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
  11231. return false;
  11232. }
  11233. auto GetCmpRes = [&]() {
  11234. switch (APFloatCmpResult) {
  11235. case APFloat::cmpEqual:
  11236. return CmpResult::Equal;
  11237. case APFloat::cmpLessThan:
  11238. return CmpResult::Less;
  11239. case APFloat::cmpGreaterThan:
  11240. return CmpResult::Greater;
  11241. case APFloat::cmpUnordered:
  11242. return CmpResult::Unordered;
  11243. }
  11244. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  11245. };
  11246. return Success(GetCmpRes(), E);
  11247. }
  11248. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  11249. LValue LHSValue, RHSValue;
  11250. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  11251. if (!LHSOK && !Info.noteFailure())
  11252. return false;
  11253. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  11254. return false;
  11255. // Reject differing bases from the normal codepath; we special-case
  11256. // comparisons to null.
  11257. if (!HasSameBase(LHSValue, RHSValue)) {
  11258. // Inequalities and subtractions between unrelated pointers have
  11259. // unspecified or undefined behavior.
  11260. if (!IsEquality) {
  11261. Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
  11262. return false;
  11263. }
  11264. // A constant address may compare equal to the address of a symbol.
  11265. // The one exception is that address of an object cannot compare equal
  11266. // to a null pointer constant.
  11267. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  11268. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  11269. return Error(E);
  11270. // It's implementation-defined whether distinct literals will have
  11271. // distinct addresses. In clang, the result of such a comparison is
  11272. // unspecified, so it is not a constant expression. However, we do know
  11273. // that the address of a literal will be non-null.
  11274. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  11275. LHSValue.Base && RHSValue.Base)
  11276. return Error(E);
  11277. // We can't tell whether weak symbols will end up pointing to the same
  11278. // object.
  11279. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  11280. return Error(E);
  11281. // We can't compare the address of the start of one object with the
  11282. // past-the-end address of another object, per C++ DR1652.
  11283. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  11284. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  11285. (RHSValue.Base && RHSValue.Offset.isZero() &&
  11286. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  11287. return Error(E);
  11288. // We can't tell whether an object is at the same address as another
  11289. // zero sized object.
  11290. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  11291. (LHSValue.Base && isZeroSized(RHSValue)))
  11292. return Error(E);
  11293. return Success(CmpResult::Unequal, E);
  11294. }
  11295. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  11296. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  11297. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  11298. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  11299. // C++11 [expr.rel]p3:
  11300. // Pointers to void (after pointer conversions) can be compared, with a
  11301. // result defined as follows: If both pointers represent the same
  11302. // address or are both the null pointer value, the result is true if the
  11303. // operator is <= or >= and false otherwise; otherwise the result is
  11304. // unspecified.
  11305. // We interpret this as applying to pointers to *cv* void.
  11306. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  11307. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  11308. // C++11 [expr.rel]p2:
  11309. // - If two pointers point to non-static data members of the same object,
  11310. // or to subobjects or array elements fo such members, recursively, the
  11311. // pointer to the later declared member compares greater provided the
  11312. // two members have the same access control and provided their class is
  11313. // not a union.
  11314. // [...]
  11315. // - Otherwise pointer comparisons are unspecified.
  11316. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  11317. bool WasArrayIndex;
  11318. unsigned Mismatch = FindDesignatorMismatch(
  11319. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  11320. // At the point where the designators diverge, the comparison has a
  11321. // specified value if:
  11322. // - we are comparing array indices
  11323. // - we are comparing fields of a union, or fields with the same access
  11324. // Otherwise, the result is unspecified and thus the comparison is not a
  11325. // constant expression.
  11326. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  11327. Mismatch < RHSDesignator.Entries.size()) {
  11328. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  11329. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  11330. if (!LF && !RF)
  11331. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  11332. else if (!LF)
  11333. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  11334. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  11335. << RF->getParent() << RF;
  11336. else if (!RF)
  11337. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  11338. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  11339. << LF->getParent() << LF;
  11340. else if (!LF->getParent()->isUnion() &&
  11341. LF->getAccess() != RF->getAccess())
  11342. Info.CCEDiag(E,
  11343. diag::note_constexpr_pointer_comparison_differing_access)
  11344. << LF << LF->getAccess() << RF << RF->getAccess()
  11345. << LF->getParent();
  11346. }
  11347. }
  11348. // The comparison here must be unsigned, and performed with the same
  11349. // width as the pointer.
  11350. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  11351. uint64_t CompareLHS = LHSOffset.getQuantity();
  11352. uint64_t CompareRHS = RHSOffset.getQuantity();
  11353. assert(PtrSize <= 64 && "Unexpected pointer width");
  11354. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  11355. CompareLHS &= Mask;
  11356. CompareRHS &= Mask;
  11357. // If there is a base and this is a relational operator, we can only
  11358. // compare pointers within the object in question; otherwise, the result
  11359. // depends on where the object is located in memory.
  11360. if (!LHSValue.Base.isNull() && IsRelational) {
  11361. QualType BaseTy = getType(LHSValue.Base);
  11362. if (BaseTy->isIncompleteType())
  11363. return Error(E);
  11364. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  11365. uint64_t OffsetLimit = Size.getQuantity();
  11366. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  11367. return Error(E);
  11368. }
  11369. if (CompareLHS < CompareRHS)
  11370. return Success(CmpResult::Less, E);
  11371. if (CompareLHS > CompareRHS)
  11372. return Success(CmpResult::Greater, E);
  11373. return Success(CmpResult::Equal, E);
  11374. }
  11375. if (LHSTy->isMemberPointerType()) {
  11376. assert(IsEquality && "unexpected member pointer operation");
  11377. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  11378. MemberPtr LHSValue, RHSValue;
  11379. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  11380. if (!LHSOK && !Info.noteFailure())
  11381. return false;
  11382. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  11383. return false;
  11384. // C++11 [expr.eq]p2:
  11385. // If both operands are null, they compare equal. Otherwise if only one is
  11386. // null, they compare unequal.
  11387. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  11388. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  11389. return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
  11390. }
  11391. // Otherwise if either is a pointer to a virtual member function, the
  11392. // result is unspecified.
  11393. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  11394. if (MD->isVirtual())
  11395. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  11396. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  11397. if (MD->isVirtual())
  11398. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  11399. // Otherwise they compare equal if and only if they would refer to the
  11400. // same member of the same most derived object or the same subobject if
  11401. // they were dereferenced with a hypothetical object of the associated
  11402. // class type.
  11403. bool Equal = LHSValue == RHSValue;
  11404. return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
  11405. }
  11406. if (LHSTy->isNullPtrType()) {
  11407. assert(E->isComparisonOp() && "unexpected nullptr operation");
  11408. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  11409. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  11410. // are compared, the result is true of the operator is <=, >= or ==, and
  11411. // false otherwise.
  11412. return Success(CmpResult::Equal, E);
  11413. }
  11414. return DoAfter();
  11415. }
  11416. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  11417. if (!CheckLiteralType(Info, E))
  11418. return false;
  11419. auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
  11420. ComparisonCategoryResult CCR;
  11421. switch (CR) {
  11422. case CmpResult::Unequal:
  11423. llvm_unreachable("should never produce Unequal for three-way comparison");
  11424. case CmpResult::Less:
  11425. CCR = ComparisonCategoryResult::Less;
  11426. break;
  11427. case CmpResult::Equal:
  11428. CCR = ComparisonCategoryResult::Equal;
  11429. break;
  11430. case CmpResult::Greater:
  11431. CCR = ComparisonCategoryResult::Greater;
  11432. break;
  11433. case CmpResult::Unordered:
  11434. CCR = ComparisonCategoryResult::Unordered;
  11435. break;
  11436. }
  11437. // Evaluation succeeded. Lookup the information for the comparison category
  11438. // type and fetch the VarDecl for the result.
  11439. const ComparisonCategoryInfo &CmpInfo =
  11440. Info.Ctx.CompCategories.getInfoForType(E->getType());
  11441. const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
  11442. // Check and evaluate the result as a constant expression.
  11443. LValue LV;
  11444. LV.set(VD);
  11445. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  11446. return false;
  11447. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
  11448. ConstantExprKind::Normal);
  11449. };
  11450. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  11451. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  11452. });
  11453. }
  11454. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  11455. // We don't support assignment in C. C++ assignments don't get here because
  11456. // assignment is an lvalue in C++.
  11457. if (E->isAssignmentOp()) {
  11458. Error(E);
  11459. if (!Info.noteFailure())
  11460. return false;
  11461. }
  11462. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  11463. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  11464. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  11465. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  11466. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  11467. if (E->isComparisonOp()) {
  11468. // Evaluate builtin binary comparisons by evaluating them as three-way
  11469. // comparisons and then translating the result.
  11470. auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
  11471. assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
  11472. "should only produce Unequal for equality comparisons");
  11473. bool IsEqual = CR == CmpResult::Equal,
  11474. IsLess = CR == CmpResult::Less,
  11475. IsGreater = CR == CmpResult::Greater;
  11476. auto Op = E->getOpcode();
  11477. switch (Op) {
  11478. default:
  11479. llvm_unreachable("unsupported binary operator");
  11480. case BO_EQ:
  11481. case BO_NE:
  11482. return Success(IsEqual == (Op == BO_EQ), E);
  11483. case BO_LT:
  11484. return Success(IsLess, E);
  11485. case BO_GT:
  11486. return Success(IsGreater, E);
  11487. case BO_LE:
  11488. return Success(IsEqual || IsLess, E);
  11489. case BO_GE:
  11490. return Success(IsEqual || IsGreater, E);
  11491. }
  11492. };
  11493. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  11494. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11495. });
  11496. }
  11497. QualType LHSTy = E->getLHS()->getType();
  11498. QualType RHSTy = E->getRHS()->getType();
  11499. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  11500. E->getOpcode() == BO_Sub) {
  11501. LValue LHSValue, RHSValue;
  11502. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  11503. if (!LHSOK && !Info.noteFailure())
  11504. return false;
  11505. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  11506. return false;
  11507. // Reject differing bases from the normal codepath; we special-case
  11508. // comparisons to null.
  11509. if (!HasSameBase(LHSValue, RHSValue)) {
  11510. // Handle &&A - &&B.
  11511. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  11512. return Error(E);
  11513. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  11514. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  11515. if (!LHSExpr || !RHSExpr)
  11516. return Error(E);
  11517. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  11518. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  11519. if (!LHSAddrExpr || !RHSAddrExpr)
  11520. return Error(E);
  11521. // Make sure both labels come from the same function.
  11522. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  11523. RHSAddrExpr->getLabel()->getDeclContext())
  11524. return Error(E);
  11525. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  11526. }
  11527. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  11528. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  11529. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  11530. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  11531. // C++11 [expr.add]p6:
  11532. // Unless both pointers point to elements of the same array object, or
  11533. // one past the last element of the array object, the behavior is
  11534. // undefined.
  11535. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  11536. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  11537. RHSDesignator))
  11538. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  11539. QualType Type = E->getLHS()->getType();
  11540. QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
  11541. CharUnits ElementSize;
  11542. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  11543. return false;
  11544. // As an extension, a type may have zero size (empty struct or union in
  11545. // C, array of zero length). Pointer subtraction in such cases has
  11546. // undefined behavior, so is not constant.
  11547. if (ElementSize.isZero()) {
  11548. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  11549. << ElementType;
  11550. return false;
  11551. }
  11552. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  11553. // and produce incorrect results when it overflows. Such behavior
  11554. // appears to be non-conforming, but is common, so perhaps we should
  11555. // assume the standard intended for such cases to be undefined behavior
  11556. // and check for them.
  11557. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  11558. // overflow in the final conversion to ptrdiff_t.
  11559. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  11560. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  11561. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  11562. false);
  11563. APSInt TrueResult = (LHS - RHS) / ElemSize;
  11564. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  11565. if (Result.extend(65) != TrueResult &&
  11566. !HandleOverflow(Info, E, TrueResult, E->getType()))
  11567. return false;
  11568. return Success(Result, E);
  11569. }
  11570. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  11571. }
  11572. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  11573. /// a result as the expression's type.
  11574. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  11575. const UnaryExprOrTypeTraitExpr *E) {
  11576. switch(E->getKind()) {
  11577. case UETT_PreferredAlignOf:
  11578. case UETT_AlignOf: {
  11579. if (E->isArgumentType())
  11580. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  11581. E);
  11582. else
  11583. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  11584. E);
  11585. }
  11586. case UETT_VecStep: {
  11587. QualType Ty = E->getTypeOfArgument();
  11588. if (Ty->isVectorType()) {
  11589. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  11590. // The vec_step built-in functions that take a 3-component
  11591. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  11592. if (n == 3)
  11593. n = 4;
  11594. return Success(n, E);
  11595. } else
  11596. return Success(1, E);
  11597. }
  11598. case UETT_SizeOf: {
  11599. QualType SrcTy = E->getTypeOfArgument();
  11600. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  11601. // the result is the size of the referenced type."
  11602. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  11603. SrcTy = Ref->getPointeeType();
  11604. CharUnits Sizeof;
  11605. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  11606. return false;
  11607. return Success(Sizeof, E);
  11608. }
  11609. case UETT_OpenMPRequiredSimdAlign:
  11610. assert(E->isArgumentType());
  11611. return Success(
  11612. Info.Ctx.toCharUnitsFromBits(
  11613. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  11614. .getQuantity(),
  11615. E);
  11616. }
  11617. llvm_unreachable("unknown expr/type trait");
  11618. }
  11619. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  11620. CharUnits Result;
  11621. unsigned n = OOE->getNumComponents();
  11622. if (n == 0)
  11623. return Error(OOE);
  11624. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  11625. for (unsigned i = 0; i != n; ++i) {
  11626. OffsetOfNode ON = OOE->getComponent(i);
  11627. switch (ON.getKind()) {
  11628. case OffsetOfNode::Array: {
  11629. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  11630. APSInt IdxResult;
  11631. if (!EvaluateInteger(Idx, IdxResult, Info))
  11632. return false;
  11633. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  11634. if (!AT)
  11635. return Error(OOE);
  11636. CurrentType = AT->getElementType();
  11637. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  11638. Result += IdxResult.getSExtValue() * ElementSize;
  11639. break;
  11640. }
  11641. case OffsetOfNode::Field: {
  11642. FieldDecl *MemberDecl = ON.getField();
  11643. const RecordType *RT = CurrentType->getAs<RecordType>();
  11644. if (!RT)
  11645. return Error(OOE);
  11646. RecordDecl *RD = RT->getDecl();
  11647. if (RD->isInvalidDecl()) return false;
  11648. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  11649. unsigned i = MemberDecl->getFieldIndex();
  11650. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  11651. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  11652. CurrentType = MemberDecl->getType().getNonReferenceType();
  11653. break;
  11654. }
  11655. case OffsetOfNode::Identifier:
  11656. llvm_unreachable("dependent __builtin_offsetof");
  11657. case OffsetOfNode::Base: {
  11658. CXXBaseSpecifier *BaseSpec = ON.getBase();
  11659. if (BaseSpec->isVirtual())
  11660. return Error(OOE);
  11661. // Find the layout of the class whose base we are looking into.
  11662. const RecordType *RT = CurrentType->getAs<RecordType>();
  11663. if (!RT)
  11664. return Error(OOE);
  11665. RecordDecl *RD = RT->getDecl();
  11666. if (RD->isInvalidDecl()) return false;
  11667. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  11668. // Find the base class itself.
  11669. CurrentType = BaseSpec->getType();
  11670. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  11671. if (!BaseRT)
  11672. return Error(OOE);
  11673. // Add the offset to the base.
  11674. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  11675. break;
  11676. }
  11677. }
  11678. }
  11679. return Success(Result, OOE);
  11680. }
  11681. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11682. switch (E->getOpcode()) {
  11683. default:
  11684. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  11685. // See C99 6.6p3.
  11686. return Error(E);
  11687. case UO_Extension:
  11688. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  11689. // If so, we could clear the diagnostic ID.
  11690. return Visit(E->getSubExpr());
  11691. case UO_Plus:
  11692. // The result is just the value.
  11693. return Visit(E->getSubExpr());
  11694. case UO_Minus: {
  11695. if (!Visit(E->getSubExpr()))
  11696. return false;
  11697. if (!Result.isInt()) return Error(E);
  11698. const APSInt &Value = Result.getInt();
  11699. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  11700. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  11701. E->getType()))
  11702. return false;
  11703. return Success(-Value, E);
  11704. }
  11705. case UO_Not: {
  11706. if (!Visit(E->getSubExpr()))
  11707. return false;
  11708. if (!Result.isInt()) return Error(E);
  11709. return Success(~Result.getInt(), E);
  11710. }
  11711. case UO_LNot: {
  11712. bool bres;
  11713. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  11714. return false;
  11715. return Success(!bres, E);
  11716. }
  11717. }
  11718. }
  11719. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  11720. /// result type is integer.
  11721. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11722. const Expr *SubExpr = E->getSubExpr();
  11723. QualType DestType = E->getType();
  11724. QualType SrcType = SubExpr->getType();
  11725. switch (E->getCastKind()) {
  11726. case CK_BaseToDerived:
  11727. case CK_DerivedToBase:
  11728. case CK_UncheckedDerivedToBase:
  11729. case CK_Dynamic:
  11730. case CK_ToUnion:
  11731. case CK_ArrayToPointerDecay:
  11732. case CK_FunctionToPointerDecay:
  11733. case CK_NullToPointer:
  11734. case CK_NullToMemberPointer:
  11735. case CK_BaseToDerivedMemberPointer:
  11736. case CK_DerivedToBaseMemberPointer:
  11737. case CK_ReinterpretMemberPointer:
  11738. case CK_ConstructorConversion:
  11739. case CK_IntegralToPointer:
  11740. case CK_ToVoid:
  11741. case CK_VectorSplat:
  11742. case CK_IntegralToFloating:
  11743. case CK_FloatingCast:
  11744. case CK_CPointerToObjCPointerCast:
  11745. case CK_BlockPointerToObjCPointerCast:
  11746. case CK_AnyPointerToBlockPointerCast:
  11747. case CK_ObjCObjectLValueCast:
  11748. case CK_FloatingRealToComplex:
  11749. case CK_FloatingComplexToReal:
  11750. case CK_FloatingComplexCast:
  11751. case CK_FloatingComplexToIntegralComplex:
  11752. case CK_IntegralRealToComplex:
  11753. case CK_IntegralComplexCast:
  11754. case CK_IntegralComplexToFloatingComplex:
  11755. case CK_BuiltinFnToFnPtr:
  11756. case CK_ZeroToOCLOpaqueType:
  11757. case CK_NonAtomicToAtomic:
  11758. case CK_AddressSpaceConversion:
  11759. case CK_IntToOCLSampler:
  11760. case CK_FloatingToFixedPoint:
  11761. case CK_FixedPointToFloating:
  11762. case CK_FixedPointCast:
  11763. case CK_IntegralToFixedPoint:
  11764. case CK_MatrixCast:
  11765. llvm_unreachable("invalid cast kind for integral value");
  11766. case CK_BitCast:
  11767. case CK_Dependent:
  11768. case CK_LValueBitCast:
  11769. case CK_ARCProduceObject:
  11770. case CK_ARCConsumeObject:
  11771. case CK_ARCReclaimReturnedObject:
  11772. case CK_ARCExtendBlockObject:
  11773. case CK_CopyAndAutoreleaseBlockObject:
  11774. return Error(E);
  11775. case CK_UserDefinedConversion:
  11776. case CK_LValueToRValue:
  11777. case CK_AtomicToNonAtomic:
  11778. case CK_NoOp:
  11779. case CK_LValueToRValueBitCast:
  11780. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11781. case CK_MemberPointerToBoolean:
  11782. case CK_PointerToBoolean:
  11783. case CK_IntegralToBoolean:
  11784. case CK_FloatingToBoolean:
  11785. case CK_BooleanToSignedIntegral:
  11786. case CK_FloatingComplexToBoolean:
  11787. case CK_IntegralComplexToBoolean: {
  11788. bool BoolResult;
  11789. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  11790. return false;
  11791. uint64_t IntResult = BoolResult;
  11792. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  11793. IntResult = (uint64_t)-1;
  11794. return Success(IntResult, E);
  11795. }
  11796. case CK_FixedPointToIntegral: {
  11797. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  11798. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  11799. return false;
  11800. bool Overflowed;
  11801. llvm::APSInt Result = Src.convertToInt(
  11802. Info.Ctx.getIntWidth(DestType),
  11803. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  11804. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  11805. return false;
  11806. return Success(Result, E);
  11807. }
  11808. case CK_FixedPointToBoolean: {
  11809. // Unsigned padding does not affect this.
  11810. APValue Val;
  11811. if (!Evaluate(Val, Info, SubExpr))
  11812. return false;
  11813. return Success(Val.getFixedPoint().getBoolValue(), E);
  11814. }
  11815. case CK_IntegralCast: {
  11816. if (!Visit(SubExpr))
  11817. return false;
  11818. if (!Result.isInt()) {
  11819. // Allow casts of address-of-label differences if they are no-ops
  11820. // or narrowing. (The narrowing case isn't actually guaranteed to
  11821. // be constant-evaluatable except in some narrow cases which are hard
  11822. // to detect here. We let it through on the assumption the user knows
  11823. // what they are doing.)
  11824. if (Result.isAddrLabelDiff())
  11825. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  11826. // Only allow casts of lvalues if they are lossless.
  11827. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  11828. }
  11829. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  11830. Result.getInt()), E);
  11831. }
  11832. case CK_PointerToIntegral: {
  11833. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  11834. LValue LV;
  11835. if (!EvaluatePointer(SubExpr, LV, Info))
  11836. return false;
  11837. if (LV.getLValueBase()) {
  11838. // Only allow based lvalue casts if they are lossless.
  11839. // FIXME: Allow a larger integer size than the pointer size, and allow
  11840. // narrowing back down to pointer width in subsequent integral casts.
  11841. // FIXME: Check integer type's active bits, not its type size.
  11842. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  11843. return Error(E);
  11844. LV.Designator.setInvalid();
  11845. LV.moveInto(Result);
  11846. return true;
  11847. }
  11848. APSInt AsInt;
  11849. APValue V;
  11850. LV.moveInto(V);
  11851. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  11852. llvm_unreachable("Can't cast this!");
  11853. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  11854. }
  11855. case CK_IntegralComplexToReal: {
  11856. ComplexValue C;
  11857. if (!EvaluateComplex(SubExpr, C, Info))
  11858. return false;
  11859. return Success(C.getComplexIntReal(), E);
  11860. }
  11861. case CK_FloatingToIntegral: {
  11862. APFloat F(0.0);
  11863. if (!EvaluateFloat(SubExpr, F, Info))
  11864. return false;
  11865. APSInt Value;
  11866. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  11867. return false;
  11868. return Success(Value, E);
  11869. }
  11870. }
  11871. llvm_unreachable("unknown cast resulting in integral value");
  11872. }
  11873. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  11874. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  11875. ComplexValue LV;
  11876. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  11877. return false;
  11878. if (!LV.isComplexInt())
  11879. return Error(E);
  11880. return Success(LV.getComplexIntReal(), E);
  11881. }
  11882. return Visit(E->getSubExpr());
  11883. }
  11884. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  11885. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  11886. ComplexValue LV;
  11887. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  11888. return false;
  11889. if (!LV.isComplexInt())
  11890. return Error(E);
  11891. return Success(LV.getComplexIntImag(), E);
  11892. }
  11893. VisitIgnoredValue(E->getSubExpr());
  11894. return Success(0, E);
  11895. }
  11896. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  11897. return Success(E->getPackLength(), E);
  11898. }
  11899. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  11900. return Success(E->getValue(), E);
  11901. }
  11902. bool IntExprEvaluator::VisitConceptSpecializationExpr(
  11903. const ConceptSpecializationExpr *E) {
  11904. return Success(E->isSatisfied(), E);
  11905. }
  11906. bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
  11907. return Success(E->isSatisfied(), E);
  11908. }
  11909. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  11910. switch (E->getOpcode()) {
  11911. default:
  11912. // Invalid unary operators
  11913. return Error(E);
  11914. case UO_Plus:
  11915. // The result is just the value.
  11916. return Visit(E->getSubExpr());
  11917. case UO_Minus: {
  11918. if (!Visit(E->getSubExpr())) return false;
  11919. if (!Result.isFixedPoint())
  11920. return Error(E);
  11921. bool Overflowed;
  11922. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  11923. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  11924. return false;
  11925. return Success(Negated, E);
  11926. }
  11927. case UO_LNot: {
  11928. bool bres;
  11929. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  11930. return false;
  11931. return Success(!bres, E);
  11932. }
  11933. }
  11934. }
  11935. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  11936. const Expr *SubExpr = E->getSubExpr();
  11937. QualType DestType = E->getType();
  11938. assert(DestType->isFixedPointType() &&
  11939. "Expected destination type to be a fixed point type");
  11940. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  11941. switch (E->getCastKind()) {
  11942. case CK_FixedPointCast: {
  11943. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  11944. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  11945. return false;
  11946. bool Overflowed;
  11947. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  11948. if (Overflowed) {
  11949. if (Info.checkingForUndefinedBehavior())
  11950. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  11951. diag::warn_fixedpoint_constant_overflow)
  11952. << Result.toString() << E->getType();
  11953. if (!HandleOverflow(Info, E, Result, E->getType()))
  11954. return false;
  11955. }
  11956. return Success(Result, E);
  11957. }
  11958. case CK_IntegralToFixedPoint: {
  11959. APSInt Src;
  11960. if (!EvaluateInteger(SubExpr, Src, Info))
  11961. return false;
  11962. bool Overflowed;
  11963. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  11964. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  11965. if (Overflowed) {
  11966. if (Info.checkingForUndefinedBehavior())
  11967. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  11968. diag::warn_fixedpoint_constant_overflow)
  11969. << IntResult.toString() << E->getType();
  11970. if (!HandleOverflow(Info, E, IntResult, E->getType()))
  11971. return false;
  11972. }
  11973. return Success(IntResult, E);
  11974. }
  11975. case CK_FloatingToFixedPoint: {
  11976. APFloat Src(0.0);
  11977. if (!EvaluateFloat(SubExpr, Src, Info))
  11978. return false;
  11979. bool Overflowed;
  11980. APFixedPoint Result = APFixedPoint::getFromFloatValue(
  11981. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  11982. if (Overflowed) {
  11983. if (Info.checkingForUndefinedBehavior())
  11984. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  11985. diag::warn_fixedpoint_constant_overflow)
  11986. << Result.toString() << E->getType();
  11987. if (!HandleOverflow(Info, E, Result, E->getType()))
  11988. return false;
  11989. }
  11990. return Success(Result, E);
  11991. }
  11992. case CK_NoOp:
  11993. case CK_LValueToRValue:
  11994. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  11995. default:
  11996. return Error(E);
  11997. }
  11998. }
  11999. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  12000. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  12001. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  12002. const Expr *LHS = E->getLHS();
  12003. const Expr *RHS = E->getRHS();
  12004. FixedPointSemantics ResultFXSema =
  12005. Info.Ctx.getFixedPointSemantics(E->getType());
  12006. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  12007. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  12008. return false;
  12009. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  12010. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  12011. return false;
  12012. bool OpOverflow = false, ConversionOverflow = false;
  12013. APFixedPoint Result(LHSFX.getSemantics());
  12014. switch (E->getOpcode()) {
  12015. case BO_Add: {
  12016. Result = LHSFX.add(RHSFX, &OpOverflow)
  12017. .convert(ResultFXSema, &ConversionOverflow);
  12018. break;
  12019. }
  12020. case BO_Sub: {
  12021. Result = LHSFX.sub(RHSFX, &OpOverflow)
  12022. .convert(ResultFXSema, &ConversionOverflow);
  12023. break;
  12024. }
  12025. case BO_Mul: {
  12026. Result = LHSFX.mul(RHSFX, &OpOverflow)
  12027. .convert(ResultFXSema, &ConversionOverflow);
  12028. break;
  12029. }
  12030. case BO_Div: {
  12031. if (RHSFX.getValue() == 0) {
  12032. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  12033. return false;
  12034. }
  12035. Result = LHSFX.div(RHSFX, &OpOverflow)
  12036. .convert(ResultFXSema, &ConversionOverflow);
  12037. break;
  12038. }
  12039. case BO_Shl:
  12040. case BO_Shr: {
  12041. FixedPointSemantics LHSSema = LHSFX.getSemantics();
  12042. llvm::APSInt RHSVal = RHSFX.getValue();
  12043. unsigned ShiftBW =
  12044. LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
  12045. unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
  12046. // Embedded-C 4.1.6.2.2:
  12047. // The right operand must be nonnegative and less than the total number
  12048. // of (nonpadding) bits of the fixed-point operand ...
  12049. if (RHSVal.isNegative())
  12050. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
  12051. else if (Amt != RHSVal)
  12052. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  12053. << RHSVal << E->getType() << ShiftBW;
  12054. if (E->getOpcode() == BO_Shl)
  12055. Result = LHSFX.shl(Amt, &OpOverflow);
  12056. else
  12057. Result = LHSFX.shr(Amt, &OpOverflow);
  12058. break;
  12059. }
  12060. default:
  12061. return false;
  12062. }
  12063. if (OpOverflow || ConversionOverflow) {
  12064. if (Info.checkingForUndefinedBehavior())
  12065. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  12066. diag::warn_fixedpoint_constant_overflow)
  12067. << Result.toString() << E->getType();
  12068. if (!HandleOverflow(Info, E, Result, E->getType()))
  12069. return false;
  12070. }
  12071. return Success(Result, E);
  12072. }
  12073. //===----------------------------------------------------------------------===//
  12074. // Float Evaluation
  12075. //===----------------------------------------------------------------------===//
  12076. namespace {
  12077. class FloatExprEvaluator
  12078. : public ExprEvaluatorBase<FloatExprEvaluator> {
  12079. APFloat &Result;
  12080. public:
  12081. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  12082. : ExprEvaluatorBaseTy(info), Result(result) {}
  12083. bool Success(const APValue &V, const Expr *e) {
  12084. Result = V.getFloat();
  12085. return true;
  12086. }
  12087. bool ZeroInitialization(const Expr *E) {
  12088. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  12089. return true;
  12090. }
  12091. bool VisitCallExpr(const CallExpr *E);
  12092. bool VisitUnaryOperator(const UnaryOperator *E);
  12093. bool VisitBinaryOperator(const BinaryOperator *E);
  12094. bool VisitFloatingLiteral(const FloatingLiteral *E);
  12095. bool VisitCastExpr(const CastExpr *E);
  12096. bool VisitUnaryReal(const UnaryOperator *E);
  12097. bool VisitUnaryImag(const UnaryOperator *E);
  12098. // FIXME: Missing: array subscript of vector, member of vector
  12099. };
  12100. } // end anonymous namespace
  12101. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  12102. assert(!E->isValueDependent());
  12103. assert(E->isPRValue() && E->getType()->isRealFloatingType());
  12104. return FloatExprEvaluator(Info, Result).Visit(E);
  12105. }
  12106. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  12107. QualType ResultTy,
  12108. const Expr *Arg,
  12109. bool SNaN,
  12110. llvm::APFloat &Result) {
  12111. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  12112. if (!S) return false;
  12113. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  12114. llvm::APInt fill;
  12115. // Treat empty strings as if they were zero.
  12116. if (S->getString().empty())
  12117. fill = llvm::APInt(32, 0);
  12118. else if (S->getString().getAsInteger(0, fill))
  12119. return false;
  12120. if (Context.getTargetInfo().isNan2008()) {
  12121. if (SNaN)
  12122. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  12123. else
  12124. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  12125. } else {
  12126. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  12127. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  12128. // a different encoding to what became a standard in 2008, and for pre-
  12129. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  12130. // sNaN. This is now known as "legacy NaN" encoding.
  12131. if (SNaN)
  12132. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  12133. else
  12134. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  12135. }
  12136. return true;
  12137. }
  12138. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  12139. switch (E->getBuiltinCallee()) {
  12140. default:
  12141. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  12142. case Builtin::BI__builtin_huge_val:
  12143. case Builtin::BI__builtin_huge_valf:
  12144. case Builtin::BI__builtin_huge_vall:
  12145. case Builtin::BI__builtin_huge_valf128:
  12146. case Builtin::BI__builtin_inf:
  12147. case Builtin::BI__builtin_inff:
  12148. case Builtin::BI__builtin_infl:
  12149. case Builtin::BI__builtin_inff128: {
  12150. const llvm::fltSemantics &Sem =
  12151. Info.Ctx.getFloatTypeSemantics(E->getType());
  12152. Result = llvm::APFloat::getInf(Sem);
  12153. return true;
  12154. }
  12155. case Builtin::BI__builtin_nans:
  12156. case Builtin::BI__builtin_nansf:
  12157. case Builtin::BI__builtin_nansl:
  12158. case Builtin::BI__builtin_nansf128:
  12159. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  12160. true, Result))
  12161. return Error(E);
  12162. return true;
  12163. case Builtin::BI__builtin_nan:
  12164. case Builtin::BI__builtin_nanf:
  12165. case Builtin::BI__builtin_nanl:
  12166. case Builtin::BI__builtin_nanf128:
  12167. // If this is __builtin_nan() turn this into a nan, otherwise we
  12168. // can't constant fold it.
  12169. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  12170. false, Result))
  12171. return Error(E);
  12172. return true;
  12173. case Builtin::BI__builtin_fabs:
  12174. case Builtin::BI__builtin_fabsf:
  12175. case Builtin::BI__builtin_fabsl:
  12176. case Builtin::BI__builtin_fabsf128:
  12177. // The C standard says "fabs raises no floating-point exceptions,
  12178. // even if x is a signaling NaN. The returned value is independent of
  12179. // the current rounding direction mode." Therefore constant folding can
  12180. // proceed without regard to the floating point settings.
  12181. // Reference, WG14 N2478 F.10.4.3
  12182. if (!EvaluateFloat(E->getArg(0), Result, Info))
  12183. return false;
  12184. if (Result.isNegative())
  12185. Result.changeSign();
  12186. return true;
  12187. case Builtin::BI__arithmetic_fence:
  12188. return EvaluateFloat(E->getArg(0), Result, Info);
  12189. // FIXME: Builtin::BI__builtin_powi
  12190. // FIXME: Builtin::BI__builtin_powif
  12191. // FIXME: Builtin::BI__builtin_powil
  12192. case Builtin::BI__builtin_copysign:
  12193. case Builtin::BI__builtin_copysignf:
  12194. case Builtin::BI__builtin_copysignl:
  12195. case Builtin::BI__builtin_copysignf128: {
  12196. APFloat RHS(0.);
  12197. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  12198. !EvaluateFloat(E->getArg(1), RHS, Info))
  12199. return false;
  12200. Result.copySign(RHS);
  12201. return true;
  12202. }
  12203. }
  12204. }
  12205. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  12206. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  12207. ComplexValue CV;
  12208. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  12209. return false;
  12210. Result = CV.FloatReal;
  12211. return true;
  12212. }
  12213. return Visit(E->getSubExpr());
  12214. }
  12215. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  12216. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  12217. ComplexValue CV;
  12218. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  12219. return false;
  12220. Result = CV.FloatImag;
  12221. return true;
  12222. }
  12223. VisitIgnoredValue(E->getSubExpr());
  12224. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  12225. Result = llvm::APFloat::getZero(Sem);
  12226. return true;
  12227. }
  12228. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  12229. switch (E->getOpcode()) {
  12230. default: return Error(E);
  12231. case UO_Plus:
  12232. return EvaluateFloat(E->getSubExpr(), Result, Info);
  12233. case UO_Minus:
  12234. // In C standard, WG14 N2478 F.3 p4
  12235. // "the unary - raises no floating point exceptions,
  12236. // even if the operand is signalling."
  12237. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  12238. return false;
  12239. Result.changeSign();
  12240. return true;
  12241. }
  12242. }
  12243. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  12244. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  12245. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  12246. APFloat RHS(0.0);
  12247. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  12248. if (!LHSOK && !Info.noteFailure())
  12249. return false;
  12250. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  12251. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  12252. }
  12253. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  12254. Result = E->getValue();
  12255. return true;
  12256. }
  12257. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  12258. const Expr* SubExpr = E->getSubExpr();
  12259. switch (E->getCastKind()) {
  12260. default:
  12261. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12262. case CK_IntegralToFloating: {
  12263. APSInt IntResult;
  12264. const FPOptions FPO = E->getFPFeaturesInEffect(
  12265. Info.Ctx.getLangOpts());
  12266. return EvaluateInteger(SubExpr, IntResult, Info) &&
  12267. HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
  12268. IntResult, E->getType(), Result);
  12269. }
  12270. case CK_FixedPointToFloating: {
  12271. APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  12272. if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
  12273. return false;
  12274. Result =
  12275. FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
  12276. return true;
  12277. }
  12278. case CK_FloatingCast: {
  12279. if (!Visit(SubExpr))
  12280. return false;
  12281. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  12282. Result);
  12283. }
  12284. case CK_FloatingComplexToReal: {
  12285. ComplexValue V;
  12286. if (!EvaluateComplex(SubExpr, V, Info))
  12287. return false;
  12288. Result = V.getComplexFloatReal();
  12289. return true;
  12290. }
  12291. }
  12292. }
  12293. //===----------------------------------------------------------------------===//
  12294. // Complex Evaluation (for float and integer)
  12295. //===----------------------------------------------------------------------===//
  12296. namespace {
  12297. class ComplexExprEvaluator
  12298. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  12299. ComplexValue &Result;
  12300. public:
  12301. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  12302. : ExprEvaluatorBaseTy(info), Result(Result) {}
  12303. bool Success(const APValue &V, const Expr *e) {
  12304. Result.setFrom(V);
  12305. return true;
  12306. }
  12307. bool ZeroInitialization(const Expr *E);
  12308. //===--------------------------------------------------------------------===//
  12309. // Visitor Methods
  12310. //===--------------------------------------------------------------------===//
  12311. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  12312. bool VisitCastExpr(const CastExpr *E);
  12313. bool VisitBinaryOperator(const BinaryOperator *E);
  12314. bool VisitUnaryOperator(const UnaryOperator *E);
  12315. bool VisitInitListExpr(const InitListExpr *E);
  12316. bool VisitCallExpr(const CallExpr *E);
  12317. };
  12318. } // end anonymous namespace
  12319. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  12320. EvalInfo &Info) {
  12321. assert(!E->isValueDependent());
  12322. assert(E->isPRValue() && E->getType()->isAnyComplexType());
  12323. return ComplexExprEvaluator(Info, Result).Visit(E);
  12324. }
  12325. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  12326. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  12327. if (ElemTy->isRealFloatingType()) {
  12328. Result.makeComplexFloat();
  12329. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  12330. Result.FloatReal = Zero;
  12331. Result.FloatImag = Zero;
  12332. } else {
  12333. Result.makeComplexInt();
  12334. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  12335. Result.IntReal = Zero;
  12336. Result.IntImag = Zero;
  12337. }
  12338. return true;
  12339. }
  12340. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  12341. const Expr* SubExpr = E->getSubExpr();
  12342. if (SubExpr->getType()->isRealFloatingType()) {
  12343. Result.makeComplexFloat();
  12344. APFloat &Imag = Result.FloatImag;
  12345. if (!EvaluateFloat(SubExpr, Imag, Info))
  12346. return false;
  12347. Result.FloatReal = APFloat(Imag.getSemantics());
  12348. return true;
  12349. } else {
  12350. assert(SubExpr->getType()->isIntegerType() &&
  12351. "Unexpected imaginary literal.");
  12352. Result.makeComplexInt();
  12353. APSInt &Imag = Result.IntImag;
  12354. if (!EvaluateInteger(SubExpr, Imag, Info))
  12355. return false;
  12356. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  12357. return true;
  12358. }
  12359. }
  12360. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  12361. switch (E->getCastKind()) {
  12362. case CK_BitCast:
  12363. case CK_BaseToDerived:
  12364. case CK_DerivedToBase:
  12365. case CK_UncheckedDerivedToBase:
  12366. case CK_Dynamic:
  12367. case CK_ToUnion:
  12368. case CK_ArrayToPointerDecay:
  12369. case CK_FunctionToPointerDecay:
  12370. case CK_NullToPointer:
  12371. case CK_NullToMemberPointer:
  12372. case CK_BaseToDerivedMemberPointer:
  12373. case CK_DerivedToBaseMemberPointer:
  12374. case CK_MemberPointerToBoolean:
  12375. case CK_ReinterpretMemberPointer:
  12376. case CK_ConstructorConversion:
  12377. case CK_IntegralToPointer:
  12378. case CK_PointerToIntegral:
  12379. case CK_PointerToBoolean:
  12380. case CK_ToVoid:
  12381. case CK_VectorSplat:
  12382. case CK_IntegralCast:
  12383. case CK_BooleanToSignedIntegral:
  12384. case CK_IntegralToBoolean:
  12385. case CK_IntegralToFloating:
  12386. case CK_FloatingToIntegral:
  12387. case CK_FloatingToBoolean:
  12388. case CK_FloatingCast:
  12389. case CK_CPointerToObjCPointerCast:
  12390. case CK_BlockPointerToObjCPointerCast:
  12391. case CK_AnyPointerToBlockPointerCast:
  12392. case CK_ObjCObjectLValueCast:
  12393. case CK_FloatingComplexToReal:
  12394. case CK_FloatingComplexToBoolean:
  12395. case CK_IntegralComplexToReal:
  12396. case CK_IntegralComplexToBoolean:
  12397. case CK_ARCProduceObject:
  12398. case CK_ARCConsumeObject:
  12399. case CK_ARCReclaimReturnedObject:
  12400. case CK_ARCExtendBlockObject:
  12401. case CK_CopyAndAutoreleaseBlockObject:
  12402. case CK_BuiltinFnToFnPtr:
  12403. case CK_ZeroToOCLOpaqueType:
  12404. case CK_NonAtomicToAtomic:
  12405. case CK_AddressSpaceConversion:
  12406. case CK_IntToOCLSampler:
  12407. case CK_FloatingToFixedPoint:
  12408. case CK_FixedPointToFloating:
  12409. case CK_FixedPointCast:
  12410. case CK_FixedPointToBoolean:
  12411. case CK_FixedPointToIntegral:
  12412. case CK_IntegralToFixedPoint:
  12413. case CK_MatrixCast:
  12414. llvm_unreachable("invalid cast kind for complex value");
  12415. case CK_LValueToRValue:
  12416. case CK_AtomicToNonAtomic:
  12417. case CK_NoOp:
  12418. case CK_LValueToRValueBitCast:
  12419. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12420. case CK_Dependent:
  12421. case CK_LValueBitCast:
  12422. case CK_UserDefinedConversion:
  12423. return Error(E);
  12424. case CK_FloatingRealToComplex: {
  12425. APFloat &Real = Result.FloatReal;
  12426. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  12427. return false;
  12428. Result.makeComplexFloat();
  12429. Result.FloatImag = APFloat(Real.getSemantics());
  12430. return true;
  12431. }
  12432. case CK_FloatingComplexCast: {
  12433. if (!Visit(E->getSubExpr()))
  12434. return false;
  12435. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12436. QualType From
  12437. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12438. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  12439. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  12440. }
  12441. case CK_FloatingComplexToIntegralComplex: {
  12442. if (!Visit(E->getSubExpr()))
  12443. return false;
  12444. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12445. QualType From
  12446. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12447. Result.makeComplexInt();
  12448. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  12449. To, Result.IntReal) &&
  12450. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  12451. To, Result.IntImag);
  12452. }
  12453. case CK_IntegralRealToComplex: {
  12454. APSInt &Real = Result.IntReal;
  12455. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  12456. return false;
  12457. Result.makeComplexInt();
  12458. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  12459. return true;
  12460. }
  12461. case CK_IntegralComplexCast: {
  12462. if (!Visit(E->getSubExpr()))
  12463. return false;
  12464. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12465. QualType From
  12466. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12467. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  12468. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  12469. return true;
  12470. }
  12471. case CK_IntegralComplexToFloatingComplex: {
  12472. if (!Visit(E->getSubExpr()))
  12473. return false;
  12474. const FPOptions FPO = E->getFPFeaturesInEffect(
  12475. Info.Ctx.getLangOpts());
  12476. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  12477. QualType From
  12478. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  12479. Result.makeComplexFloat();
  12480. return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
  12481. To, Result.FloatReal) &&
  12482. HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
  12483. To, Result.FloatImag);
  12484. }
  12485. }
  12486. llvm_unreachable("unknown cast resulting in complex value");
  12487. }
  12488. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  12489. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  12490. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  12491. // Track whether the LHS or RHS is real at the type system level. When this is
  12492. // the case we can simplify our evaluation strategy.
  12493. bool LHSReal = false, RHSReal = false;
  12494. bool LHSOK;
  12495. if (E->getLHS()->getType()->isRealFloatingType()) {
  12496. LHSReal = true;
  12497. APFloat &Real = Result.FloatReal;
  12498. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  12499. if (LHSOK) {
  12500. Result.makeComplexFloat();
  12501. Result.FloatImag = APFloat(Real.getSemantics());
  12502. }
  12503. } else {
  12504. LHSOK = Visit(E->getLHS());
  12505. }
  12506. if (!LHSOK && !Info.noteFailure())
  12507. return false;
  12508. ComplexValue RHS;
  12509. if (E->getRHS()->getType()->isRealFloatingType()) {
  12510. RHSReal = true;
  12511. APFloat &Real = RHS.FloatReal;
  12512. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  12513. return false;
  12514. RHS.makeComplexFloat();
  12515. RHS.FloatImag = APFloat(Real.getSemantics());
  12516. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  12517. return false;
  12518. assert(!(LHSReal && RHSReal) &&
  12519. "Cannot have both operands of a complex operation be real.");
  12520. switch (E->getOpcode()) {
  12521. default: return Error(E);
  12522. case BO_Add:
  12523. if (Result.isComplexFloat()) {
  12524. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  12525. APFloat::rmNearestTiesToEven);
  12526. if (LHSReal)
  12527. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  12528. else if (!RHSReal)
  12529. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  12530. APFloat::rmNearestTiesToEven);
  12531. } else {
  12532. Result.getComplexIntReal() += RHS.getComplexIntReal();
  12533. Result.getComplexIntImag() += RHS.getComplexIntImag();
  12534. }
  12535. break;
  12536. case BO_Sub:
  12537. if (Result.isComplexFloat()) {
  12538. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  12539. APFloat::rmNearestTiesToEven);
  12540. if (LHSReal) {
  12541. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  12542. Result.getComplexFloatImag().changeSign();
  12543. } else if (!RHSReal) {
  12544. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  12545. APFloat::rmNearestTiesToEven);
  12546. }
  12547. } else {
  12548. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  12549. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  12550. }
  12551. break;
  12552. case BO_Mul:
  12553. if (Result.isComplexFloat()) {
  12554. // This is an implementation of complex multiplication according to the
  12555. // constraints laid out in C11 Annex G. The implementation uses the
  12556. // following naming scheme:
  12557. // (a + ib) * (c + id)
  12558. ComplexValue LHS = Result;
  12559. APFloat &A = LHS.getComplexFloatReal();
  12560. APFloat &B = LHS.getComplexFloatImag();
  12561. APFloat &C = RHS.getComplexFloatReal();
  12562. APFloat &D = RHS.getComplexFloatImag();
  12563. APFloat &ResR = Result.getComplexFloatReal();
  12564. APFloat &ResI = Result.getComplexFloatImag();
  12565. if (LHSReal) {
  12566. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  12567. ResR = A * C;
  12568. ResI = A * D;
  12569. } else if (RHSReal) {
  12570. ResR = C * A;
  12571. ResI = C * B;
  12572. } else {
  12573. // In the fully general case, we need to handle NaNs and infinities
  12574. // robustly.
  12575. APFloat AC = A * C;
  12576. APFloat BD = B * D;
  12577. APFloat AD = A * D;
  12578. APFloat BC = B * C;
  12579. ResR = AC - BD;
  12580. ResI = AD + BC;
  12581. if (ResR.isNaN() && ResI.isNaN()) {
  12582. bool Recalc = false;
  12583. if (A.isInfinity() || B.isInfinity()) {
  12584. A = APFloat::copySign(
  12585. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  12586. B = APFloat::copySign(
  12587. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  12588. if (C.isNaN())
  12589. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  12590. if (D.isNaN())
  12591. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  12592. Recalc = true;
  12593. }
  12594. if (C.isInfinity() || D.isInfinity()) {
  12595. C = APFloat::copySign(
  12596. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  12597. D = APFloat::copySign(
  12598. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  12599. if (A.isNaN())
  12600. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  12601. if (B.isNaN())
  12602. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  12603. Recalc = true;
  12604. }
  12605. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  12606. AD.isInfinity() || BC.isInfinity())) {
  12607. if (A.isNaN())
  12608. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  12609. if (B.isNaN())
  12610. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  12611. if (C.isNaN())
  12612. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  12613. if (D.isNaN())
  12614. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  12615. Recalc = true;
  12616. }
  12617. if (Recalc) {
  12618. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  12619. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  12620. }
  12621. }
  12622. }
  12623. } else {
  12624. ComplexValue LHS = Result;
  12625. Result.getComplexIntReal() =
  12626. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  12627. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  12628. Result.getComplexIntImag() =
  12629. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  12630. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  12631. }
  12632. break;
  12633. case BO_Div:
  12634. if (Result.isComplexFloat()) {
  12635. // This is an implementation of complex division according to the
  12636. // constraints laid out in C11 Annex G. The implementation uses the
  12637. // following naming scheme:
  12638. // (a + ib) / (c + id)
  12639. ComplexValue LHS = Result;
  12640. APFloat &A = LHS.getComplexFloatReal();
  12641. APFloat &B = LHS.getComplexFloatImag();
  12642. APFloat &C = RHS.getComplexFloatReal();
  12643. APFloat &D = RHS.getComplexFloatImag();
  12644. APFloat &ResR = Result.getComplexFloatReal();
  12645. APFloat &ResI = Result.getComplexFloatImag();
  12646. if (RHSReal) {
  12647. ResR = A / C;
  12648. ResI = B / C;
  12649. } else {
  12650. if (LHSReal) {
  12651. // No real optimizations we can do here, stub out with zero.
  12652. B = APFloat::getZero(A.getSemantics());
  12653. }
  12654. int DenomLogB = 0;
  12655. APFloat MaxCD = maxnum(abs(C), abs(D));
  12656. if (MaxCD.isFinite()) {
  12657. DenomLogB = ilogb(MaxCD);
  12658. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  12659. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  12660. }
  12661. APFloat Denom = C * C + D * D;
  12662. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  12663. APFloat::rmNearestTiesToEven);
  12664. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  12665. APFloat::rmNearestTiesToEven);
  12666. if (ResR.isNaN() && ResI.isNaN()) {
  12667. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  12668. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  12669. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  12670. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  12671. D.isFinite()) {
  12672. A = APFloat::copySign(
  12673. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  12674. B = APFloat::copySign(
  12675. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  12676. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  12677. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  12678. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  12679. C = APFloat::copySign(
  12680. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  12681. D = APFloat::copySign(
  12682. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  12683. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  12684. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  12685. }
  12686. }
  12687. }
  12688. } else {
  12689. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  12690. return Error(E, diag::note_expr_divide_by_zero);
  12691. ComplexValue LHS = Result;
  12692. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  12693. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  12694. Result.getComplexIntReal() =
  12695. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  12696. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  12697. Result.getComplexIntImag() =
  12698. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  12699. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  12700. }
  12701. break;
  12702. }
  12703. return true;
  12704. }
  12705. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  12706. // Get the operand value into 'Result'.
  12707. if (!Visit(E->getSubExpr()))
  12708. return false;
  12709. switch (E->getOpcode()) {
  12710. default:
  12711. return Error(E);
  12712. case UO_Extension:
  12713. return true;
  12714. case UO_Plus:
  12715. // The result is always just the subexpr.
  12716. return true;
  12717. case UO_Minus:
  12718. if (Result.isComplexFloat()) {
  12719. Result.getComplexFloatReal().changeSign();
  12720. Result.getComplexFloatImag().changeSign();
  12721. }
  12722. else {
  12723. Result.getComplexIntReal() = -Result.getComplexIntReal();
  12724. Result.getComplexIntImag() = -Result.getComplexIntImag();
  12725. }
  12726. return true;
  12727. case UO_Not:
  12728. if (Result.isComplexFloat())
  12729. Result.getComplexFloatImag().changeSign();
  12730. else
  12731. Result.getComplexIntImag() = -Result.getComplexIntImag();
  12732. return true;
  12733. }
  12734. }
  12735. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  12736. if (E->getNumInits() == 2) {
  12737. if (E->getType()->isComplexType()) {
  12738. Result.makeComplexFloat();
  12739. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  12740. return false;
  12741. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  12742. return false;
  12743. } else {
  12744. Result.makeComplexInt();
  12745. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  12746. return false;
  12747. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  12748. return false;
  12749. }
  12750. return true;
  12751. }
  12752. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  12753. }
  12754. bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
  12755. switch (E->getBuiltinCallee()) {
  12756. case Builtin::BI__builtin_complex:
  12757. Result.makeComplexFloat();
  12758. if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
  12759. return false;
  12760. if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
  12761. return false;
  12762. return true;
  12763. default:
  12764. break;
  12765. }
  12766. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  12767. }
  12768. //===----------------------------------------------------------------------===//
  12769. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  12770. // implicit conversion.
  12771. //===----------------------------------------------------------------------===//
  12772. namespace {
  12773. class AtomicExprEvaluator :
  12774. public ExprEvaluatorBase<AtomicExprEvaluator> {
  12775. const LValue *This;
  12776. APValue &Result;
  12777. public:
  12778. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  12779. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  12780. bool Success(const APValue &V, const Expr *E) {
  12781. Result = V;
  12782. return true;
  12783. }
  12784. bool ZeroInitialization(const Expr *E) {
  12785. ImplicitValueInitExpr VIE(
  12786. E->getType()->castAs<AtomicType>()->getValueType());
  12787. // For atomic-qualified class (and array) types in C++, initialize the
  12788. // _Atomic-wrapped subobject directly, in-place.
  12789. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  12790. : Evaluate(Result, Info, &VIE);
  12791. }
  12792. bool VisitCastExpr(const CastExpr *E) {
  12793. switch (E->getCastKind()) {
  12794. default:
  12795. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12796. case CK_NonAtomicToAtomic:
  12797. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  12798. : Evaluate(Result, Info, E->getSubExpr());
  12799. }
  12800. }
  12801. };
  12802. } // end anonymous namespace
  12803. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  12804. EvalInfo &Info) {
  12805. assert(!E->isValueDependent());
  12806. assert(E->isPRValue() && E->getType()->isAtomicType());
  12807. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  12808. }
  12809. //===----------------------------------------------------------------------===//
  12810. // Void expression evaluation, primarily for a cast to void on the LHS of a
  12811. // comma operator
  12812. //===----------------------------------------------------------------------===//
  12813. namespace {
  12814. class VoidExprEvaluator
  12815. : public ExprEvaluatorBase<VoidExprEvaluator> {
  12816. public:
  12817. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  12818. bool Success(const APValue &V, const Expr *e) { return true; }
  12819. bool ZeroInitialization(const Expr *E) { return true; }
  12820. bool VisitCastExpr(const CastExpr *E) {
  12821. switch (E->getCastKind()) {
  12822. default:
  12823. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  12824. case CK_ToVoid:
  12825. VisitIgnoredValue(E->getSubExpr());
  12826. return true;
  12827. }
  12828. }
  12829. bool VisitCallExpr(const CallExpr *E) {
  12830. switch (E->getBuiltinCallee()) {
  12831. case Builtin::BI__assume:
  12832. case Builtin::BI__builtin_assume:
  12833. // The argument is not evaluated!
  12834. return true;
  12835. case Builtin::BI__builtin_operator_delete:
  12836. return HandleOperatorDeleteCall(Info, E);
  12837. default:
  12838. break;
  12839. }
  12840. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  12841. }
  12842. bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
  12843. };
  12844. } // end anonymous namespace
  12845. bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
  12846. // We cannot speculatively evaluate a delete expression.
  12847. if (Info.SpeculativeEvaluationDepth)
  12848. return false;
  12849. FunctionDecl *OperatorDelete = E->getOperatorDelete();
  12850. if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
  12851. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  12852. << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
  12853. return false;
  12854. }
  12855. const Expr *Arg = E->getArgument();
  12856. LValue Pointer;
  12857. if (!EvaluatePointer(Arg, Pointer, Info))
  12858. return false;
  12859. if (Pointer.Designator.Invalid)
  12860. return false;
  12861. // Deleting a null pointer has no effect.
  12862. if (Pointer.isNullPointer()) {
  12863. // This is the only case where we need to produce an extension warning:
  12864. // the only other way we can succeed is if we find a dynamic allocation,
  12865. // and we will have warned when we allocated it in that case.
  12866. if (!Info.getLangOpts().CPlusPlus20)
  12867. Info.CCEDiag(E, diag::note_constexpr_new);
  12868. return true;
  12869. }
  12870. Optional<DynAlloc *> Alloc = CheckDeleteKind(
  12871. Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
  12872. if (!Alloc)
  12873. return false;
  12874. QualType AllocType = Pointer.Base.getDynamicAllocType();
  12875. // For the non-array case, the designator must be empty if the static type
  12876. // does not have a virtual destructor.
  12877. if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
  12878. !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
  12879. Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
  12880. << Arg->getType()->getPointeeType() << AllocType;
  12881. return false;
  12882. }
  12883. // For a class type with a virtual destructor, the selected operator delete
  12884. // is the one looked up when building the destructor.
  12885. if (!E->isArrayForm() && !E->isGlobalDelete()) {
  12886. const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
  12887. if (VirtualDelete &&
  12888. !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
  12889. Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
  12890. << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
  12891. return false;
  12892. }
  12893. }
  12894. if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
  12895. (*Alloc)->Value, AllocType))
  12896. return false;
  12897. if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
  12898. // The element was already erased. This means the destructor call also
  12899. // deleted the object.
  12900. // FIXME: This probably results in undefined behavior before we get this
  12901. // far, and should be diagnosed elsewhere first.
  12902. Info.FFDiag(E, diag::note_constexpr_double_delete);
  12903. return false;
  12904. }
  12905. return true;
  12906. }
  12907. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  12908. assert(!E->isValueDependent());
  12909. assert(E->isPRValue() && E->getType()->isVoidType());
  12910. return VoidExprEvaluator(Info).Visit(E);
  12911. }
  12912. //===----------------------------------------------------------------------===//
  12913. // Top level Expr::EvaluateAsRValue method.
  12914. //===----------------------------------------------------------------------===//
  12915. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  12916. assert(!E->isValueDependent());
  12917. // In C, function designators are not lvalues, but we evaluate them as if they
  12918. // are.
  12919. QualType T = E->getType();
  12920. if (E->isGLValue() || T->isFunctionType()) {
  12921. LValue LV;
  12922. if (!EvaluateLValue(E, LV, Info))
  12923. return false;
  12924. LV.moveInto(Result);
  12925. } else if (T->isVectorType()) {
  12926. if (!EvaluateVector(E, Result, Info))
  12927. return false;
  12928. } else if (T->isIntegralOrEnumerationType()) {
  12929. if (!IntExprEvaluator(Info, Result).Visit(E))
  12930. return false;
  12931. } else if (T->hasPointerRepresentation()) {
  12932. LValue LV;
  12933. if (!EvaluatePointer(E, LV, Info))
  12934. return false;
  12935. LV.moveInto(Result);
  12936. } else if (T->isRealFloatingType()) {
  12937. llvm::APFloat F(0.0);
  12938. if (!EvaluateFloat(E, F, Info))
  12939. return false;
  12940. Result = APValue(F);
  12941. } else if (T->isAnyComplexType()) {
  12942. ComplexValue C;
  12943. if (!EvaluateComplex(E, C, Info))
  12944. return false;
  12945. C.moveInto(Result);
  12946. } else if (T->isFixedPointType()) {
  12947. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  12948. } else if (T->isMemberPointerType()) {
  12949. MemberPtr P;
  12950. if (!EvaluateMemberPointer(E, P, Info))
  12951. return false;
  12952. P.moveInto(Result);
  12953. return true;
  12954. } else if (T->isArrayType()) {
  12955. LValue LV;
  12956. APValue &Value =
  12957. Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
  12958. if (!EvaluateArray(E, LV, Value, Info))
  12959. return false;
  12960. Result = Value;
  12961. } else if (T->isRecordType()) {
  12962. LValue LV;
  12963. APValue &Value =
  12964. Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
  12965. if (!EvaluateRecord(E, LV, Value, Info))
  12966. return false;
  12967. Result = Value;
  12968. } else if (T->isVoidType()) {
  12969. if (!Info.getLangOpts().CPlusPlus11)
  12970. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  12971. << E->getType();
  12972. if (!EvaluateVoid(E, Info))
  12973. return false;
  12974. } else if (T->isAtomicType()) {
  12975. QualType Unqual = T.getAtomicUnqualifiedType();
  12976. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  12977. LValue LV;
  12978. APValue &Value = Info.CurrentCall->createTemporary(
  12979. E, Unqual, ScopeKind::FullExpression, LV);
  12980. if (!EvaluateAtomic(E, &LV, Value, Info))
  12981. return false;
  12982. } else {
  12983. if (!EvaluateAtomic(E, nullptr, Result, Info))
  12984. return false;
  12985. }
  12986. } else if (Info.getLangOpts().CPlusPlus11) {
  12987. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  12988. return false;
  12989. } else {
  12990. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  12991. return false;
  12992. }
  12993. return true;
  12994. }
  12995. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  12996. /// cases, the in-place evaluation is essential, since later initializers for
  12997. /// an object can indirectly refer to subobjects which were initialized earlier.
  12998. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  12999. const Expr *E, bool AllowNonLiteralTypes) {
  13000. assert(!E->isValueDependent());
  13001. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  13002. return false;
  13003. if (E->isPRValue()) {
  13004. // Evaluate arrays and record types in-place, so that later initializers can
  13005. // refer to earlier-initialized members of the object.
  13006. QualType T = E->getType();
  13007. if (T->isArrayType())
  13008. return EvaluateArray(E, This, Result, Info);
  13009. else if (T->isRecordType())
  13010. return EvaluateRecord(E, This, Result, Info);
  13011. else if (T->isAtomicType()) {
  13012. QualType Unqual = T.getAtomicUnqualifiedType();
  13013. if (Unqual->isArrayType() || Unqual->isRecordType())
  13014. return EvaluateAtomic(E, &This, Result, Info);
  13015. }
  13016. }
  13017. // For any other type, in-place evaluation is unimportant.
  13018. return Evaluate(Result, Info, E);
  13019. }
  13020. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  13021. /// lvalue-to-rvalue cast if it is an lvalue.
  13022. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  13023. assert(!E->isValueDependent());
  13024. if (Info.EnableNewConstInterp) {
  13025. if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
  13026. return false;
  13027. } else {
  13028. if (E->getType().isNull())
  13029. return false;
  13030. if (!CheckLiteralType(Info, E))
  13031. return false;
  13032. if (!::Evaluate(Result, Info, E))
  13033. return false;
  13034. if (E->isGLValue()) {
  13035. LValue LV;
  13036. LV.setFrom(Info.Ctx, Result);
  13037. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  13038. return false;
  13039. }
  13040. }
  13041. // Check this core constant expression is a constant expression.
  13042. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
  13043. ConstantExprKind::Normal) &&
  13044. CheckMemoryLeaks(Info);
  13045. }
  13046. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  13047. const ASTContext &Ctx, bool &IsConst) {
  13048. // Fast-path evaluations of integer literals, since we sometimes see files
  13049. // containing vast quantities of these.
  13050. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  13051. Result.Val = APValue(APSInt(L->getValue(),
  13052. L->getType()->isUnsignedIntegerType()));
  13053. IsConst = true;
  13054. return true;
  13055. }
  13056. // This case should be rare, but we need to check it before we check on
  13057. // the type below.
  13058. if (Exp->getType().isNull()) {
  13059. IsConst = false;
  13060. return true;
  13061. }
  13062. // FIXME: Evaluating values of large array and record types can cause
  13063. // performance problems. Only do so in C++11 for now.
  13064. if (Exp->isPRValue() &&
  13065. (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
  13066. !Ctx.getLangOpts().CPlusPlus11) {
  13067. IsConst = false;
  13068. return true;
  13069. }
  13070. return false;
  13071. }
  13072. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  13073. Expr::SideEffectsKind SEK) {
  13074. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  13075. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  13076. }
  13077. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  13078. const ASTContext &Ctx, EvalInfo &Info) {
  13079. assert(!E->isValueDependent());
  13080. bool IsConst;
  13081. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  13082. return IsConst;
  13083. return EvaluateAsRValue(Info, E, Result.Val);
  13084. }
  13085. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  13086. const ASTContext &Ctx,
  13087. Expr::SideEffectsKind AllowSideEffects,
  13088. EvalInfo &Info) {
  13089. assert(!E->isValueDependent());
  13090. if (!E->getType()->isIntegralOrEnumerationType())
  13091. return false;
  13092. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  13093. !ExprResult.Val.isInt() ||
  13094. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  13095. return false;
  13096. return true;
  13097. }
  13098. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  13099. const ASTContext &Ctx,
  13100. Expr::SideEffectsKind AllowSideEffects,
  13101. EvalInfo &Info) {
  13102. assert(!E->isValueDependent());
  13103. if (!E->getType()->isFixedPointType())
  13104. return false;
  13105. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  13106. return false;
  13107. if (!ExprResult.Val.isFixedPoint() ||
  13108. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  13109. return false;
  13110. return true;
  13111. }
  13112. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  13113. /// any crazy technique (that has nothing to do with language standards) that
  13114. /// we want to. If this function returns true, it returns the folded constant
  13115. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  13116. /// will be applied to the result.
  13117. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  13118. bool InConstantContext) const {
  13119. assert(!isValueDependent() &&
  13120. "Expression evaluator can't be called on a dependent expression.");
  13121. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  13122. Info.InConstantContext = InConstantContext;
  13123. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  13124. }
  13125. bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
  13126. bool InConstantContext) const {
  13127. assert(!isValueDependent() &&
  13128. "Expression evaluator can't be called on a dependent expression.");
  13129. EvalResult Scratch;
  13130. return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
  13131. HandleConversionToBool(Scratch.Val, Result);
  13132. }
  13133. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  13134. SideEffectsKind AllowSideEffects,
  13135. bool InConstantContext) const {
  13136. assert(!isValueDependent() &&
  13137. "Expression evaluator can't be called on a dependent expression.");
  13138. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  13139. Info.InConstantContext = InConstantContext;
  13140. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  13141. }
  13142. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  13143. SideEffectsKind AllowSideEffects,
  13144. bool InConstantContext) const {
  13145. assert(!isValueDependent() &&
  13146. "Expression evaluator can't be called on a dependent expression.");
  13147. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  13148. Info.InConstantContext = InConstantContext;
  13149. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  13150. }
  13151. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  13152. SideEffectsKind AllowSideEffects,
  13153. bool InConstantContext) const {
  13154. assert(!isValueDependent() &&
  13155. "Expression evaluator can't be called on a dependent expression.");
  13156. if (!getType()->isRealFloatingType())
  13157. return false;
  13158. EvalResult ExprResult;
  13159. if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
  13160. !ExprResult.Val.isFloat() ||
  13161. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  13162. return false;
  13163. Result = ExprResult.Val.getFloat();
  13164. return true;
  13165. }
  13166. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
  13167. bool InConstantContext) const {
  13168. assert(!isValueDependent() &&
  13169. "Expression evaluator can't be called on a dependent expression.");
  13170. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  13171. Info.InConstantContext = InConstantContext;
  13172. LValue LV;
  13173. CheckedTemporaries CheckedTemps;
  13174. if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
  13175. Result.HasSideEffects ||
  13176. !CheckLValueConstantExpression(Info, getExprLoc(),
  13177. Ctx.getLValueReferenceType(getType()), LV,
  13178. ConstantExprKind::Normal, CheckedTemps))
  13179. return false;
  13180. LV.moveInto(Result.Val);
  13181. return true;
  13182. }
  13183. static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
  13184. APValue DestroyedValue, QualType Type,
  13185. SourceLocation Loc, Expr::EvalStatus &EStatus,
  13186. bool IsConstantDestruction) {
  13187. EvalInfo Info(Ctx, EStatus,
  13188. IsConstantDestruction ? EvalInfo::EM_ConstantExpression
  13189. : EvalInfo::EM_ConstantFold);
  13190. Info.setEvaluatingDecl(Base, DestroyedValue,
  13191. EvalInfo::EvaluatingDeclKind::Dtor);
  13192. Info.InConstantContext = IsConstantDestruction;
  13193. LValue LVal;
  13194. LVal.set(Base);
  13195. if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
  13196. EStatus.HasSideEffects)
  13197. return false;
  13198. if (!Info.discardCleanups())
  13199. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  13200. return true;
  13201. }
  13202. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
  13203. ConstantExprKind Kind) const {
  13204. assert(!isValueDependent() &&
  13205. "Expression evaluator can't be called on a dependent expression.");
  13206. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  13207. EvalInfo Info(Ctx, Result, EM);
  13208. Info.InConstantContext = true;
  13209. // The type of the object we're initializing is 'const T' for a class NTTP.
  13210. QualType T = getType();
  13211. if (Kind == ConstantExprKind::ClassTemplateArgument)
  13212. T.addConst();
  13213. // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
  13214. // represent the result of the evaluation. CheckConstantExpression ensures
  13215. // this doesn't escape.
  13216. MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
  13217. APValue::LValueBase Base(&BaseMTE);
  13218. Info.setEvaluatingDecl(Base, Result.Val);
  13219. LValue LVal;
  13220. LVal.set(Base);
  13221. if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
  13222. return false;
  13223. if (!Info.discardCleanups())
  13224. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  13225. if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
  13226. Result.Val, Kind))
  13227. return false;
  13228. if (!CheckMemoryLeaks(Info))
  13229. return false;
  13230. // If this is a class template argument, it's required to have constant
  13231. // destruction too.
  13232. if (Kind == ConstantExprKind::ClassTemplateArgument &&
  13233. (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
  13234. true) ||
  13235. Result.HasSideEffects)) {
  13236. // FIXME: Prefix a note to indicate that the problem is lack of constant
  13237. // destruction.
  13238. return false;
  13239. }
  13240. return true;
  13241. }
  13242. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  13243. const VarDecl *VD,
  13244. SmallVectorImpl<PartialDiagnosticAt> &Notes,
  13245. bool IsConstantInitialization) const {
  13246. assert(!isValueDependent() &&
  13247. "Expression evaluator can't be called on a dependent expression.");
  13248. // FIXME: Evaluating initializers for large array and record types can cause
  13249. // performance problems. Only do so in C++11 for now.
  13250. if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  13251. !Ctx.getLangOpts().CPlusPlus11)
  13252. return false;
  13253. Expr::EvalStatus EStatus;
  13254. EStatus.Diag = &Notes;
  13255. EvalInfo Info(Ctx, EStatus,
  13256. (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
  13257. ? EvalInfo::EM_ConstantExpression
  13258. : EvalInfo::EM_ConstantFold);
  13259. Info.setEvaluatingDecl(VD, Value);
  13260. Info.InConstantContext = IsConstantInitialization;
  13261. SourceLocation DeclLoc = VD->getLocation();
  13262. QualType DeclTy = VD->getType();
  13263. if (Info.EnableNewConstInterp) {
  13264. auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
  13265. if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
  13266. return false;
  13267. } else {
  13268. LValue LVal;
  13269. LVal.set(VD);
  13270. if (!EvaluateInPlace(Value, Info, LVal, this,
  13271. /*AllowNonLiteralTypes=*/true) ||
  13272. EStatus.HasSideEffects)
  13273. return false;
  13274. // At this point, any lifetime-extended temporaries are completely
  13275. // initialized.
  13276. Info.performLifetimeExtension();
  13277. if (!Info.discardCleanups())
  13278. llvm_unreachable("Unhandled cleanup; missing full expression marker?");
  13279. }
  13280. return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
  13281. ConstantExprKind::Normal) &&
  13282. CheckMemoryLeaks(Info);
  13283. }
  13284. bool VarDecl::evaluateDestruction(
  13285. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  13286. Expr::EvalStatus EStatus;
  13287. EStatus.Diag = &Notes;
  13288. // Only treat the destruction as constant destruction if we formally have
  13289. // constant initialization (or are usable in a constant expression).
  13290. bool IsConstantDestruction = hasConstantInitialization();
  13291. // Make a copy of the value for the destructor to mutate, if we know it.
  13292. // Otherwise, treat the value as default-initialized; if the destructor works
  13293. // anyway, then the destruction is constant (and must be essentially empty).
  13294. APValue DestroyedValue;
  13295. if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
  13296. DestroyedValue = *getEvaluatedValue();
  13297. else if (!getDefaultInitValue(getType(), DestroyedValue))
  13298. return false;
  13299. if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
  13300. getType(), getLocation(), EStatus,
  13301. IsConstantDestruction) ||
  13302. EStatus.HasSideEffects)
  13303. return false;
  13304. ensureEvaluatedStmt()->HasConstantDestruction = true;
  13305. return true;
  13306. }
  13307. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  13308. /// constant folded, but discard the result.
  13309. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  13310. assert(!isValueDependent() &&
  13311. "Expression evaluator can't be called on a dependent expression.");
  13312. EvalResult Result;
  13313. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  13314. !hasUnacceptableSideEffect(Result, SEK);
  13315. }
  13316. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  13317. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  13318. assert(!isValueDependent() &&
  13319. "Expression evaluator can't be called on a dependent expression.");
  13320. EvalResult EVResult;
  13321. EVResult.Diag = Diag;
  13322. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  13323. Info.InConstantContext = true;
  13324. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  13325. (void)Result;
  13326. assert(Result && "Could not evaluate expression");
  13327. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  13328. return EVResult.Val.getInt();
  13329. }
  13330. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  13331. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  13332. assert(!isValueDependent() &&
  13333. "Expression evaluator can't be called on a dependent expression.");
  13334. EvalResult EVResult;
  13335. EVResult.Diag = Diag;
  13336. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  13337. Info.InConstantContext = true;
  13338. Info.CheckingForUndefinedBehavior = true;
  13339. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  13340. (void)Result;
  13341. assert(Result && "Could not evaluate expression");
  13342. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  13343. return EVResult.Val.getInt();
  13344. }
  13345. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  13346. assert(!isValueDependent() &&
  13347. "Expression evaluator can't be called on a dependent expression.");
  13348. bool IsConst;
  13349. EvalResult EVResult;
  13350. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  13351. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  13352. Info.CheckingForUndefinedBehavior = true;
  13353. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  13354. }
  13355. }
  13356. bool Expr::EvalResult::isGlobalLValue() const {
  13357. assert(Val.isLValue());
  13358. return IsGlobalLValue(Val.getLValueBase());
  13359. }
  13360. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  13361. /// an integer constant expression.
  13362. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  13363. /// comma, etc
  13364. // CheckICE - This function does the fundamental ICE checking: the returned
  13365. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  13366. // and a (possibly null) SourceLocation indicating the location of the problem.
  13367. //
  13368. // Note that to reduce code duplication, this helper does no evaluation
  13369. // itself; the caller checks whether the expression is evaluatable, and
  13370. // in the rare cases where CheckICE actually cares about the evaluated
  13371. // value, it calls into Evaluate.
  13372. namespace {
  13373. enum ICEKind {
  13374. /// This expression is an ICE.
  13375. IK_ICE,
  13376. /// This expression is not an ICE, but if it isn't evaluated, it's
  13377. /// a legal subexpression for an ICE. This return value is used to handle
  13378. /// the comma operator in C99 mode, and non-constant subexpressions.
  13379. IK_ICEIfUnevaluated,
  13380. /// This expression is not an ICE, and is not a legal subexpression for one.
  13381. IK_NotICE
  13382. };
  13383. struct ICEDiag {
  13384. ICEKind Kind;
  13385. SourceLocation Loc;
  13386. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  13387. };
  13388. }
  13389. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  13390. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  13391. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  13392. Expr::EvalResult EVResult;
  13393. Expr::EvalStatus Status;
  13394. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  13395. Info.InConstantContext = true;
  13396. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  13397. !EVResult.Val.isInt())
  13398. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13399. return NoDiag();
  13400. }
  13401. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  13402. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  13403. if (!E->getType()->isIntegralOrEnumerationType())
  13404. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13405. switch (E->getStmtClass()) {
  13406. #define ABSTRACT_STMT(Node)
  13407. #define STMT(Node, Base) case Expr::Node##Class:
  13408. #define EXPR(Node, Base)
  13409. #include "clang/AST/StmtNodes.inc"
  13410. case Expr::PredefinedExprClass:
  13411. case Expr::FloatingLiteralClass:
  13412. case Expr::ImaginaryLiteralClass:
  13413. case Expr::StringLiteralClass:
  13414. case Expr::ArraySubscriptExprClass:
  13415. case Expr::MatrixSubscriptExprClass:
  13416. case Expr::OMPArraySectionExprClass:
  13417. case Expr::OMPArrayShapingExprClass:
  13418. case Expr::OMPIteratorExprClass:
  13419. case Expr::MemberExprClass:
  13420. case Expr::CompoundAssignOperatorClass:
  13421. case Expr::CompoundLiteralExprClass:
  13422. case Expr::ExtVectorElementExprClass:
  13423. case Expr::DesignatedInitExprClass:
  13424. case Expr::ArrayInitLoopExprClass:
  13425. case Expr::ArrayInitIndexExprClass:
  13426. case Expr::NoInitExprClass:
  13427. case Expr::DesignatedInitUpdateExprClass:
  13428. case Expr::ImplicitValueInitExprClass:
  13429. case Expr::ParenListExprClass:
  13430. case Expr::VAArgExprClass:
  13431. case Expr::AddrLabelExprClass:
  13432. case Expr::StmtExprClass:
  13433. case Expr::CXXMemberCallExprClass:
  13434. case Expr::CUDAKernelCallExprClass:
  13435. case Expr::CXXAddrspaceCastExprClass:
  13436. case Expr::CXXDynamicCastExprClass:
  13437. case Expr::CXXTypeidExprClass:
  13438. case Expr::CXXUuidofExprClass:
  13439. case Expr::MSPropertyRefExprClass:
  13440. case Expr::MSPropertySubscriptExprClass:
  13441. case Expr::CXXNullPtrLiteralExprClass:
  13442. case Expr::UserDefinedLiteralClass:
  13443. case Expr::CXXThisExprClass:
  13444. case Expr::CXXThrowExprClass:
  13445. case Expr::CXXNewExprClass:
  13446. case Expr::CXXDeleteExprClass:
  13447. case Expr::CXXPseudoDestructorExprClass:
  13448. case Expr::UnresolvedLookupExprClass:
  13449. case Expr::TypoExprClass:
  13450. case Expr::RecoveryExprClass:
  13451. case Expr::DependentScopeDeclRefExprClass:
  13452. case Expr::CXXConstructExprClass:
  13453. case Expr::CXXInheritedCtorInitExprClass:
  13454. case Expr::CXXStdInitializerListExprClass:
  13455. case Expr::CXXBindTemporaryExprClass:
  13456. case Expr::ExprWithCleanupsClass:
  13457. case Expr::CXXTemporaryObjectExprClass:
  13458. case Expr::CXXUnresolvedConstructExprClass:
  13459. case Expr::CXXDependentScopeMemberExprClass:
  13460. case Expr::UnresolvedMemberExprClass:
  13461. case Expr::ObjCStringLiteralClass:
  13462. case Expr::ObjCBoxedExprClass:
  13463. case Expr::ObjCArrayLiteralClass:
  13464. case Expr::ObjCDictionaryLiteralClass:
  13465. case Expr::ObjCEncodeExprClass:
  13466. case Expr::ObjCMessageExprClass:
  13467. case Expr::ObjCSelectorExprClass:
  13468. case Expr::ObjCProtocolExprClass:
  13469. case Expr::ObjCIvarRefExprClass:
  13470. case Expr::ObjCPropertyRefExprClass:
  13471. case Expr::ObjCSubscriptRefExprClass:
  13472. case Expr::ObjCIsaExprClass:
  13473. case Expr::ObjCAvailabilityCheckExprClass:
  13474. case Expr::ShuffleVectorExprClass:
  13475. case Expr::ConvertVectorExprClass:
  13476. case Expr::BlockExprClass:
  13477. case Expr::NoStmtClass:
  13478. case Expr::OpaqueValueExprClass:
  13479. case Expr::PackExpansionExprClass:
  13480. case Expr::SubstNonTypeTemplateParmPackExprClass:
  13481. case Expr::FunctionParmPackExprClass:
  13482. case Expr::AsTypeExprClass:
  13483. case Expr::ObjCIndirectCopyRestoreExprClass:
  13484. case Expr::MaterializeTemporaryExprClass:
  13485. case Expr::PseudoObjectExprClass:
  13486. case Expr::AtomicExprClass:
  13487. case Expr::LambdaExprClass:
  13488. case Expr::CXXFoldExprClass:
  13489. case Expr::CoawaitExprClass:
  13490. case Expr::DependentCoawaitExprClass:
  13491. case Expr::CoyieldExprClass:
  13492. case Expr::SYCLUniqueStableNameExprClass:
  13493. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13494. case Expr::InitListExprClass: {
  13495. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  13496. // form "T x = { a };" is equivalent to "T x = a;".
  13497. // Unless we're initializing a reference, T is a scalar as it is known to be
  13498. // of integral or enumeration type.
  13499. if (E->isPRValue())
  13500. if (cast<InitListExpr>(E)->getNumInits() == 1)
  13501. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  13502. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13503. }
  13504. case Expr::SizeOfPackExprClass:
  13505. case Expr::GNUNullExprClass:
  13506. case Expr::SourceLocExprClass:
  13507. return NoDiag();
  13508. case Expr::SubstNonTypeTemplateParmExprClass:
  13509. return
  13510. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  13511. case Expr::ConstantExprClass:
  13512. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  13513. case Expr::ParenExprClass:
  13514. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  13515. case Expr::GenericSelectionExprClass:
  13516. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  13517. case Expr::IntegerLiteralClass:
  13518. case Expr::FixedPointLiteralClass:
  13519. case Expr::CharacterLiteralClass:
  13520. case Expr::ObjCBoolLiteralExprClass:
  13521. case Expr::CXXBoolLiteralExprClass:
  13522. case Expr::CXXScalarValueInitExprClass:
  13523. case Expr::TypeTraitExprClass:
  13524. case Expr::ConceptSpecializationExprClass:
  13525. case Expr::RequiresExprClass:
  13526. case Expr::ArrayTypeTraitExprClass:
  13527. case Expr::ExpressionTraitExprClass:
  13528. case Expr::CXXNoexceptExprClass:
  13529. return NoDiag();
  13530. case Expr::CallExprClass:
  13531. case Expr::CXXOperatorCallExprClass: {
  13532. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  13533. // constant expressions, but they can never be ICEs because an ICE cannot
  13534. // contain an operand of (pointer to) function type.
  13535. const CallExpr *CE = cast<CallExpr>(E);
  13536. if (CE->getBuiltinCallee())
  13537. return CheckEvalInICE(E, Ctx);
  13538. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13539. }
  13540. case Expr::CXXRewrittenBinaryOperatorClass:
  13541. return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
  13542. Ctx);
  13543. case Expr::DeclRefExprClass: {
  13544. const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
  13545. if (isa<EnumConstantDecl>(D))
  13546. return NoDiag();
  13547. // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
  13548. // integer variables in constant expressions:
  13549. //
  13550. // C++ 7.1.5.1p2
  13551. // A variable of non-volatile const-qualified integral or enumeration
  13552. // type initialized by an ICE can be used in ICEs.
  13553. //
  13554. // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
  13555. // that mode, use of reference variables should not be allowed.
  13556. const VarDecl *VD = dyn_cast<VarDecl>(D);
  13557. if (VD && VD->isUsableInConstantExpressions(Ctx) &&
  13558. !VD->getType()->isReferenceType())
  13559. return NoDiag();
  13560. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13561. }
  13562. case Expr::UnaryOperatorClass: {
  13563. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  13564. switch (Exp->getOpcode()) {
  13565. case UO_PostInc:
  13566. case UO_PostDec:
  13567. case UO_PreInc:
  13568. case UO_PreDec:
  13569. case UO_AddrOf:
  13570. case UO_Deref:
  13571. case UO_Coawait:
  13572. // C99 6.6/3 allows increment and decrement within unevaluated
  13573. // subexpressions of constant expressions, but they can never be ICEs
  13574. // because an ICE cannot contain an lvalue operand.
  13575. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13576. case UO_Extension:
  13577. case UO_LNot:
  13578. case UO_Plus:
  13579. case UO_Minus:
  13580. case UO_Not:
  13581. case UO_Real:
  13582. case UO_Imag:
  13583. return CheckICE(Exp->getSubExpr(), Ctx);
  13584. }
  13585. llvm_unreachable("invalid unary operator class");
  13586. }
  13587. case Expr::OffsetOfExprClass: {
  13588. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  13589. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  13590. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  13591. // compliance: we should warn earlier for offsetof expressions with
  13592. // array subscripts that aren't ICEs, and if the array subscripts
  13593. // are ICEs, the value of the offsetof must be an integer constant.
  13594. return CheckEvalInICE(E, Ctx);
  13595. }
  13596. case Expr::UnaryExprOrTypeTraitExprClass: {
  13597. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  13598. if ((Exp->getKind() == UETT_SizeOf) &&
  13599. Exp->getTypeOfArgument()->isVariableArrayType())
  13600. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13601. return NoDiag();
  13602. }
  13603. case Expr::BinaryOperatorClass: {
  13604. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  13605. switch (Exp->getOpcode()) {
  13606. case BO_PtrMemD:
  13607. case BO_PtrMemI:
  13608. case BO_Assign:
  13609. case BO_MulAssign:
  13610. case BO_DivAssign:
  13611. case BO_RemAssign:
  13612. case BO_AddAssign:
  13613. case BO_SubAssign:
  13614. case BO_ShlAssign:
  13615. case BO_ShrAssign:
  13616. case BO_AndAssign:
  13617. case BO_XorAssign:
  13618. case BO_OrAssign:
  13619. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  13620. // constant expressions, but they can never be ICEs because an ICE cannot
  13621. // contain an lvalue operand.
  13622. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13623. case BO_Mul:
  13624. case BO_Div:
  13625. case BO_Rem:
  13626. case BO_Add:
  13627. case BO_Sub:
  13628. case BO_Shl:
  13629. case BO_Shr:
  13630. case BO_LT:
  13631. case BO_GT:
  13632. case BO_LE:
  13633. case BO_GE:
  13634. case BO_EQ:
  13635. case BO_NE:
  13636. case BO_And:
  13637. case BO_Xor:
  13638. case BO_Or:
  13639. case BO_Comma:
  13640. case BO_Cmp: {
  13641. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  13642. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  13643. if (Exp->getOpcode() == BO_Div ||
  13644. Exp->getOpcode() == BO_Rem) {
  13645. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  13646. // we don't evaluate one.
  13647. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  13648. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  13649. if (REval == 0)
  13650. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  13651. if (REval.isSigned() && REval.isAllOnes()) {
  13652. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  13653. if (LEval.isMinSignedValue())
  13654. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  13655. }
  13656. }
  13657. }
  13658. if (Exp->getOpcode() == BO_Comma) {
  13659. if (Ctx.getLangOpts().C99) {
  13660. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  13661. // if it isn't evaluated.
  13662. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  13663. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  13664. } else {
  13665. // In both C89 and C++, commas in ICEs are illegal.
  13666. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13667. }
  13668. }
  13669. return Worst(LHSResult, RHSResult);
  13670. }
  13671. case BO_LAnd:
  13672. case BO_LOr: {
  13673. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  13674. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  13675. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  13676. // Rare case where the RHS has a comma "side-effect"; we need
  13677. // to actually check the condition to see whether the side
  13678. // with the comma is evaluated.
  13679. if ((Exp->getOpcode() == BO_LAnd) !=
  13680. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  13681. return RHSResult;
  13682. return NoDiag();
  13683. }
  13684. return Worst(LHSResult, RHSResult);
  13685. }
  13686. }
  13687. llvm_unreachable("invalid binary operator kind");
  13688. }
  13689. case Expr::ImplicitCastExprClass:
  13690. case Expr::CStyleCastExprClass:
  13691. case Expr::CXXFunctionalCastExprClass:
  13692. case Expr::CXXStaticCastExprClass:
  13693. case Expr::CXXReinterpretCastExprClass:
  13694. case Expr::CXXConstCastExprClass:
  13695. case Expr::ObjCBridgedCastExprClass: {
  13696. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  13697. if (isa<ExplicitCastExpr>(E)) {
  13698. if (const FloatingLiteral *FL
  13699. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  13700. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  13701. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  13702. APSInt IgnoredVal(DestWidth, !DestSigned);
  13703. bool Ignored;
  13704. // If the value does not fit in the destination type, the behavior is
  13705. // undefined, so we are not required to treat it as a constant
  13706. // expression.
  13707. if (FL->getValue().convertToInteger(IgnoredVal,
  13708. llvm::APFloat::rmTowardZero,
  13709. &Ignored) & APFloat::opInvalidOp)
  13710. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13711. return NoDiag();
  13712. }
  13713. }
  13714. switch (cast<CastExpr>(E)->getCastKind()) {
  13715. case CK_LValueToRValue:
  13716. case CK_AtomicToNonAtomic:
  13717. case CK_NonAtomicToAtomic:
  13718. case CK_NoOp:
  13719. case CK_IntegralToBoolean:
  13720. case CK_IntegralCast:
  13721. return CheckICE(SubExpr, Ctx);
  13722. default:
  13723. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13724. }
  13725. }
  13726. case Expr::BinaryConditionalOperatorClass: {
  13727. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  13728. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  13729. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  13730. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  13731. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  13732. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  13733. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  13734. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  13735. return FalseResult;
  13736. }
  13737. case Expr::ConditionalOperatorClass: {
  13738. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  13739. // If the condition (ignoring parens) is a __builtin_constant_p call,
  13740. // then only the true side is actually considered in an integer constant
  13741. // expression, and it is fully evaluated. This is an important GNU
  13742. // extension. See GCC PR38377 for discussion.
  13743. if (const CallExpr *CallCE
  13744. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  13745. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  13746. return CheckEvalInICE(E, Ctx);
  13747. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  13748. if (CondResult.Kind == IK_NotICE)
  13749. return CondResult;
  13750. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  13751. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  13752. if (TrueResult.Kind == IK_NotICE)
  13753. return TrueResult;
  13754. if (FalseResult.Kind == IK_NotICE)
  13755. return FalseResult;
  13756. if (CondResult.Kind == IK_ICEIfUnevaluated)
  13757. return CondResult;
  13758. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  13759. return NoDiag();
  13760. // Rare case where the diagnostics depend on which side is evaluated
  13761. // Note that if we get here, CondResult is 0, and at least one of
  13762. // TrueResult and FalseResult is non-zero.
  13763. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  13764. return FalseResult;
  13765. return TrueResult;
  13766. }
  13767. case Expr::CXXDefaultArgExprClass:
  13768. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  13769. case Expr::CXXDefaultInitExprClass:
  13770. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  13771. case Expr::ChooseExprClass: {
  13772. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  13773. }
  13774. case Expr::BuiltinBitCastExprClass: {
  13775. if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
  13776. return ICEDiag(IK_NotICE, E->getBeginLoc());
  13777. return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
  13778. }
  13779. }
  13780. llvm_unreachable("Invalid StmtClass!");
  13781. }
  13782. /// Evaluate an expression as a C++11 integral constant expression.
  13783. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  13784. const Expr *E,
  13785. llvm::APSInt *Value,
  13786. SourceLocation *Loc) {
  13787. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  13788. if (Loc) *Loc = E->getExprLoc();
  13789. return false;
  13790. }
  13791. APValue Result;
  13792. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  13793. return false;
  13794. if (!Result.isInt()) {
  13795. if (Loc) *Loc = E->getExprLoc();
  13796. return false;
  13797. }
  13798. if (Value) *Value = Result.getInt();
  13799. return true;
  13800. }
  13801. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  13802. SourceLocation *Loc) const {
  13803. assert(!isValueDependent() &&
  13804. "Expression evaluator can't be called on a dependent expression.");
  13805. if (Ctx.getLangOpts().CPlusPlus11)
  13806. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  13807. ICEDiag D = CheckICE(this, Ctx);
  13808. if (D.Kind != IK_ICE) {
  13809. if (Loc) *Loc = D.Loc;
  13810. return false;
  13811. }
  13812. return true;
  13813. }
  13814. Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
  13815. SourceLocation *Loc,
  13816. bool isEvaluated) const {
  13817. if (isValueDependent()) {
  13818. // Expression evaluator can't succeed on a dependent expression.
  13819. return None;
  13820. }
  13821. APSInt Value;
  13822. if (Ctx.getLangOpts().CPlusPlus11) {
  13823. if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
  13824. return Value;
  13825. return None;
  13826. }
  13827. if (!isIntegerConstantExpr(Ctx, Loc))
  13828. return None;
  13829. // The only possible side-effects here are due to UB discovered in the
  13830. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  13831. // required to treat the expression as an ICE, so we produce the folded
  13832. // value.
  13833. EvalResult ExprResult;
  13834. Expr::EvalStatus Status;
  13835. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  13836. Info.InConstantContext = true;
  13837. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  13838. llvm_unreachable("ICE cannot be evaluated!");
  13839. return ExprResult.Val.getInt();
  13840. }
  13841. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  13842. assert(!isValueDependent() &&
  13843. "Expression evaluator can't be called on a dependent expression.");
  13844. return CheckICE(this, Ctx).Kind == IK_ICE;
  13845. }
  13846. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  13847. SourceLocation *Loc) const {
  13848. assert(!isValueDependent() &&
  13849. "Expression evaluator can't be called on a dependent expression.");
  13850. // We support this checking in C++98 mode in order to diagnose compatibility
  13851. // issues.
  13852. assert(Ctx.getLangOpts().CPlusPlus);
  13853. // Build evaluation settings.
  13854. Expr::EvalStatus Status;
  13855. SmallVector<PartialDiagnosticAt, 8> Diags;
  13856. Status.Diag = &Diags;
  13857. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  13858. APValue Scratch;
  13859. bool IsConstExpr =
  13860. ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
  13861. // FIXME: We don't produce a diagnostic for this, but the callers that
  13862. // call us on arbitrary full-expressions should generally not care.
  13863. Info.discardCleanups() && !Status.HasSideEffects;
  13864. if (!Diags.empty()) {
  13865. IsConstExpr = false;
  13866. if (Loc) *Loc = Diags[0].first;
  13867. } else if (!IsConstExpr) {
  13868. // FIXME: This shouldn't happen.
  13869. if (Loc) *Loc = getExprLoc();
  13870. }
  13871. return IsConstExpr;
  13872. }
  13873. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  13874. const FunctionDecl *Callee,
  13875. ArrayRef<const Expr*> Args,
  13876. const Expr *This) const {
  13877. assert(!isValueDependent() &&
  13878. "Expression evaluator can't be called on a dependent expression.");
  13879. Expr::EvalStatus Status;
  13880. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  13881. Info.InConstantContext = true;
  13882. LValue ThisVal;
  13883. const LValue *ThisPtr = nullptr;
  13884. if (This) {
  13885. #ifndef NDEBUG
  13886. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  13887. assert(MD && "Don't provide `this` for non-methods.");
  13888. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  13889. #endif
  13890. if (!This->isValueDependent() &&
  13891. EvaluateObjectArgument(Info, This, ThisVal) &&
  13892. !Info.EvalStatus.HasSideEffects)
  13893. ThisPtr = &ThisVal;
  13894. // Ignore any side-effects from a failed evaluation. This is safe because
  13895. // they can't interfere with any other argument evaluation.
  13896. Info.EvalStatus.HasSideEffects = false;
  13897. }
  13898. CallRef Call = Info.CurrentCall->createCall(Callee);
  13899. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  13900. I != E; ++I) {
  13901. unsigned Idx = I - Args.begin();
  13902. if (Idx >= Callee->getNumParams())
  13903. break;
  13904. const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
  13905. if ((*I)->isValueDependent() ||
  13906. !EvaluateCallArg(PVD, *I, Call, Info) ||
  13907. Info.EvalStatus.HasSideEffects) {
  13908. // If evaluation fails, throw away the argument entirely.
  13909. if (APValue *Slot = Info.getParamSlot(Call, PVD))
  13910. *Slot = APValue();
  13911. }
  13912. // Ignore any side-effects from a failed evaluation. This is safe because
  13913. // they can't interfere with any other argument evaluation.
  13914. Info.EvalStatus.HasSideEffects = false;
  13915. }
  13916. // Parameter cleanups happen in the caller and are not part of this
  13917. // evaluation.
  13918. Info.discardCleanups();
  13919. Info.EvalStatus.HasSideEffects = false;
  13920. // Build fake call to Callee.
  13921. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
  13922. // FIXME: Missing ExprWithCleanups in enable_if conditions?
  13923. FullExpressionRAII Scope(Info);
  13924. return Evaluate(Value, Info, this) && Scope.destroy() &&
  13925. !Info.EvalStatus.HasSideEffects;
  13926. }
  13927. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  13928. SmallVectorImpl<
  13929. PartialDiagnosticAt> &Diags) {
  13930. // FIXME: It would be useful to check constexpr function templates, but at the
  13931. // moment the constant expression evaluator cannot cope with the non-rigorous
  13932. // ASTs which we build for dependent expressions.
  13933. if (FD->isDependentContext())
  13934. return true;
  13935. Expr::EvalStatus Status;
  13936. Status.Diag = &Diags;
  13937. EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
  13938. Info.InConstantContext = true;
  13939. Info.CheckingPotentialConstantExpression = true;
  13940. // The constexpr VM attempts to compile all methods to bytecode here.
  13941. if (Info.EnableNewConstInterp) {
  13942. Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
  13943. return Diags.empty();
  13944. }
  13945. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  13946. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  13947. // Fabricate an arbitrary expression on the stack and pretend that it
  13948. // is a temporary being used as the 'this' pointer.
  13949. LValue This;
  13950. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  13951. This.set({&VIE, Info.CurrentCall->Index});
  13952. ArrayRef<const Expr*> Args;
  13953. APValue Scratch;
  13954. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  13955. // Evaluate the call as a constant initializer, to allow the construction
  13956. // of objects of non-literal types.
  13957. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  13958. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  13959. } else {
  13960. SourceLocation Loc = FD->getLocation();
  13961. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  13962. Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
  13963. }
  13964. return Diags.empty();
  13965. }
  13966. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  13967. const FunctionDecl *FD,
  13968. SmallVectorImpl<
  13969. PartialDiagnosticAt> &Diags) {
  13970. assert(!E->isValueDependent() &&
  13971. "Expression evaluator can't be called on a dependent expression.");
  13972. Expr::EvalStatus Status;
  13973. Status.Diag = &Diags;
  13974. EvalInfo Info(FD->getASTContext(), Status,
  13975. EvalInfo::EM_ConstantExpressionUnevaluated);
  13976. Info.InConstantContext = true;
  13977. Info.CheckingPotentialConstantExpression = true;
  13978. // Fabricate a call stack frame to give the arguments a plausible cover story.
  13979. CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
  13980. APValue ResultScratch;
  13981. Evaluate(ResultScratch, Info, E);
  13982. return Diags.empty();
  13983. }
  13984. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  13985. unsigned Type) const {
  13986. if (!getType()->isPointerType())
  13987. return false;
  13988. Expr::EvalStatus Status;
  13989. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  13990. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  13991. }
  13992. static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
  13993. EvalInfo &Info) {
  13994. if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
  13995. return false;
  13996. LValue String;
  13997. if (!EvaluatePointer(E, String, Info))
  13998. return false;
  13999. QualType CharTy = E->getType()->getPointeeType();
  14000. // Fast path: if it's a string literal, search the string value.
  14001. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  14002. String.getLValueBase().dyn_cast<const Expr *>())) {
  14003. StringRef Str = S->getBytes();
  14004. int64_t Off = String.Offset.getQuantity();
  14005. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  14006. S->getCharByteWidth() == 1 &&
  14007. // FIXME: Add fast-path for wchar_t too.
  14008. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  14009. Str = Str.substr(Off);
  14010. StringRef::size_type Pos = Str.find(0);
  14011. if (Pos != StringRef::npos)
  14012. Str = Str.substr(0, Pos);
  14013. Result = Str.size();
  14014. return true;
  14015. }
  14016. // Fall through to slow path.
  14017. }
  14018. // Slow path: scan the bytes of the string looking for the terminating 0.
  14019. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  14020. APValue Char;
  14021. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  14022. !Char.isInt())
  14023. return false;
  14024. if (!Char.getInt()) {
  14025. Result = Strlen;
  14026. return true;
  14027. }
  14028. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  14029. return false;
  14030. }
  14031. }
  14032. bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
  14033. Expr::EvalStatus Status;
  14034. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  14035. return EvaluateBuiltinStrLen(this, Result, Info);
  14036. }