ExprConstant.cpp 409 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Expr constant evaluator.
  11. //
  12. // Constant expression evaluation produces four main results:
  13. //
  14. // * A success/failure flag indicating whether constant folding was successful.
  15. // This is the 'bool' return value used by most of the code in this file. A
  16. // 'false' return value indicates that constant folding has failed, and any
  17. // appropriate diagnostic has already been produced.
  18. //
  19. // * An evaluated result, valid only if constant folding has not failed.
  20. //
  21. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  22. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  23. // where it is possible to determine the evaluated result regardless.
  24. //
  25. // * A set of notes indicating why the evaluation was not a constant expression
  26. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  27. // too, why the expression could not be folded.
  28. //
  29. // If we are checking for a potential constant expression, failure to constant
  30. // fold a potential constant sub-expression will be indicated by a 'false'
  31. // return value (the expression could not be folded) and no diagnostic (the
  32. // expression is not necessarily non-constant).
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #include "clang/AST/APValue.h"
  36. #include "clang/AST/ASTContext.h"
  37. #include "clang/AST/ASTDiagnostic.h"
  38. #include "clang/AST/ASTLambda.h"
  39. #include "clang/AST/CharUnits.h"
  40. #include "clang/AST/Expr.h"
  41. #include "clang/AST/OSLog.h"
  42. #include "clang/AST/RecordLayout.h"
  43. #include "clang/AST/StmtVisitor.h"
  44. #include "clang/AST/TypeLoc.h"
  45. #include "clang/Basic/Builtins.h"
  46. #include "clang/Basic/TargetInfo.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <cstring>
  49. #include <functional>
  50. #define DEBUG_TYPE "exprconstant"
  51. using namespace clang;
  52. using llvm::APSInt;
  53. using llvm::APFloat;
  54. static bool IsGlobalLValue(APValue::LValueBase B);
  55. namespace {
  56. struct LValue;
  57. struct CallStackFrame;
  58. struct EvalInfo;
  59. static QualType getType(APValue::LValueBase B) {
  60. if (!B) return QualType();
  61. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  62. // FIXME: It's unclear where we're supposed to take the type from, and
  63. // this actually matters for arrays of unknown bound. Eg:
  64. //
  65. // extern int arr[]; void f() { extern int arr[3]; };
  66. // constexpr int *p = &arr[1]; // valid?
  67. //
  68. // For now, we take the array bound from the most recent declaration.
  69. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  70. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  71. QualType T = Redecl->getType();
  72. if (!T->isIncompleteArrayType())
  73. return T;
  74. }
  75. return D->getType();
  76. }
  77. const Expr *Base = B.get<const Expr*>();
  78. // For a materialized temporary, the type of the temporary we materialized
  79. // may not be the type of the expression.
  80. if (const MaterializeTemporaryExpr *MTE =
  81. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  82. SmallVector<const Expr *, 2> CommaLHSs;
  83. SmallVector<SubobjectAdjustment, 2> Adjustments;
  84. const Expr *Temp = MTE->GetTemporaryExpr();
  85. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  86. Adjustments);
  87. // Keep any cv-qualifiers from the reference if we generated a temporary
  88. // for it directly. Otherwise use the type after adjustment.
  89. if (!Adjustments.empty())
  90. return Inner->getType();
  91. }
  92. return Base->getType();
  93. }
  94. /// Get an LValue path entry, which is known to not be an array index, as a
  95. /// field or base class.
  96. static
  97. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  98. APValue::BaseOrMemberType Value;
  99. Value.setFromOpaqueValue(E.BaseOrMember);
  100. return Value;
  101. }
  102. /// Get an LValue path entry, which is known to not be an array index, as a
  103. /// field declaration.
  104. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  105. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  106. }
  107. /// Get an LValue path entry, which is known to not be an array index, as a
  108. /// base class declaration.
  109. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  110. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  111. }
  112. /// Determine whether this LValue path entry for a base class names a virtual
  113. /// base class.
  114. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  115. return getAsBaseOrMember(E).getInt();
  116. }
  117. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  118. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  119. const FunctionDecl *Callee = CE->getDirectCallee();
  120. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  121. }
  122. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  123. /// This will look through a single cast.
  124. ///
  125. /// Returns null if we couldn't unwrap a function with alloc_size.
  126. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  127. if (!E->getType()->isPointerType())
  128. return nullptr;
  129. E = E->IgnoreParens();
  130. // If we're doing a variable assignment from e.g. malloc(N), there will
  131. // probably be a cast of some kind. In exotic cases, we might also see a
  132. // top-level ExprWithCleanups. Ignore them either way.
  133. if (const auto *FE = dyn_cast<FullExpr>(E))
  134. E = FE->getSubExpr()->IgnoreParens();
  135. if (const auto *Cast = dyn_cast<CastExpr>(E))
  136. E = Cast->getSubExpr()->IgnoreParens();
  137. if (const auto *CE = dyn_cast<CallExpr>(E))
  138. return getAllocSizeAttr(CE) ? CE : nullptr;
  139. return nullptr;
  140. }
  141. /// Determines whether or not the given Base contains a call to a function
  142. /// with the alloc_size attribute.
  143. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  144. const auto *E = Base.dyn_cast<const Expr *>();
  145. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  146. }
  147. /// The bound to claim that an array of unknown bound has.
  148. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  149. /// to an arbitrary value that's likely to loudly break things if it's used.
  150. static const uint64_t AssumedSizeForUnsizedArray =
  151. std::numeric_limits<uint64_t>::max() / 2;
  152. /// Determines if an LValue with the given LValueBase will have an unsized
  153. /// array in its designator.
  154. /// Find the path length and type of the most-derived subobject in the given
  155. /// path, and find the size of the containing array, if any.
  156. static unsigned
  157. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  158. ArrayRef<APValue::LValuePathEntry> Path,
  159. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  160. bool &FirstEntryIsUnsizedArray) {
  161. // This only accepts LValueBases from APValues, and APValues don't support
  162. // arrays that lack size info.
  163. assert(!isBaseAnAllocSizeCall(Base) &&
  164. "Unsized arrays shouldn't appear here");
  165. unsigned MostDerivedLength = 0;
  166. Type = getType(Base);
  167. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  168. if (Type->isArrayType()) {
  169. const ArrayType *AT = Ctx.getAsArrayType(Type);
  170. Type = AT->getElementType();
  171. MostDerivedLength = I + 1;
  172. IsArray = true;
  173. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  174. ArraySize = CAT->getSize().getZExtValue();
  175. } else {
  176. assert(I == 0 && "unexpected unsized array designator");
  177. FirstEntryIsUnsizedArray = true;
  178. ArraySize = AssumedSizeForUnsizedArray;
  179. }
  180. } else if (Type->isAnyComplexType()) {
  181. const ComplexType *CT = Type->castAs<ComplexType>();
  182. Type = CT->getElementType();
  183. ArraySize = 2;
  184. MostDerivedLength = I + 1;
  185. IsArray = true;
  186. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  187. Type = FD->getType();
  188. ArraySize = 0;
  189. MostDerivedLength = I + 1;
  190. IsArray = false;
  191. } else {
  192. // Path[I] describes a base class.
  193. ArraySize = 0;
  194. IsArray = false;
  195. }
  196. }
  197. return MostDerivedLength;
  198. }
  199. // The order of this enum is important for diagnostics.
  200. enum CheckSubobjectKind {
  201. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  202. CSK_This, CSK_Real, CSK_Imag
  203. };
  204. /// A path from a glvalue to a subobject of that glvalue.
  205. struct SubobjectDesignator {
  206. /// True if the subobject was named in a manner not supported by C++11. Such
  207. /// lvalues can still be folded, but they are not core constant expressions
  208. /// and we cannot perform lvalue-to-rvalue conversions on them.
  209. unsigned Invalid : 1;
  210. /// Is this a pointer one past the end of an object?
  211. unsigned IsOnePastTheEnd : 1;
  212. /// Indicator of whether the first entry is an unsized array.
  213. unsigned FirstEntryIsAnUnsizedArray : 1;
  214. /// Indicator of whether the most-derived object is an array element.
  215. unsigned MostDerivedIsArrayElement : 1;
  216. /// The length of the path to the most-derived object of which this is a
  217. /// subobject.
  218. unsigned MostDerivedPathLength : 28;
  219. /// The size of the array of which the most-derived object is an element.
  220. /// This will always be 0 if the most-derived object is not an array
  221. /// element. 0 is not an indicator of whether or not the most-derived object
  222. /// is an array, however, because 0-length arrays are allowed.
  223. ///
  224. /// If the current array is an unsized array, the value of this is
  225. /// undefined.
  226. uint64_t MostDerivedArraySize;
  227. /// The type of the most derived object referred to by this address.
  228. QualType MostDerivedType;
  229. typedef APValue::LValuePathEntry PathEntry;
  230. /// The entries on the path from the glvalue to the designated subobject.
  231. SmallVector<PathEntry, 8> Entries;
  232. SubobjectDesignator() : Invalid(true) {}
  233. explicit SubobjectDesignator(QualType T)
  234. : Invalid(false), IsOnePastTheEnd(false),
  235. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  236. MostDerivedPathLength(0), MostDerivedArraySize(0),
  237. MostDerivedType(T) {}
  238. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  239. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  240. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  241. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  242. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  243. if (!Invalid) {
  244. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  245. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  246. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  247. if (V.getLValueBase()) {
  248. bool IsArray = false;
  249. bool FirstIsUnsizedArray = false;
  250. MostDerivedPathLength = findMostDerivedSubobject(
  251. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  252. MostDerivedType, IsArray, FirstIsUnsizedArray);
  253. MostDerivedIsArrayElement = IsArray;
  254. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  255. }
  256. }
  257. }
  258. void setInvalid() {
  259. Invalid = true;
  260. Entries.clear();
  261. }
  262. /// Determine whether the most derived subobject is an array without a
  263. /// known bound.
  264. bool isMostDerivedAnUnsizedArray() const {
  265. assert(!Invalid && "Calling this makes no sense on invalid designators");
  266. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  267. }
  268. /// Determine what the most derived array's size is. Results in an assertion
  269. /// failure if the most derived array lacks a size.
  270. uint64_t getMostDerivedArraySize() const {
  271. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  272. return MostDerivedArraySize;
  273. }
  274. /// Determine whether this is a one-past-the-end pointer.
  275. bool isOnePastTheEnd() const {
  276. assert(!Invalid);
  277. if (IsOnePastTheEnd)
  278. return true;
  279. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  280. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  281. return true;
  282. return false;
  283. }
  284. /// Get the range of valid index adjustments in the form
  285. /// {maximum value that can be subtracted from this pointer,
  286. /// maximum value that can be added to this pointer}
  287. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  288. if (Invalid || isMostDerivedAnUnsizedArray())
  289. return {0, 0};
  290. // [expr.add]p4: For the purposes of these operators, a pointer to a
  291. // nonarray object behaves the same as a pointer to the first element of
  292. // an array of length one with the type of the object as its element type.
  293. bool IsArray = MostDerivedPathLength == Entries.size() &&
  294. MostDerivedIsArrayElement;
  295. uint64_t ArrayIndex =
  296. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  297. uint64_t ArraySize =
  298. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  299. return {ArrayIndex, ArraySize - ArrayIndex};
  300. }
  301. /// Check that this refers to a valid subobject.
  302. bool isValidSubobject() const {
  303. if (Invalid)
  304. return false;
  305. return !isOnePastTheEnd();
  306. }
  307. /// Check that this refers to a valid subobject, and if not, produce a
  308. /// relevant diagnostic and set the designator as invalid.
  309. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  310. /// Get the type of the designated object.
  311. QualType getType(ASTContext &Ctx) const {
  312. assert(!Invalid && "invalid designator has no subobject type");
  313. return MostDerivedPathLength == Entries.size()
  314. ? MostDerivedType
  315. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  316. }
  317. /// Update this designator to refer to the first element within this array.
  318. void addArrayUnchecked(const ConstantArrayType *CAT) {
  319. PathEntry Entry;
  320. Entry.ArrayIndex = 0;
  321. Entries.push_back(Entry);
  322. // This is a most-derived object.
  323. MostDerivedType = CAT->getElementType();
  324. MostDerivedIsArrayElement = true;
  325. MostDerivedArraySize = CAT->getSize().getZExtValue();
  326. MostDerivedPathLength = Entries.size();
  327. }
  328. /// Update this designator to refer to the first element within the array of
  329. /// elements of type T. This is an array of unknown size.
  330. void addUnsizedArrayUnchecked(QualType ElemTy) {
  331. PathEntry Entry;
  332. Entry.ArrayIndex = 0;
  333. Entries.push_back(Entry);
  334. MostDerivedType = ElemTy;
  335. MostDerivedIsArrayElement = true;
  336. // The value in MostDerivedArraySize is undefined in this case. So, set it
  337. // to an arbitrary value that's likely to loudly break things if it's
  338. // used.
  339. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  340. MostDerivedPathLength = Entries.size();
  341. }
  342. /// Update this designator to refer to the given base or member of this
  343. /// object.
  344. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  345. PathEntry Entry;
  346. APValue::BaseOrMemberType Value(D, Virtual);
  347. Entry.BaseOrMember = Value.getOpaqueValue();
  348. Entries.push_back(Entry);
  349. // If this isn't a base class, it's a new most-derived object.
  350. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  351. MostDerivedType = FD->getType();
  352. MostDerivedIsArrayElement = false;
  353. MostDerivedArraySize = 0;
  354. MostDerivedPathLength = Entries.size();
  355. }
  356. }
  357. /// Update this designator to refer to the given complex component.
  358. void addComplexUnchecked(QualType EltTy, bool Imag) {
  359. PathEntry Entry;
  360. Entry.ArrayIndex = Imag;
  361. Entries.push_back(Entry);
  362. // This is technically a most-derived object, though in practice this
  363. // is unlikely to matter.
  364. MostDerivedType = EltTy;
  365. MostDerivedIsArrayElement = true;
  366. MostDerivedArraySize = 2;
  367. MostDerivedPathLength = Entries.size();
  368. }
  369. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  370. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  371. const APSInt &N);
  372. /// Add N to the address of this subobject.
  373. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  374. if (Invalid || !N) return;
  375. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  376. if (isMostDerivedAnUnsizedArray()) {
  377. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  378. // Can't verify -- trust that the user is doing the right thing (or if
  379. // not, trust that the caller will catch the bad behavior).
  380. // FIXME: Should we reject if this overflows, at least?
  381. Entries.back().ArrayIndex += TruncatedN;
  382. return;
  383. }
  384. // [expr.add]p4: For the purposes of these operators, a pointer to a
  385. // nonarray object behaves the same as a pointer to the first element of
  386. // an array of length one with the type of the object as its element type.
  387. bool IsArray = MostDerivedPathLength == Entries.size() &&
  388. MostDerivedIsArrayElement;
  389. uint64_t ArrayIndex =
  390. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  391. uint64_t ArraySize =
  392. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  393. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  394. // Calculate the actual index in a wide enough type, so we can include
  395. // it in the note.
  396. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  397. (llvm::APInt&)N += ArrayIndex;
  398. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  399. diagnosePointerArithmetic(Info, E, N);
  400. setInvalid();
  401. return;
  402. }
  403. ArrayIndex += TruncatedN;
  404. assert(ArrayIndex <= ArraySize &&
  405. "bounds check succeeded for out-of-bounds index");
  406. if (IsArray)
  407. Entries.back().ArrayIndex = ArrayIndex;
  408. else
  409. IsOnePastTheEnd = (ArrayIndex != 0);
  410. }
  411. };
  412. /// A stack frame in the constexpr call stack.
  413. struct CallStackFrame {
  414. EvalInfo &Info;
  415. /// Parent - The caller of this stack frame.
  416. CallStackFrame *Caller;
  417. /// Callee - The function which was called.
  418. const FunctionDecl *Callee;
  419. /// This - The binding for the this pointer in this call, if any.
  420. const LValue *This;
  421. /// Arguments - Parameter bindings for this function call, indexed by
  422. /// parameters' function scope indices.
  423. APValue *Arguments;
  424. // Note that we intentionally use std::map here so that references to
  425. // values are stable.
  426. typedef std::pair<const void *, unsigned> MapKeyTy;
  427. typedef std::map<MapKeyTy, APValue> MapTy;
  428. /// Temporaries - Temporary lvalues materialized within this stack frame.
  429. MapTy Temporaries;
  430. /// CallLoc - The location of the call expression for this call.
  431. SourceLocation CallLoc;
  432. /// Index - The call index of this call.
  433. unsigned Index;
  434. /// The stack of integers for tracking version numbers for temporaries.
  435. SmallVector<unsigned, 2> TempVersionStack = {1};
  436. unsigned CurTempVersion = TempVersionStack.back();
  437. unsigned getTempVersion() const { return TempVersionStack.back(); }
  438. void pushTempVersion() {
  439. TempVersionStack.push_back(++CurTempVersion);
  440. }
  441. void popTempVersion() {
  442. TempVersionStack.pop_back();
  443. }
  444. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  445. // on the overall stack usage of deeply-recursing constexpr evaluataions.
  446. // (We should cache this map rather than recomputing it repeatedly.)
  447. // But let's try this and see how it goes; we can look into caching the map
  448. // as a later change.
  449. /// LambdaCaptureFields - Mapping from captured variables/this to
  450. /// corresponding data members in the closure class.
  451. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  452. FieldDecl *LambdaThisCaptureField;
  453. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  454. const FunctionDecl *Callee, const LValue *This,
  455. APValue *Arguments);
  456. ~CallStackFrame();
  457. // Return the temporary for Key whose version number is Version.
  458. APValue *getTemporary(const void *Key, unsigned Version) {
  459. MapKeyTy KV(Key, Version);
  460. auto LB = Temporaries.lower_bound(KV);
  461. if (LB != Temporaries.end() && LB->first == KV)
  462. return &LB->second;
  463. // Pair (Key,Version) wasn't found in the map. Check that no elements
  464. // in the map have 'Key' as their key.
  465. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  466. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  467. "Element with key 'Key' found in map");
  468. return nullptr;
  469. }
  470. // Return the current temporary for Key in the map.
  471. APValue *getCurrentTemporary(const void *Key) {
  472. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  473. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  474. return &std::prev(UB)->second;
  475. return nullptr;
  476. }
  477. // Return the version number of the current temporary for Key.
  478. unsigned getCurrentTemporaryVersion(const void *Key) const {
  479. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  480. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  481. return std::prev(UB)->first.second;
  482. return 0;
  483. }
  484. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  485. };
  486. /// Temporarily override 'this'.
  487. class ThisOverrideRAII {
  488. public:
  489. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  490. : Frame(Frame), OldThis(Frame.This) {
  491. if (Enable)
  492. Frame.This = NewThis;
  493. }
  494. ~ThisOverrideRAII() {
  495. Frame.This = OldThis;
  496. }
  497. private:
  498. CallStackFrame &Frame;
  499. const LValue *OldThis;
  500. };
  501. /// A partial diagnostic which we might know in advance that we are not going
  502. /// to emit.
  503. class OptionalDiagnostic {
  504. PartialDiagnostic *Diag;
  505. public:
  506. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  507. : Diag(Diag) {}
  508. template<typename T>
  509. OptionalDiagnostic &operator<<(const T &v) {
  510. if (Diag)
  511. *Diag << v;
  512. return *this;
  513. }
  514. OptionalDiagnostic &operator<<(const APSInt &I) {
  515. if (Diag) {
  516. SmallVector<char, 32> Buffer;
  517. I.toString(Buffer);
  518. *Diag << StringRef(Buffer.data(), Buffer.size());
  519. }
  520. return *this;
  521. }
  522. OptionalDiagnostic &operator<<(const APFloat &F) {
  523. if (Diag) {
  524. // FIXME: Force the precision of the source value down so we don't
  525. // print digits which are usually useless (we don't really care here if
  526. // we truncate a digit by accident in edge cases). Ideally,
  527. // APFloat::toString would automatically print the shortest
  528. // representation which rounds to the correct value, but it's a bit
  529. // tricky to implement.
  530. unsigned precision =
  531. llvm::APFloat::semanticsPrecision(F.getSemantics());
  532. precision = (precision * 59 + 195) / 196;
  533. SmallVector<char, 32> Buffer;
  534. F.toString(Buffer, precision);
  535. *Diag << StringRef(Buffer.data(), Buffer.size());
  536. }
  537. return *this;
  538. }
  539. };
  540. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  541. class Cleanup {
  542. llvm::PointerIntPair<APValue*, 1, bool> Value;
  543. public:
  544. Cleanup(APValue *Val, bool IsLifetimeExtended)
  545. : Value(Val, IsLifetimeExtended) {}
  546. bool isLifetimeExtended() const { return Value.getInt(); }
  547. void endLifetime() {
  548. *Value.getPointer() = APValue();
  549. }
  550. };
  551. /// EvalInfo - This is a private struct used by the evaluator to capture
  552. /// information about a subexpression as it is folded. It retains information
  553. /// about the AST context, but also maintains information about the folded
  554. /// expression.
  555. ///
  556. /// If an expression could be evaluated, it is still possible it is not a C
  557. /// "integer constant expression" or constant expression. If not, this struct
  558. /// captures information about how and why not.
  559. ///
  560. /// One bit of information passed *into* the request for constant folding
  561. /// indicates whether the subexpression is "evaluated" or not according to C
  562. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  563. /// evaluate the expression regardless of what the RHS is, but C only allows
  564. /// certain things in certain situations.
  565. struct EvalInfo {
  566. ASTContext &Ctx;
  567. /// EvalStatus - Contains information about the evaluation.
  568. Expr::EvalStatus &EvalStatus;
  569. /// CurrentCall - The top of the constexpr call stack.
  570. CallStackFrame *CurrentCall;
  571. /// CallStackDepth - The number of calls in the call stack right now.
  572. unsigned CallStackDepth;
  573. /// NextCallIndex - The next call index to assign.
  574. unsigned NextCallIndex;
  575. /// StepsLeft - The remaining number of evaluation steps we're permitted
  576. /// to perform. This is essentially a limit for the number of statements
  577. /// we will evaluate.
  578. unsigned StepsLeft;
  579. /// BottomFrame - The frame in which evaluation started. This must be
  580. /// initialized after CurrentCall and CallStackDepth.
  581. CallStackFrame BottomFrame;
  582. /// A stack of values whose lifetimes end at the end of some surrounding
  583. /// evaluation frame.
  584. llvm::SmallVector<Cleanup, 16> CleanupStack;
  585. /// EvaluatingDecl - This is the declaration whose initializer is being
  586. /// evaluated, if any.
  587. APValue::LValueBase EvaluatingDecl;
  588. /// EvaluatingDeclValue - This is the value being constructed for the
  589. /// declaration whose initializer is being evaluated, if any.
  590. APValue *EvaluatingDeclValue;
  591. /// EvaluatingObject - Pair of the AST node that an lvalue represents and
  592. /// the call index that that lvalue was allocated in.
  593. typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
  594. EvaluatingObject;
  595. /// EvaluatingConstructors - Set of objects that are currently being
  596. /// constructed.
  597. llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
  598. struct EvaluatingConstructorRAII {
  599. EvalInfo &EI;
  600. EvaluatingObject Object;
  601. bool DidInsert;
  602. EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
  603. : EI(EI), Object(Object) {
  604. DidInsert = EI.EvaluatingConstructors.insert(Object).second;
  605. }
  606. ~EvaluatingConstructorRAII() {
  607. if (DidInsert) EI.EvaluatingConstructors.erase(Object);
  608. }
  609. };
  610. bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
  611. unsigned Version) {
  612. return EvaluatingConstructors.count(
  613. EvaluatingObject(Decl, {CallIndex, Version}));
  614. }
  615. /// The current array initialization index, if we're performing array
  616. /// initialization.
  617. uint64_t ArrayInitIndex = -1;
  618. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  619. /// notes attached to it will also be stored, otherwise they will not be.
  620. bool HasActiveDiagnostic;
  621. /// Have we emitted a diagnostic explaining why we couldn't constant
  622. /// fold (not just why it's not strictly a constant expression)?
  623. bool HasFoldFailureDiagnostic;
  624. /// Whether or not we're currently speculatively evaluating.
  625. bool IsSpeculativelyEvaluating;
  626. enum EvaluationMode {
  627. /// Evaluate as a constant expression. Stop if we find that the expression
  628. /// is not a constant expression.
  629. EM_ConstantExpression,
  630. /// Evaluate as a potential constant expression. Keep going if we hit a
  631. /// construct that we can't evaluate yet (because we don't yet know the
  632. /// value of something) but stop if we hit something that could never be
  633. /// a constant expression.
  634. EM_PotentialConstantExpression,
  635. /// Fold the expression to a constant. Stop if we hit a side-effect that
  636. /// we can't model.
  637. EM_ConstantFold,
  638. /// Evaluate the expression looking for integer overflow and similar
  639. /// issues. Don't worry about side-effects, and try to visit all
  640. /// subexpressions.
  641. EM_EvaluateForOverflow,
  642. /// Evaluate in any way we know how. Don't worry about side-effects that
  643. /// can't be modeled.
  644. EM_IgnoreSideEffects,
  645. /// Evaluate as a constant expression. Stop if we find that the expression
  646. /// is not a constant expression. Some expressions can be retried in the
  647. /// optimizer if we don't constant fold them here, but in an unevaluated
  648. /// context we try to fold them immediately since the optimizer never
  649. /// gets a chance to look at it.
  650. EM_ConstantExpressionUnevaluated,
  651. /// Evaluate as a potential constant expression. Keep going if we hit a
  652. /// construct that we can't evaluate yet (because we don't yet know the
  653. /// value of something) but stop if we hit something that could never be
  654. /// a constant expression. Some expressions can be retried in the
  655. /// optimizer if we don't constant fold them here, but in an unevaluated
  656. /// context we try to fold them immediately since the optimizer never
  657. /// gets a chance to look at it.
  658. EM_PotentialConstantExpressionUnevaluated,
  659. } EvalMode;
  660. /// Are we checking whether the expression is a potential constant
  661. /// expression?
  662. bool checkingPotentialConstantExpression() const {
  663. return EvalMode == EM_PotentialConstantExpression ||
  664. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  665. }
  666. /// Are we checking an expression for overflow?
  667. // FIXME: We should check for any kind of undefined or suspicious behavior
  668. // in such constructs, not just overflow.
  669. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  670. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  671. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  672. CallStackDepth(0), NextCallIndex(1),
  673. StepsLeft(getLangOpts().ConstexprStepLimit),
  674. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  675. EvaluatingDecl((const ValueDecl *)nullptr),
  676. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  677. HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
  678. EvalMode(Mode) {}
  679. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  680. EvaluatingDecl = Base;
  681. EvaluatingDeclValue = &Value;
  682. EvaluatingConstructors.insert({Base, {0, 0}});
  683. }
  684. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  685. bool CheckCallLimit(SourceLocation Loc) {
  686. // Don't perform any constexpr calls (other than the call we're checking)
  687. // when checking a potential constant expression.
  688. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  689. return false;
  690. if (NextCallIndex == 0) {
  691. // NextCallIndex has wrapped around.
  692. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  693. return false;
  694. }
  695. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  696. return true;
  697. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  698. << getLangOpts().ConstexprCallDepth;
  699. return false;
  700. }
  701. CallStackFrame *getCallFrame(unsigned CallIndex) {
  702. assert(CallIndex && "no call index in getCallFrame");
  703. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  704. // be null in this loop.
  705. CallStackFrame *Frame = CurrentCall;
  706. while (Frame->Index > CallIndex)
  707. Frame = Frame->Caller;
  708. return (Frame->Index == CallIndex) ? Frame : nullptr;
  709. }
  710. bool nextStep(const Stmt *S) {
  711. if (!StepsLeft) {
  712. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  713. return false;
  714. }
  715. --StepsLeft;
  716. return true;
  717. }
  718. private:
  719. /// Add a diagnostic to the diagnostics list.
  720. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  721. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  722. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  723. return EvalStatus.Diag->back().second;
  724. }
  725. /// Add notes containing a call stack to the current point of evaluation.
  726. void addCallStack(unsigned Limit);
  727. private:
  728. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  729. unsigned ExtraNotes, bool IsCCEDiag) {
  730. if (EvalStatus.Diag) {
  731. // If we have a prior diagnostic, it will be noting that the expression
  732. // isn't a constant expression. This diagnostic is more important,
  733. // unless we require this evaluation to produce a constant expression.
  734. //
  735. // FIXME: We might want to show both diagnostics to the user in
  736. // EM_ConstantFold mode.
  737. if (!EvalStatus.Diag->empty()) {
  738. switch (EvalMode) {
  739. case EM_ConstantFold:
  740. case EM_IgnoreSideEffects:
  741. case EM_EvaluateForOverflow:
  742. if (!HasFoldFailureDiagnostic)
  743. break;
  744. // We've already failed to fold something. Keep that diagnostic.
  745. LLVM_FALLTHROUGH;
  746. case EM_ConstantExpression:
  747. case EM_PotentialConstantExpression:
  748. case EM_ConstantExpressionUnevaluated:
  749. case EM_PotentialConstantExpressionUnevaluated:
  750. HasActiveDiagnostic = false;
  751. return OptionalDiagnostic();
  752. }
  753. }
  754. unsigned CallStackNotes = CallStackDepth - 1;
  755. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  756. if (Limit)
  757. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  758. if (checkingPotentialConstantExpression())
  759. CallStackNotes = 0;
  760. HasActiveDiagnostic = true;
  761. HasFoldFailureDiagnostic = !IsCCEDiag;
  762. EvalStatus.Diag->clear();
  763. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  764. addDiag(Loc, DiagId);
  765. if (!checkingPotentialConstantExpression())
  766. addCallStack(Limit);
  767. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  768. }
  769. HasActiveDiagnostic = false;
  770. return OptionalDiagnostic();
  771. }
  772. public:
  773. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  774. OptionalDiagnostic
  775. FFDiag(SourceLocation Loc,
  776. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  777. unsigned ExtraNotes = 0) {
  778. return Diag(Loc, DiagId, ExtraNotes, false);
  779. }
  780. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  781. = diag::note_invalid_subexpr_in_const_expr,
  782. unsigned ExtraNotes = 0) {
  783. if (EvalStatus.Diag)
  784. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  785. HasActiveDiagnostic = false;
  786. return OptionalDiagnostic();
  787. }
  788. /// Diagnose that the evaluation does not produce a C++11 core constant
  789. /// expression.
  790. ///
  791. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  792. /// EM_PotentialConstantExpression mode and we produce one of these.
  793. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  794. = diag::note_invalid_subexpr_in_const_expr,
  795. unsigned ExtraNotes = 0) {
  796. // Don't override a previous diagnostic. Don't bother collecting
  797. // diagnostics if we're evaluating for overflow.
  798. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  799. HasActiveDiagnostic = false;
  800. return OptionalDiagnostic();
  801. }
  802. return Diag(Loc, DiagId, ExtraNotes, true);
  803. }
  804. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  805. = diag::note_invalid_subexpr_in_const_expr,
  806. unsigned ExtraNotes = 0) {
  807. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  808. }
  809. /// Add a note to a prior diagnostic.
  810. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  811. if (!HasActiveDiagnostic)
  812. return OptionalDiagnostic();
  813. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  814. }
  815. /// Add a stack of notes to a prior diagnostic.
  816. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  817. if (HasActiveDiagnostic) {
  818. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  819. Diags.begin(), Diags.end());
  820. }
  821. }
  822. /// Should we continue evaluation after encountering a side-effect that we
  823. /// couldn't model?
  824. bool keepEvaluatingAfterSideEffect() {
  825. switch (EvalMode) {
  826. case EM_PotentialConstantExpression:
  827. case EM_PotentialConstantExpressionUnevaluated:
  828. case EM_EvaluateForOverflow:
  829. case EM_IgnoreSideEffects:
  830. return true;
  831. case EM_ConstantExpression:
  832. case EM_ConstantExpressionUnevaluated:
  833. case EM_ConstantFold:
  834. return false;
  835. }
  836. llvm_unreachable("Missed EvalMode case");
  837. }
  838. /// Note that we have had a side-effect, and determine whether we should
  839. /// keep evaluating.
  840. bool noteSideEffect() {
  841. EvalStatus.HasSideEffects = true;
  842. return keepEvaluatingAfterSideEffect();
  843. }
  844. /// Should we continue evaluation after encountering undefined behavior?
  845. bool keepEvaluatingAfterUndefinedBehavior() {
  846. switch (EvalMode) {
  847. case EM_EvaluateForOverflow:
  848. case EM_IgnoreSideEffects:
  849. case EM_ConstantFold:
  850. return true;
  851. case EM_PotentialConstantExpression:
  852. case EM_PotentialConstantExpressionUnevaluated:
  853. case EM_ConstantExpression:
  854. case EM_ConstantExpressionUnevaluated:
  855. return false;
  856. }
  857. llvm_unreachable("Missed EvalMode case");
  858. }
  859. /// Note that we hit something that was technically undefined behavior, but
  860. /// that we can evaluate past it (such as signed overflow or floating-point
  861. /// division by zero.)
  862. bool noteUndefinedBehavior() {
  863. EvalStatus.HasUndefinedBehavior = true;
  864. return keepEvaluatingAfterUndefinedBehavior();
  865. }
  866. /// Should we continue evaluation as much as possible after encountering a
  867. /// construct which can't be reduced to a value?
  868. bool keepEvaluatingAfterFailure() {
  869. if (!StepsLeft)
  870. return false;
  871. switch (EvalMode) {
  872. case EM_PotentialConstantExpression:
  873. case EM_PotentialConstantExpressionUnevaluated:
  874. case EM_EvaluateForOverflow:
  875. return true;
  876. case EM_ConstantExpression:
  877. case EM_ConstantExpressionUnevaluated:
  878. case EM_ConstantFold:
  879. case EM_IgnoreSideEffects:
  880. return false;
  881. }
  882. llvm_unreachable("Missed EvalMode case");
  883. }
  884. /// Notes that we failed to evaluate an expression that other expressions
  885. /// directly depend on, and determine if we should keep evaluating. This
  886. /// should only be called if we actually intend to keep evaluating.
  887. ///
  888. /// Call noteSideEffect() instead if we may be able to ignore the value that
  889. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  890. ///
  891. /// (Foo(), 1) // use noteSideEffect
  892. /// (Foo() || true) // use noteSideEffect
  893. /// Foo() + 1 // use noteFailure
  894. LLVM_NODISCARD bool noteFailure() {
  895. // Failure when evaluating some expression often means there is some
  896. // subexpression whose evaluation was skipped. Therefore, (because we
  897. // don't track whether we skipped an expression when unwinding after an
  898. // evaluation failure) every evaluation failure that bubbles up from a
  899. // subexpression implies that a side-effect has potentially happened. We
  900. // skip setting the HasSideEffects flag to true until we decide to
  901. // continue evaluating after that point, which happens here.
  902. bool KeepGoing = keepEvaluatingAfterFailure();
  903. EvalStatus.HasSideEffects |= KeepGoing;
  904. return KeepGoing;
  905. }
  906. class ArrayInitLoopIndex {
  907. EvalInfo &Info;
  908. uint64_t OuterIndex;
  909. public:
  910. ArrayInitLoopIndex(EvalInfo &Info)
  911. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  912. Info.ArrayInitIndex = 0;
  913. }
  914. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  915. operator uint64_t&() { return Info.ArrayInitIndex; }
  916. };
  917. };
  918. /// Object used to treat all foldable expressions as constant expressions.
  919. struct FoldConstant {
  920. EvalInfo &Info;
  921. bool Enabled;
  922. bool HadNoPriorDiags;
  923. EvalInfo::EvaluationMode OldMode;
  924. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  925. : Info(Info),
  926. Enabled(Enabled),
  927. HadNoPriorDiags(Info.EvalStatus.Diag &&
  928. Info.EvalStatus.Diag->empty() &&
  929. !Info.EvalStatus.HasSideEffects),
  930. OldMode(Info.EvalMode) {
  931. if (Enabled &&
  932. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  933. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  934. Info.EvalMode = EvalInfo::EM_ConstantFold;
  935. }
  936. void keepDiagnostics() { Enabled = false; }
  937. ~FoldConstant() {
  938. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  939. !Info.EvalStatus.HasSideEffects)
  940. Info.EvalStatus.Diag->clear();
  941. Info.EvalMode = OldMode;
  942. }
  943. };
  944. /// RAII object used to set the current evaluation mode to ignore
  945. /// side-effects.
  946. struct IgnoreSideEffectsRAII {
  947. EvalInfo &Info;
  948. EvalInfo::EvaluationMode OldMode;
  949. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  950. : Info(Info), OldMode(Info.EvalMode) {
  951. if (!Info.checkingPotentialConstantExpression())
  952. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  953. }
  954. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  955. };
  956. /// RAII object used to optionally suppress diagnostics and side-effects from
  957. /// a speculative evaluation.
  958. class SpeculativeEvaluationRAII {
  959. EvalInfo *Info = nullptr;
  960. Expr::EvalStatus OldStatus;
  961. bool OldIsSpeculativelyEvaluating;
  962. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  963. Info = Other.Info;
  964. OldStatus = Other.OldStatus;
  965. OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
  966. Other.Info = nullptr;
  967. }
  968. void maybeRestoreState() {
  969. if (!Info)
  970. return;
  971. Info->EvalStatus = OldStatus;
  972. Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
  973. }
  974. public:
  975. SpeculativeEvaluationRAII() = default;
  976. SpeculativeEvaluationRAII(
  977. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  978. : Info(&Info), OldStatus(Info.EvalStatus),
  979. OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
  980. Info.EvalStatus.Diag = NewDiag;
  981. Info.IsSpeculativelyEvaluating = true;
  982. }
  983. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  984. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  985. moveFromAndCancel(std::move(Other));
  986. }
  987. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  988. maybeRestoreState();
  989. moveFromAndCancel(std::move(Other));
  990. return *this;
  991. }
  992. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  993. };
  994. /// RAII object wrapping a full-expression or block scope, and handling
  995. /// the ending of the lifetime of temporaries created within it.
  996. template<bool IsFullExpression>
  997. class ScopeRAII {
  998. EvalInfo &Info;
  999. unsigned OldStackSize;
  1000. public:
  1001. ScopeRAII(EvalInfo &Info)
  1002. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1003. // Push a new temporary version. This is needed to distinguish between
  1004. // temporaries created in different iterations of a loop.
  1005. Info.CurrentCall->pushTempVersion();
  1006. }
  1007. ~ScopeRAII() {
  1008. // Body moved to a static method to encourage the compiler to inline away
  1009. // instances of this class.
  1010. cleanup(Info, OldStackSize);
  1011. Info.CurrentCall->popTempVersion();
  1012. }
  1013. private:
  1014. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1015. unsigned NewEnd = OldStackSize;
  1016. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1017. I != N; ++I) {
  1018. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1019. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1020. // to do, just move this cleanup to the right place in the stack.
  1021. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1022. ++NewEnd;
  1023. } else {
  1024. // End the lifetime of the object.
  1025. Info.CleanupStack[I].endLifetime();
  1026. }
  1027. }
  1028. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1029. Info.CleanupStack.end());
  1030. }
  1031. };
  1032. typedef ScopeRAII<false> BlockScopeRAII;
  1033. typedef ScopeRAII<true> FullExpressionRAII;
  1034. }
  1035. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1036. CheckSubobjectKind CSK) {
  1037. if (Invalid)
  1038. return false;
  1039. if (isOnePastTheEnd()) {
  1040. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1041. << CSK;
  1042. setInvalid();
  1043. return false;
  1044. }
  1045. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1046. // must actually be at least one array element; even a VLA cannot have a
  1047. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1048. return true;
  1049. }
  1050. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1051. const Expr *E) {
  1052. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1053. // Do not set the designator as invalid: we can represent this situation,
  1054. // and correct handling of __builtin_object_size requires us to do so.
  1055. }
  1056. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1057. const Expr *E,
  1058. const APSInt &N) {
  1059. // If we're complaining, we must be able to statically determine the size of
  1060. // the most derived array.
  1061. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1062. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1063. << N << /*array*/ 0
  1064. << static_cast<unsigned>(getMostDerivedArraySize());
  1065. else
  1066. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1067. << N << /*non-array*/ 1;
  1068. setInvalid();
  1069. }
  1070. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1071. const FunctionDecl *Callee, const LValue *This,
  1072. APValue *Arguments)
  1073. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1074. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1075. Info.CurrentCall = this;
  1076. ++Info.CallStackDepth;
  1077. }
  1078. CallStackFrame::~CallStackFrame() {
  1079. assert(Info.CurrentCall == this && "calls retired out of order");
  1080. --Info.CallStackDepth;
  1081. Info.CurrentCall = Caller;
  1082. }
  1083. APValue &CallStackFrame::createTemporary(const void *Key,
  1084. bool IsLifetimeExtended) {
  1085. unsigned Version = Info.CurrentCall->getTempVersion();
  1086. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1087. assert(Result.isUninit() && "temporary created multiple times");
  1088. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1089. return Result;
  1090. }
  1091. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1092. void EvalInfo::addCallStack(unsigned Limit) {
  1093. // Determine which calls to skip, if any.
  1094. unsigned ActiveCalls = CallStackDepth - 1;
  1095. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1096. if (Limit && Limit < ActiveCalls) {
  1097. SkipStart = Limit / 2 + Limit % 2;
  1098. SkipEnd = ActiveCalls - Limit / 2;
  1099. }
  1100. // Walk the call stack and add the diagnostics.
  1101. unsigned CallIdx = 0;
  1102. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1103. Frame = Frame->Caller, ++CallIdx) {
  1104. // Skip this call?
  1105. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1106. if (CallIdx == SkipStart) {
  1107. // Note that we're skipping calls.
  1108. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1109. << unsigned(ActiveCalls - Limit);
  1110. }
  1111. continue;
  1112. }
  1113. // Use a different note for an inheriting constructor, because from the
  1114. // user's perspective it's not really a function at all.
  1115. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1116. if (CD->isInheritingConstructor()) {
  1117. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1118. << CD->getParent();
  1119. continue;
  1120. }
  1121. }
  1122. SmallVector<char, 128> Buffer;
  1123. llvm::raw_svector_ostream Out(Buffer);
  1124. describeCall(Frame, Out);
  1125. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1126. }
  1127. }
  1128. namespace {
  1129. struct ComplexValue {
  1130. private:
  1131. bool IsInt;
  1132. public:
  1133. APSInt IntReal, IntImag;
  1134. APFloat FloatReal, FloatImag;
  1135. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1136. void makeComplexFloat() { IsInt = false; }
  1137. bool isComplexFloat() const { return !IsInt; }
  1138. APFloat &getComplexFloatReal() { return FloatReal; }
  1139. APFloat &getComplexFloatImag() { return FloatImag; }
  1140. void makeComplexInt() { IsInt = true; }
  1141. bool isComplexInt() const { return IsInt; }
  1142. APSInt &getComplexIntReal() { return IntReal; }
  1143. APSInt &getComplexIntImag() { return IntImag; }
  1144. void moveInto(APValue &v) const {
  1145. if (isComplexFloat())
  1146. v = APValue(FloatReal, FloatImag);
  1147. else
  1148. v = APValue(IntReal, IntImag);
  1149. }
  1150. void setFrom(const APValue &v) {
  1151. assert(v.isComplexFloat() || v.isComplexInt());
  1152. if (v.isComplexFloat()) {
  1153. makeComplexFloat();
  1154. FloatReal = v.getComplexFloatReal();
  1155. FloatImag = v.getComplexFloatImag();
  1156. } else {
  1157. makeComplexInt();
  1158. IntReal = v.getComplexIntReal();
  1159. IntImag = v.getComplexIntImag();
  1160. }
  1161. }
  1162. };
  1163. struct LValue {
  1164. APValue::LValueBase Base;
  1165. CharUnits Offset;
  1166. SubobjectDesignator Designator;
  1167. bool IsNullPtr : 1;
  1168. bool InvalidBase : 1;
  1169. const APValue::LValueBase getLValueBase() const { return Base; }
  1170. CharUnits &getLValueOffset() { return Offset; }
  1171. const CharUnits &getLValueOffset() const { return Offset; }
  1172. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1173. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1174. bool isNullPointer() const { return IsNullPtr;}
  1175. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1176. unsigned getLValueVersion() const { return Base.getVersion(); }
  1177. void moveInto(APValue &V) const {
  1178. if (Designator.Invalid)
  1179. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1180. else {
  1181. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1182. V = APValue(Base, Offset, Designator.Entries,
  1183. Designator.IsOnePastTheEnd, IsNullPtr);
  1184. }
  1185. }
  1186. void setFrom(ASTContext &Ctx, const APValue &V) {
  1187. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1188. Base = V.getLValueBase();
  1189. Offset = V.getLValueOffset();
  1190. InvalidBase = false;
  1191. Designator = SubobjectDesignator(Ctx, V);
  1192. IsNullPtr = V.isNullPointer();
  1193. }
  1194. void set(APValue::LValueBase B, bool BInvalid = false) {
  1195. #ifndef NDEBUG
  1196. // We only allow a few types of invalid bases. Enforce that here.
  1197. if (BInvalid) {
  1198. const auto *E = B.get<const Expr *>();
  1199. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1200. "Unexpected type of invalid base");
  1201. }
  1202. #endif
  1203. Base = B;
  1204. Offset = CharUnits::fromQuantity(0);
  1205. InvalidBase = BInvalid;
  1206. Designator = SubobjectDesignator(getType(B));
  1207. IsNullPtr = false;
  1208. }
  1209. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1210. Base = (Expr *)nullptr;
  1211. Offset = CharUnits::fromQuantity(TargetVal);
  1212. InvalidBase = false;
  1213. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1214. IsNullPtr = true;
  1215. }
  1216. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1217. set(B, true);
  1218. }
  1219. // Check that this LValue is not based on a null pointer. If it is, produce
  1220. // a diagnostic and mark the designator as invalid.
  1221. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1222. CheckSubobjectKind CSK) {
  1223. if (Designator.Invalid)
  1224. return false;
  1225. if (IsNullPtr) {
  1226. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  1227. << CSK;
  1228. Designator.setInvalid();
  1229. return false;
  1230. }
  1231. return true;
  1232. }
  1233. // Check this LValue refers to an object. If not, set the designator to be
  1234. // invalid and emit a diagnostic.
  1235. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1236. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1237. Designator.checkSubobject(Info, E, CSK);
  1238. }
  1239. void addDecl(EvalInfo &Info, const Expr *E,
  1240. const Decl *D, bool Virtual = false) {
  1241. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1242. Designator.addDeclUnchecked(D, Virtual);
  1243. }
  1244. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1245. if (!Designator.Entries.empty()) {
  1246. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1247. Designator.setInvalid();
  1248. return;
  1249. }
  1250. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1251. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1252. Designator.FirstEntryIsAnUnsizedArray = true;
  1253. Designator.addUnsizedArrayUnchecked(ElemTy);
  1254. }
  1255. }
  1256. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1257. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1258. Designator.addArrayUnchecked(CAT);
  1259. }
  1260. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1261. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1262. Designator.addComplexUnchecked(EltTy, Imag);
  1263. }
  1264. void clearIsNullPointer() {
  1265. IsNullPtr = false;
  1266. }
  1267. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1268. const APSInt &Index, CharUnits ElementSize) {
  1269. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1270. // but we're not required to diagnose it and it's valid in C++.)
  1271. if (!Index)
  1272. return;
  1273. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1274. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1275. // offsets.
  1276. uint64_t Offset64 = Offset.getQuantity();
  1277. uint64_t ElemSize64 = ElementSize.getQuantity();
  1278. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1279. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1280. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1281. Designator.adjustIndex(Info, E, Index);
  1282. clearIsNullPointer();
  1283. }
  1284. void adjustOffset(CharUnits N) {
  1285. Offset += N;
  1286. if (N.getQuantity())
  1287. clearIsNullPointer();
  1288. }
  1289. };
  1290. struct MemberPtr {
  1291. MemberPtr() {}
  1292. explicit MemberPtr(const ValueDecl *Decl) :
  1293. DeclAndIsDerivedMember(Decl, false), Path() {}
  1294. /// The member or (direct or indirect) field referred to by this member
  1295. /// pointer, or 0 if this is a null member pointer.
  1296. const ValueDecl *getDecl() const {
  1297. return DeclAndIsDerivedMember.getPointer();
  1298. }
  1299. /// Is this actually a member of some type derived from the relevant class?
  1300. bool isDerivedMember() const {
  1301. return DeclAndIsDerivedMember.getInt();
  1302. }
  1303. /// Get the class which the declaration actually lives in.
  1304. const CXXRecordDecl *getContainingRecord() const {
  1305. return cast<CXXRecordDecl>(
  1306. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1307. }
  1308. void moveInto(APValue &V) const {
  1309. V = APValue(getDecl(), isDerivedMember(), Path);
  1310. }
  1311. void setFrom(const APValue &V) {
  1312. assert(V.isMemberPointer());
  1313. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1314. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1315. Path.clear();
  1316. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1317. Path.insert(Path.end(), P.begin(), P.end());
  1318. }
  1319. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1320. /// whether the member is a member of some class derived from the class type
  1321. /// of the member pointer.
  1322. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1323. /// Path - The path of base/derived classes from the member declaration's
  1324. /// class (exclusive) to the class type of the member pointer (inclusive).
  1325. SmallVector<const CXXRecordDecl*, 4> Path;
  1326. /// Perform a cast towards the class of the Decl (either up or down the
  1327. /// hierarchy).
  1328. bool castBack(const CXXRecordDecl *Class) {
  1329. assert(!Path.empty());
  1330. const CXXRecordDecl *Expected;
  1331. if (Path.size() >= 2)
  1332. Expected = Path[Path.size() - 2];
  1333. else
  1334. Expected = getContainingRecord();
  1335. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1336. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1337. // if B does not contain the original member and is not a base or
  1338. // derived class of the class containing the original member, the result
  1339. // of the cast is undefined.
  1340. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1341. // (D::*). We consider that to be a language defect.
  1342. return false;
  1343. }
  1344. Path.pop_back();
  1345. return true;
  1346. }
  1347. /// Perform a base-to-derived member pointer cast.
  1348. bool castToDerived(const CXXRecordDecl *Derived) {
  1349. if (!getDecl())
  1350. return true;
  1351. if (!isDerivedMember()) {
  1352. Path.push_back(Derived);
  1353. return true;
  1354. }
  1355. if (!castBack(Derived))
  1356. return false;
  1357. if (Path.empty())
  1358. DeclAndIsDerivedMember.setInt(false);
  1359. return true;
  1360. }
  1361. /// Perform a derived-to-base member pointer cast.
  1362. bool castToBase(const CXXRecordDecl *Base) {
  1363. if (!getDecl())
  1364. return true;
  1365. if (Path.empty())
  1366. DeclAndIsDerivedMember.setInt(true);
  1367. if (isDerivedMember()) {
  1368. Path.push_back(Base);
  1369. return true;
  1370. }
  1371. return castBack(Base);
  1372. }
  1373. };
  1374. /// Compare two member pointers, which are assumed to be of the same type.
  1375. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1376. if (!LHS.getDecl() || !RHS.getDecl())
  1377. return !LHS.getDecl() && !RHS.getDecl();
  1378. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1379. return false;
  1380. return LHS.Path == RHS.Path;
  1381. }
  1382. }
  1383. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1384. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1385. const LValue &This, const Expr *E,
  1386. bool AllowNonLiteralTypes = false);
  1387. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1388. bool InvalidBaseOK = false);
  1389. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1390. bool InvalidBaseOK = false);
  1391. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1392. EvalInfo &Info);
  1393. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1394. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1395. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1396. EvalInfo &Info);
  1397. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1398. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1399. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1400. EvalInfo &Info);
  1401. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1402. //===----------------------------------------------------------------------===//
  1403. // Misc utilities
  1404. //===----------------------------------------------------------------------===//
  1405. /// A helper function to create a temporary and set an LValue.
  1406. template <class KeyTy>
  1407. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1408. LValue &LV, CallStackFrame &Frame) {
  1409. LV.set({Key, Frame.Info.CurrentCall->Index,
  1410. Frame.Info.CurrentCall->getTempVersion()});
  1411. return Frame.createTemporary(Key, IsLifetimeExtended);
  1412. }
  1413. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1414. /// preserving its value (by extending by up to one bit as needed).
  1415. static void negateAsSigned(APSInt &Int) {
  1416. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1417. Int = Int.extend(Int.getBitWidth() + 1);
  1418. Int.setIsSigned(true);
  1419. }
  1420. Int = -Int;
  1421. }
  1422. /// Produce a string describing the given constexpr call.
  1423. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1424. unsigned ArgIndex = 0;
  1425. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1426. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1427. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1428. if (!IsMemberCall)
  1429. Out << *Frame->Callee << '(';
  1430. if (Frame->This && IsMemberCall) {
  1431. APValue Val;
  1432. Frame->This->moveInto(Val);
  1433. Val.printPretty(Out, Frame->Info.Ctx,
  1434. Frame->This->Designator.MostDerivedType);
  1435. // FIXME: Add parens around Val if needed.
  1436. Out << "->" << *Frame->Callee << '(';
  1437. IsMemberCall = false;
  1438. }
  1439. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1440. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1441. if (ArgIndex > (unsigned)IsMemberCall)
  1442. Out << ", ";
  1443. const ParmVarDecl *Param = *I;
  1444. const APValue &Arg = Frame->Arguments[ArgIndex];
  1445. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1446. if (ArgIndex == 0 && IsMemberCall)
  1447. Out << "->" << *Frame->Callee << '(';
  1448. }
  1449. Out << ')';
  1450. }
  1451. /// Evaluate an expression to see if it had side-effects, and discard its
  1452. /// result.
  1453. /// \return \c true if the caller should keep evaluating.
  1454. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1455. APValue Scratch;
  1456. if (!Evaluate(Scratch, Info, E))
  1457. // We don't need the value, but we might have skipped a side effect here.
  1458. return Info.noteSideEffect();
  1459. return true;
  1460. }
  1461. /// Should this call expression be treated as a string literal?
  1462. static bool IsStringLiteralCall(const CallExpr *E) {
  1463. unsigned Builtin = E->getBuiltinCallee();
  1464. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1465. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1466. }
  1467. static bool IsGlobalLValue(APValue::LValueBase B) {
  1468. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1469. // constant expression of pointer type that evaluates to...
  1470. // ... a null pointer value, or a prvalue core constant expression of type
  1471. // std::nullptr_t.
  1472. if (!B) return true;
  1473. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1474. // ... the address of an object with static storage duration,
  1475. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1476. return VD->hasGlobalStorage();
  1477. // ... the address of a function,
  1478. return isa<FunctionDecl>(D);
  1479. }
  1480. const Expr *E = B.get<const Expr*>();
  1481. switch (E->getStmtClass()) {
  1482. default:
  1483. return false;
  1484. case Expr::CompoundLiteralExprClass: {
  1485. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1486. return CLE->isFileScope() && CLE->isLValue();
  1487. }
  1488. case Expr::MaterializeTemporaryExprClass:
  1489. // A materialized temporary might have been lifetime-extended to static
  1490. // storage duration.
  1491. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1492. // A string literal has static storage duration.
  1493. case Expr::StringLiteralClass:
  1494. case Expr::PredefinedExprClass:
  1495. case Expr::ObjCStringLiteralClass:
  1496. case Expr::ObjCEncodeExprClass:
  1497. case Expr::CXXTypeidExprClass:
  1498. case Expr::CXXUuidofExprClass:
  1499. return true;
  1500. case Expr::CallExprClass:
  1501. return IsStringLiteralCall(cast<CallExpr>(E));
  1502. // For GCC compatibility, &&label has static storage duration.
  1503. case Expr::AddrLabelExprClass:
  1504. return true;
  1505. // A Block literal expression may be used as the initialization value for
  1506. // Block variables at global or local static scope.
  1507. case Expr::BlockExprClass:
  1508. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1509. case Expr::ImplicitValueInitExprClass:
  1510. // FIXME:
  1511. // We can never form an lvalue with an implicit value initialization as its
  1512. // base through expression evaluation, so these only appear in one case: the
  1513. // implicit variable declaration we invent when checking whether a constexpr
  1514. // constructor can produce a constant expression. We must assume that such
  1515. // an expression might be a global lvalue.
  1516. return true;
  1517. }
  1518. }
  1519. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1520. return LVal.Base.dyn_cast<const ValueDecl*>();
  1521. }
  1522. static bool IsLiteralLValue(const LValue &Value) {
  1523. if (Value.getLValueCallIndex())
  1524. return false;
  1525. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1526. return E && !isa<MaterializeTemporaryExpr>(E);
  1527. }
  1528. static bool IsWeakLValue(const LValue &Value) {
  1529. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1530. return Decl && Decl->isWeak();
  1531. }
  1532. static bool isZeroSized(const LValue &Value) {
  1533. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1534. if (Decl && isa<VarDecl>(Decl)) {
  1535. QualType Ty = Decl->getType();
  1536. if (Ty->isArrayType())
  1537. return Ty->isIncompleteType() ||
  1538. Decl->getASTContext().getTypeSize(Ty) == 0;
  1539. }
  1540. return false;
  1541. }
  1542. static bool HasSameBase(const LValue &A, const LValue &B) {
  1543. if (!A.getLValueBase())
  1544. return !B.getLValueBase();
  1545. if (!B.getLValueBase())
  1546. return false;
  1547. if (A.getLValueBase().getOpaqueValue() !=
  1548. B.getLValueBase().getOpaqueValue()) {
  1549. const Decl *ADecl = GetLValueBaseDecl(A);
  1550. if (!ADecl)
  1551. return false;
  1552. const Decl *BDecl = GetLValueBaseDecl(B);
  1553. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1554. return false;
  1555. }
  1556. return IsGlobalLValue(A.getLValueBase()) ||
  1557. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1558. A.getLValueVersion() == B.getLValueVersion());
  1559. }
  1560. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1561. assert(Base && "no location for a null lvalue");
  1562. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1563. if (VD)
  1564. Info.Note(VD->getLocation(), diag::note_declared_at);
  1565. else
  1566. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1567. diag::note_constexpr_temporary_here);
  1568. }
  1569. /// Check that this reference or pointer core constant expression is a valid
  1570. /// value for an address or reference constant expression. Return true if we
  1571. /// can fold this expression, whether or not it's a constant expression.
  1572. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1573. QualType Type, const LValue &LVal,
  1574. Expr::ConstExprUsage Usage) {
  1575. bool IsReferenceType = Type->isReferenceType();
  1576. APValue::LValueBase Base = LVal.getLValueBase();
  1577. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1578. // Check that the object is a global. Note that the fake 'this' object we
  1579. // manufacture when checking potential constant expressions is conservatively
  1580. // assumed to be global here.
  1581. if (!IsGlobalLValue(Base)) {
  1582. if (Info.getLangOpts().CPlusPlus11) {
  1583. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1584. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1585. << IsReferenceType << !Designator.Entries.empty()
  1586. << !!VD << VD;
  1587. NoteLValueLocation(Info, Base);
  1588. } else {
  1589. Info.FFDiag(Loc);
  1590. }
  1591. // Don't allow references to temporaries to escape.
  1592. return false;
  1593. }
  1594. assert((Info.checkingPotentialConstantExpression() ||
  1595. LVal.getLValueCallIndex() == 0) &&
  1596. "have call index for global lvalue");
  1597. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1598. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1599. // Check if this is a thread-local variable.
  1600. if (Var->getTLSKind())
  1601. return false;
  1602. // A dllimport variable never acts like a constant.
  1603. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1604. return false;
  1605. }
  1606. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1607. // __declspec(dllimport) must be handled very carefully:
  1608. // We must never initialize an expression with the thunk in C++.
  1609. // Doing otherwise would allow the same id-expression to yield
  1610. // different addresses for the same function in different translation
  1611. // units. However, this means that we must dynamically initialize the
  1612. // expression with the contents of the import address table at runtime.
  1613. //
  1614. // The C language has no notion of ODR; furthermore, it has no notion of
  1615. // dynamic initialization. This means that we are permitted to
  1616. // perform initialization with the address of the thunk.
  1617. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1618. FD->hasAttr<DLLImportAttr>())
  1619. return false;
  1620. }
  1621. }
  1622. // Allow address constant expressions to be past-the-end pointers. This is
  1623. // an extension: the standard requires them to point to an object.
  1624. if (!IsReferenceType)
  1625. return true;
  1626. // A reference constant expression must refer to an object.
  1627. if (!Base) {
  1628. // FIXME: diagnostic
  1629. Info.CCEDiag(Loc);
  1630. return true;
  1631. }
  1632. // Does this refer one past the end of some object?
  1633. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1634. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1635. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1636. << !Designator.Entries.empty() << !!VD << VD;
  1637. NoteLValueLocation(Info, Base);
  1638. }
  1639. return true;
  1640. }
  1641. /// Member pointers are constant expressions unless they point to a
  1642. /// non-virtual dllimport member function.
  1643. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1644. SourceLocation Loc,
  1645. QualType Type,
  1646. const APValue &Value,
  1647. Expr::ConstExprUsage Usage) {
  1648. const ValueDecl *Member = Value.getMemberPointerDecl();
  1649. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1650. if (!FD)
  1651. return true;
  1652. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1653. !FD->hasAttr<DLLImportAttr>();
  1654. }
  1655. /// Check that this core constant expression is of literal type, and if not,
  1656. /// produce an appropriate diagnostic.
  1657. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1658. const LValue *This = nullptr) {
  1659. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1660. return true;
  1661. // C++1y: A constant initializer for an object o [...] may also invoke
  1662. // constexpr constructors for o and its subobjects even if those objects
  1663. // are of non-literal class types.
  1664. //
  1665. // C++11 missed this detail for aggregates, so classes like this:
  1666. // struct foo_t { union { int i; volatile int j; } u; };
  1667. // are not (obviously) initializable like so:
  1668. // __attribute__((__require_constant_initialization__))
  1669. // static const foo_t x = {{0}};
  1670. // because "i" is a subobject with non-literal initialization (due to the
  1671. // volatile member of the union). See:
  1672. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1673. // Therefore, we use the C++1y behavior.
  1674. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1675. return true;
  1676. // Prvalue constant expressions must be of literal types.
  1677. if (Info.getLangOpts().CPlusPlus11)
  1678. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1679. << E->getType();
  1680. else
  1681. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1682. return false;
  1683. }
  1684. /// Check that this core constant expression value is a valid value for a
  1685. /// constant expression. If not, report an appropriate diagnostic. Does not
  1686. /// check that the expression is of literal type.
  1687. static bool
  1688. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1689. const APValue &Value,
  1690. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1691. if (Value.isUninit()) {
  1692. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1693. << true << Type;
  1694. return false;
  1695. }
  1696. // We allow _Atomic(T) to be initialized from anything that T can be
  1697. // initialized from.
  1698. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1699. Type = AT->getValueType();
  1700. // Core issue 1454: For a literal constant expression of array or class type,
  1701. // each subobject of its value shall have been initialized by a constant
  1702. // expression.
  1703. if (Value.isArray()) {
  1704. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1705. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1706. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1707. Value.getArrayInitializedElt(I), Usage))
  1708. return false;
  1709. }
  1710. if (!Value.hasArrayFiller())
  1711. return true;
  1712. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1713. Usage);
  1714. }
  1715. if (Value.isUnion() && Value.getUnionField()) {
  1716. return CheckConstantExpression(Info, DiagLoc,
  1717. Value.getUnionField()->getType(),
  1718. Value.getUnionValue(), Usage);
  1719. }
  1720. if (Value.isStruct()) {
  1721. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1722. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1723. unsigned BaseIndex = 0;
  1724. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1725. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1726. Value.getStructBase(BaseIndex), Usage))
  1727. return false;
  1728. ++BaseIndex;
  1729. }
  1730. }
  1731. for (const auto *I : RD->fields()) {
  1732. if (I->isUnnamedBitfield())
  1733. continue;
  1734. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1735. Value.getStructField(I->getFieldIndex()),
  1736. Usage))
  1737. return false;
  1738. }
  1739. }
  1740. if (Value.isLValue()) {
  1741. LValue LVal;
  1742. LVal.setFrom(Info.Ctx, Value);
  1743. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1744. }
  1745. if (Value.isMemberPointer())
  1746. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1747. // Everything else is fine.
  1748. return true;
  1749. }
  1750. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1751. // A null base expression indicates a null pointer. These are always
  1752. // evaluatable, and they are false unless the offset is zero.
  1753. if (!Value.getLValueBase()) {
  1754. Result = !Value.getLValueOffset().isZero();
  1755. return true;
  1756. }
  1757. // We have a non-null base. These are generally known to be true, but if it's
  1758. // a weak declaration it can be null at runtime.
  1759. Result = true;
  1760. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1761. return !Decl || !Decl->isWeak();
  1762. }
  1763. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1764. switch (Val.getKind()) {
  1765. case APValue::Uninitialized:
  1766. return false;
  1767. case APValue::Int:
  1768. Result = Val.getInt().getBoolValue();
  1769. return true;
  1770. case APValue::Float:
  1771. Result = !Val.getFloat().isZero();
  1772. return true;
  1773. case APValue::ComplexInt:
  1774. Result = Val.getComplexIntReal().getBoolValue() ||
  1775. Val.getComplexIntImag().getBoolValue();
  1776. return true;
  1777. case APValue::ComplexFloat:
  1778. Result = !Val.getComplexFloatReal().isZero() ||
  1779. !Val.getComplexFloatImag().isZero();
  1780. return true;
  1781. case APValue::LValue:
  1782. return EvalPointerValueAsBool(Val, Result);
  1783. case APValue::MemberPointer:
  1784. Result = Val.getMemberPointerDecl();
  1785. return true;
  1786. case APValue::Vector:
  1787. case APValue::Array:
  1788. case APValue::Struct:
  1789. case APValue::Union:
  1790. case APValue::AddrLabelDiff:
  1791. return false;
  1792. }
  1793. llvm_unreachable("unknown APValue kind");
  1794. }
  1795. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1796. EvalInfo &Info) {
  1797. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1798. APValue Val;
  1799. if (!Evaluate(Val, Info, E))
  1800. return false;
  1801. return HandleConversionToBool(Val, Result);
  1802. }
  1803. template<typename T>
  1804. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1805. const T &SrcValue, QualType DestType) {
  1806. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1807. << SrcValue << DestType;
  1808. return Info.noteUndefinedBehavior();
  1809. }
  1810. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1811. QualType SrcType, const APFloat &Value,
  1812. QualType DestType, APSInt &Result) {
  1813. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1814. // Determine whether we are converting to unsigned or signed.
  1815. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1816. Result = APSInt(DestWidth, !DestSigned);
  1817. bool ignored;
  1818. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1819. & APFloat::opInvalidOp)
  1820. return HandleOverflow(Info, E, Value, DestType);
  1821. return true;
  1822. }
  1823. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1824. QualType SrcType, QualType DestType,
  1825. APFloat &Result) {
  1826. APFloat Value = Result;
  1827. bool ignored;
  1828. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1829. APFloat::rmNearestTiesToEven, &ignored)
  1830. & APFloat::opOverflow)
  1831. return HandleOverflow(Info, E, Value, DestType);
  1832. return true;
  1833. }
  1834. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1835. QualType DestType, QualType SrcType,
  1836. const APSInt &Value) {
  1837. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1838. APSInt Result = Value;
  1839. // Figure out if this is a truncate, extend or noop cast.
  1840. // If the input is signed, do a sign extend, noop, or truncate.
  1841. Result = Result.extOrTrunc(DestWidth);
  1842. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1843. return Result;
  1844. }
  1845. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1846. QualType SrcType, const APSInt &Value,
  1847. QualType DestType, APFloat &Result) {
  1848. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1849. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1850. APFloat::rmNearestTiesToEven)
  1851. & APFloat::opOverflow)
  1852. return HandleOverflow(Info, E, Value, DestType);
  1853. return true;
  1854. }
  1855. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1856. APValue &Value, const FieldDecl *FD) {
  1857. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1858. if (!Value.isInt()) {
  1859. // Trying to store a pointer-cast-to-integer into a bitfield.
  1860. // FIXME: In this case, we should provide the diagnostic for casting
  1861. // a pointer to an integer.
  1862. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1863. Info.FFDiag(E);
  1864. return false;
  1865. }
  1866. APSInt &Int = Value.getInt();
  1867. unsigned OldBitWidth = Int.getBitWidth();
  1868. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1869. if (NewBitWidth < OldBitWidth)
  1870. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1871. return true;
  1872. }
  1873. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1874. llvm::APInt &Res) {
  1875. APValue SVal;
  1876. if (!Evaluate(SVal, Info, E))
  1877. return false;
  1878. if (SVal.isInt()) {
  1879. Res = SVal.getInt();
  1880. return true;
  1881. }
  1882. if (SVal.isFloat()) {
  1883. Res = SVal.getFloat().bitcastToAPInt();
  1884. return true;
  1885. }
  1886. if (SVal.isVector()) {
  1887. QualType VecTy = E->getType();
  1888. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1889. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1890. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1891. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1892. Res = llvm::APInt::getNullValue(VecSize);
  1893. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1894. APValue &Elt = SVal.getVectorElt(i);
  1895. llvm::APInt EltAsInt;
  1896. if (Elt.isInt()) {
  1897. EltAsInt = Elt.getInt();
  1898. } else if (Elt.isFloat()) {
  1899. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1900. } else {
  1901. // Don't try to handle vectors of anything other than int or float
  1902. // (not sure if it's possible to hit this case).
  1903. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1904. return false;
  1905. }
  1906. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1907. if (BigEndian)
  1908. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1909. else
  1910. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1911. }
  1912. return true;
  1913. }
  1914. // Give up if the input isn't an int, float, or vector. For example, we
  1915. // reject "(v4i16)(intptr_t)&a".
  1916. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1917. return false;
  1918. }
  1919. /// Perform the given integer operation, which is known to need at most BitWidth
  1920. /// bits, and check for overflow in the original type (if that type was not an
  1921. /// unsigned type).
  1922. template<typename Operation>
  1923. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1924. const APSInt &LHS, const APSInt &RHS,
  1925. unsigned BitWidth, Operation Op,
  1926. APSInt &Result) {
  1927. if (LHS.isUnsigned()) {
  1928. Result = Op(LHS, RHS);
  1929. return true;
  1930. }
  1931. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1932. Result = Value.trunc(LHS.getBitWidth());
  1933. if (Result.extend(BitWidth) != Value) {
  1934. if (Info.checkingForOverflow())
  1935. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1936. diag::warn_integer_constant_overflow)
  1937. << Result.toString(10) << E->getType();
  1938. else
  1939. return HandleOverflow(Info, E, Value, E->getType());
  1940. }
  1941. return true;
  1942. }
  1943. /// Perform the given binary integer operation.
  1944. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1945. BinaryOperatorKind Opcode, APSInt RHS,
  1946. APSInt &Result) {
  1947. switch (Opcode) {
  1948. default:
  1949. Info.FFDiag(E);
  1950. return false;
  1951. case BO_Mul:
  1952. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1953. std::multiplies<APSInt>(), Result);
  1954. case BO_Add:
  1955. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1956. std::plus<APSInt>(), Result);
  1957. case BO_Sub:
  1958. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1959. std::minus<APSInt>(), Result);
  1960. case BO_And: Result = LHS & RHS; return true;
  1961. case BO_Xor: Result = LHS ^ RHS; return true;
  1962. case BO_Or: Result = LHS | RHS; return true;
  1963. case BO_Div:
  1964. case BO_Rem:
  1965. if (RHS == 0) {
  1966. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1967. return false;
  1968. }
  1969. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1970. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1971. // this operation and gives the two's complement result.
  1972. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1973. LHS.isSigned() && LHS.isMinSignedValue())
  1974. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1975. E->getType());
  1976. return true;
  1977. case BO_Shl: {
  1978. if (Info.getLangOpts().OpenCL)
  1979. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1980. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1981. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1982. RHS.isUnsigned());
  1983. else if (RHS.isSigned() && RHS.isNegative()) {
  1984. // During constant-folding, a negative shift is an opposite shift. Such
  1985. // a shift is not a constant expression.
  1986. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1987. RHS = -RHS;
  1988. goto shift_right;
  1989. }
  1990. shift_left:
  1991. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1992. // the shifted type.
  1993. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1994. if (SA != RHS) {
  1995. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1996. << RHS << E->getType() << LHS.getBitWidth();
  1997. } else if (LHS.isSigned()) {
  1998. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1999. // operand, and must not overflow the corresponding unsigned type.
  2000. if (LHS.isNegative())
  2001. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2002. else if (LHS.countLeadingZeros() < SA)
  2003. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2004. }
  2005. Result = LHS << SA;
  2006. return true;
  2007. }
  2008. case BO_Shr: {
  2009. if (Info.getLangOpts().OpenCL)
  2010. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2011. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2012. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2013. RHS.isUnsigned());
  2014. else if (RHS.isSigned() && RHS.isNegative()) {
  2015. // During constant-folding, a negative shift is an opposite shift. Such a
  2016. // shift is not a constant expression.
  2017. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2018. RHS = -RHS;
  2019. goto shift_left;
  2020. }
  2021. shift_right:
  2022. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2023. // shifted type.
  2024. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2025. if (SA != RHS)
  2026. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2027. << RHS << E->getType() << LHS.getBitWidth();
  2028. Result = LHS >> SA;
  2029. return true;
  2030. }
  2031. case BO_LT: Result = LHS < RHS; return true;
  2032. case BO_GT: Result = LHS > RHS; return true;
  2033. case BO_LE: Result = LHS <= RHS; return true;
  2034. case BO_GE: Result = LHS >= RHS; return true;
  2035. case BO_EQ: Result = LHS == RHS; return true;
  2036. case BO_NE: Result = LHS != RHS; return true;
  2037. case BO_Cmp:
  2038. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2039. }
  2040. }
  2041. /// Perform the given binary floating-point operation, in-place, on LHS.
  2042. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2043. APFloat &LHS, BinaryOperatorKind Opcode,
  2044. const APFloat &RHS) {
  2045. switch (Opcode) {
  2046. default:
  2047. Info.FFDiag(E);
  2048. return false;
  2049. case BO_Mul:
  2050. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2051. break;
  2052. case BO_Add:
  2053. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2054. break;
  2055. case BO_Sub:
  2056. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2057. break;
  2058. case BO_Div:
  2059. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2060. break;
  2061. }
  2062. if (LHS.isInfinity() || LHS.isNaN()) {
  2063. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2064. return Info.noteUndefinedBehavior();
  2065. }
  2066. return true;
  2067. }
  2068. /// Cast an lvalue referring to a base subobject to a derived class, by
  2069. /// truncating the lvalue's path to the given length.
  2070. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2071. const RecordDecl *TruncatedType,
  2072. unsigned TruncatedElements) {
  2073. SubobjectDesignator &D = Result.Designator;
  2074. // Check we actually point to a derived class object.
  2075. if (TruncatedElements == D.Entries.size())
  2076. return true;
  2077. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2078. "not casting to a derived class");
  2079. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2080. return false;
  2081. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2082. const RecordDecl *RD = TruncatedType;
  2083. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2084. if (RD->isInvalidDecl()) return false;
  2085. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2086. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2087. if (isVirtualBaseClass(D.Entries[I]))
  2088. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2089. else
  2090. Result.Offset -= Layout.getBaseClassOffset(Base);
  2091. RD = Base;
  2092. }
  2093. D.Entries.resize(TruncatedElements);
  2094. return true;
  2095. }
  2096. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2097. const CXXRecordDecl *Derived,
  2098. const CXXRecordDecl *Base,
  2099. const ASTRecordLayout *RL = nullptr) {
  2100. if (!RL) {
  2101. if (Derived->isInvalidDecl()) return false;
  2102. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2103. }
  2104. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2105. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2106. return true;
  2107. }
  2108. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2109. const CXXRecordDecl *DerivedDecl,
  2110. const CXXBaseSpecifier *Base) {
  2111. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2112. if (!Base->isVirtual())
  2113. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2114. SubobjectDesignator &D = Obj.Designator;
  2115. if (D.Invalid)
  2116. return false;
  2117. // Extract most-derived object and corresponding type.
  2118. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2119. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2120. return false;
  2121. // Find the virtual base class.
  2122. if (DerivedDecl->isInvalidDecl()) return false;
  2123. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2124. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2125. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2126. return true;
  2127. }
  2128. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2129. QualType Type, LValue &Result) {
  2130. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2131. PathE = E->path_end();
  2132. PathI != PathE; ++PathI) {
  2133. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2134. *PathI))
  2135. return false;
  2136. Type = (*PathI)->getType();
  2137. }
  2138. return true;
  2139. }
  2140. /// Update LVal to refer to the given field, which must be a member of the type
  2141. /// currently described by LVal.
  2142. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2143. const FieldDecl *FD,
  2144. const ASTRecordLayout *RL = nullptr) {
  2145. if (!RL) {
  2146. if (FD->getParent()->isInvalidDecl()) return false;
  2147. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2148. }
  2149. unsigned I = FD->getFieldIndex();
  2150. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2151. LVal.addDecl(Info, E, FD);
  2152. return true;
  2153. }
  2154. /// Update LVal to refer to the given indirect field.
  2155. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2156. LValue &LVal,
  2157. const IndirectFieldDecl *IFD) {
  2158. for (const auto *C : IFD->chain())
  2159. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2160. return false;
  2161. return true;
  2162. }
  2163. /// Get the size of the given type in char units.
  2164. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2165. QualType Type, CharUnits &Size) {
  2166. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2167. // extension.
  2168. if (Type->isVoidType() || Type->isFunctionType()) {
  2169. Size = CharUnits::One();
  2170. return true;
  2171. }
  2172. if (Type->isDependentType()) {
  2173. Info.FFDiag(Loc);
  2174. return false;
  2175. }
  2176. if (!Type->isConstantSizeType()) {
  2177. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2178. // FIXME: Better diagnostic.
  2179. Info.FFDiag(Loc);
  2180. return false;
  2181. }
  2182. Size = Info.Ctx.getTypeSizeInChars(Type);
  2183. return true;
  2184. }
  2185. /// Update a pointer value to model pointer arithmetic.
  2186. /// \param Info - Information about the ongoing evaluation.
  2187. /// \param E - The expression being evaluated, for diagnostic purposes.
  2188. /// \param LVal - The pointer value to be updated.
  2189. /// \param EltTy - The pointee type represented by LVal.
  2190. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2191. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2192. LValue &LVal, QualType EltTy,
  2193. APSInt Adjustment) {
  2194. CharUnits SizeOfPointee;
  2195. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2196. return false;
  2197. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2198. return true;
  2199. }
  2200. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2201. LValue &LVal, QualType EltTy,
  2202. int64_t Adjustment) {
  2203. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2204. APSInt::get(Adjustment));
  2205. }
  2206. /// Update an lvalue to refer to a component of a complex number.
  2207. /// \param Info - Information about the ongoing evaluation.
  2208. /// \param LVal - The lvalue to be updated.
  2209. /// \param EltTy - The complex number's component type.
  2210. /// \param Imag - False for the real component, true for the imaginary.
  2211. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2212. LValue &LVal, QualType EltTy,
  2213. bool Imag) {
  2214. if (Imag) {
  2215. CharUnits SizeOfComponent;
  2216. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2217. return false;
  2218. LVal.Offset += SizeOfComponent;
  2219. }
  2220. LVal.addComplex(Info, E, EltTy, Imag);
  2221. return true;
  2222. }
  2223. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2224. QualType Type, const LValue &LVal,
  2225. APValue &RVal);
  2226. /// Try to evaluate the initializer for a variable declaration.
  2227. ///
  2228. /// \param Info Information about the ongoing evaluation.
  2229. /// \param E An expression to be used when printing diagnostics.
  2230. /// \param VD The variable whose initializer should be obtained.
  2231. /// \param Frame The frame in which the variable was created. Must be null
  2232. /// if this variable is not local to the evaluation.
  2233. /// \param Result Filled in with a pointer to the value of the variable.
  2234. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2235. const VarDecl *VD, CallStackFrame *Frame,
  2236. APValue *&Result, const LValue *LVal) {
  2237. // If this is a parameter to an active constexpr function call, perform
  2238. // argument substitution.
  2239. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2240. // Assume arguments of a potential constant expression are unknown
  2241. // constant expressions.
  2242. if (Info.checkingPotentialConstantExpression())
  2243. return false;
  2244. if (!Frame || !Frame->Arguments) {
  2245. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2246. return false;
  2247. }
  2248. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2249. return true;
  2250. }
  2251. // If this is a local variable, dig out its value.
  2252. if (Frame) {
  2253. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2254. : Frame->getCurrentTemporary(VD);
  2255. if (!Result) {
  2256. // Assume variables referenced within a lambda's call operator that were
  2257. // not declared within the call operator are captures and during checking
  2258. // of a potential constant expression, assume they are unknown constant
  2259. // expressions.
  2260. assert(isLambdaCallOperator(Frame->Callee) &&
  2261. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2262. "missing value for local variable");
  2263. if (Info.checkingPotentialConstantExpression())
  2264. return false;
  2265. // FIXME: implement capture evaluation during constant expr evaluation.
  2266. Info.FFDiag(E->getBeginLoc(),
  2267. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2268. << "captures not currently allowed";
  2269. return false;
  2270. }
  2271. return true;
  2272. }
  2273. // Dig out the initializer, and use the declaration which it's attached to.
  2274. const Expr *Init = VD->getAnyInitializer(VD);
  2275. if (!Init || Init->isValueDependent()) {
  2276. // If we're checking a potential constant expression, the variable could be
  2277. // initialized later.
  2278. if (!Info.checkingPotentialConstantExpression())
  2279. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2280. return false;
  2281. }
  2282. // If we're currently evaluating the initializer of this declaration, use that
  2283. // in-flight value.
  2284. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2285. Result = Info.EvaluatingDeclValue;
  2286. return true;
  2287. }
  2288. // Never evaluate the initializer of a weak variable. We can't be sure that
  2289. // this is the definition which will be used.
  2290. if (VD->isWeak()) {
  2291. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2292. return false;
  2293. }
  2294. // Check that we can fold the initializer. In C++, we will have already done
  2295. // this in the cases where it matters for conformance.
  2296. SmallVector<PartialDiagnosticAt, 8> Notes;
  2297. if (!VD->evaluateValue(Notes)) {
  2298. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2299. Notes.size() + 1) << VD;
  2300. Info.Note(VD->getLocation(), diag::note_declared_at);
  2301. Info.addNotes(Notes);
  2302. return false;
  2303. } else if (!VD->checkInitIsICE()) {
  2304. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2305. Notes.size() + 1) << VD;
  2306. Info.Note(VD->getLocation(), diag::note_declared_at);
  2307. Info.addNotes(Notes);
  2308. }
  2309. Result = VD->getEvaluatedValue();
  2310. return true;
  2311. }
  2312. static bool IsConstNonVolatile(QualType T) {
  2313. Qualifiers Quals = T.getQualifiers();
  2314. return Quals.hasConst() && !Quals.hasVolatile();
  2315. }
  2316. /// Get the base index of the given base class within an APValue representing
  2317. /// the given derived class.
  2318. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2319. const CXXRecordDecl *Base) {
  2320. Base = Base->getCanonicalDecl();
  2321. unsigned Index = 0;
  2322. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2323. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2324. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2325. return Index;
  2326. }
  2327. llvm_unreachable("base class missing from derived class's bases list");
  2328. }
  2329. /// Extract the value of a character from a string literal.
  2330. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2331. uint64_t Index) {
  2332. // FIXME: Support MakeStringConstant
  2333. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2334. std::string Str;
  2335. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2336. assert(Index <= Str.size() && "Index too large");
  2337. return APSInt::getUnsigned(Str.c_str()[Index]);
  2338. }
  2339. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2340. Lit = PE->getFunctionName();
  2341. const StringLiteral *S = cast<StringLiteral>(Lit);
  2342. const ConstantArrayType *CAT =
  2343. Info.Ctx.getAsConstantArrayType(S->getType());
  2344. assert(CAT && "string literal isn't an array");
  2345. QualType CharType = CAT->getElementType();
  2346. assert(CharType->isIntegerType() && "unexpected character type");
  2347. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2348. CharType->isUnsignedIntegerType());
  2349. if (Index < S->getLength())
  2350. Value = S->getCodeUnit(Index);
  2351. return Value;
  2352. }
  2353. // Expand a string literal into an array of characters.
  2354. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  2355. APValue &Result) {
  2356. const StringLiteral *S = cast<StringLiteral>(Lit);
  2357. const ConstantArrayType *CAT =
  2358. Info.Ctx.getAsConstantArrayType(S->getType());
  2359. assert(CAT && "string literal isn't an array");
  2360. QualType CharType = CAT->getElementType();
  2361. assert(CharType->isIntegerType() && "unexpected character type");
  2362. unsigned Elts = CAT->getSize().getZExtValue();
  2363. Result = APValue(APValue::UninitArray(),
  2364. std::min(S->getLength(), Elts), Elts);
  2365. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2366. CharType->isUnsignedIntegerType());
  2367. if (Result.hasArrayFiller())
  2368. Result.getArrayFiller() = APValue(Value);
  2369. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2370. Value = S->getCodeUnit(I);
  2371. Result.getArrayInitializedElt(I) = APValue(Value);
  2372. }
  2373. }
  2374. // Expand an array so that it has more than Index filled elements.
  2375. static void expandArray(APValue &Array, unsigned Index) {
  2376. unsigned Size = Array.getArraySize();
  2377. assert(Index < Size);
  2378. // Always at least double the number of elements for which we store a value.
  2379. unsigned OldElts = Array.getArrayInitializedElts();
  2380. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2381. NewElts = std::min(Size, std::max(NewElts, 8u));
  2382. // Copy the data across.
  2383. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2384. for (unsigned I = 0; I != OldElts; ++I)
  2385. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2386. for (unsigned I = OldElts; I != NewElts; ++I)
  2387. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2388. if (NewValue.hasArrayFiller())
  2389. NewValue.getArrayFiller() = Array.getArrayFiller();
  2390. Array.swap(NewValue);
  2391. }
  2392. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2393. /// conversion. If it's of class type, we may assume that the copy operation
  2394. /// is trivial. Note that this is never true for a union type with fields
  2395. /// (because the copy always "reads" the active member) and always true for
  2396. /// a non-class type.
  2397. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2398. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2399. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2400. return true;
  2401. if (RD->isEmpty())
  2402. return false;
  2403. for (auto *Field : RD->fields())
  2404. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2405. return true;
  2406. for (auto &BaseSpec : RD->bases())
  2407. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2408. return true;
  2409. return false;
  2410. }
  2411. /// Diagnose an attempt to read from any unreadable field within the specified
  2412. /// type, which might be a class type.
  2413. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2414. QualType T) {
  2415. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2416. if (!RD)
  2417. return false;
  2418. if (!RD->hasMutableFields())
  2419. return false;
  2420. for (auto *Field : RD->fields()) {
  2421. // If we're actually going to read this field in some way, then it can't
  2422. // be mutable. If we're in a union, then assigning to a mutable field
  2423. // (even an empty one) can change the active member, so that's not OK.
  2424. // FIXME: Add core issue number for the union case.
  2425. if (Field->isMutable() &&
  2426. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2427. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2428. Info.Note(Field->getLocation(), diag::note_declared_at);
  2429. return true;
  2430. }
  2431. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2432. return true;
  2433. }
  2434. for (auto &BaseSpec : RD->bases())
  2435. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2436. return true;
  2437. // All mutable fields were empty, and thus not actually read.
  2438. return false;
  2439. }
  2440. /// Kinds of access we can perform on an object, for diagnostics.
  2441. enum AccessKinds {
  2442. AK_Read,
  2443. AK_Assign,
  2444. AK_Increment,
  2445. AK_Decrement
  2446. };
  2447. namespace {
  2448. /// A handle to a complete object (an object that is not a subobject of
  2449. /// another object).
  2450. struct CompleteObject {
  2451. /// The value of the complete object.
  2452. APValue *Value;
  2453. /// The type of the complete object.
  2454. QualType Type;
  2455. bool LifetimeStartedInEvaluation;
  2456. CompleteObject() : Value(nullptr) {}
  2457. CompleteObject(APValue *Value, QualType Type,
  2458. bool LifetimeStartedInEvaluation)
  2459. : Value(Value), Type(Type),
  2460. LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
  2461. assert(Value && "missing value for complete object");
  2462. }
  2463. explicit operator bool() const { return Value; }
  2464. };
  2465. } // end anonymous namespace
  2466. /// Find the designated sub-object of an rvalue.
  2467. template<typename SubobjectHandler>
  2468. typename SubobjectHandler::result_type
  2469. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2470. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2471. if (Sub.Invalid)
  2472. // A diagnostic will have already been produced.
  2473. return handler.failed();
  2474. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2475. if (Info.getLangOpts().CPlusPlus11)
  2476. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2477. ? diag::note_constexpr_access_past_end
  2478. : diag::note_constexpr_access_unsized_array)
  2479. << handler.AccessKind;
  2480. else
  2481. Info.FFDiag(E);
  2482. return handler.failed();
  2483. }
  2484. APValue *O = Obj.Value;
  2485. QualType ObjType = Obj.Type;
  2486. const FieldDecl *LastField = nullptr;
  2487. const bool MayReadMutableMembers =
  2488. Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
  2489. // Walk the designator's path to find the subobject.
  2490. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2491. if (O->isUninit()) {
  2492. if (!Info.checkingPotentialConstantExpression())
  2493. Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2494. return handler.failed();
  2495. }
  2496. if (I == N) {
  2497. // If we are reading an object of class type, there may still be more
  2498. // things we need to check: if there are any mutable subobjects, we
  2499. // cannot perform this read. (This only happens when performing a trivial
  2500. // copy or assignment.)
  2501. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2502. !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
  2503. return handler.failed();
  2504. if (!handler.found(*O, ObjType))
  2505. return false;
  2506. // If we modified a bit-field, truncate it to the right width.
  2507. if (handler.AccessKind != AK_Read &&
  2508. LastField && LastField->isBitField() &&
  2509. !truncateBitfieldValue(Info, E, *O, LastField))
  2510. return false;
  2511. return true;
  2512. }
  2513. LastField = nullptr;
  2514. if (ObjType->isArrayType()) {
  2515. // Next subobject is an array element.
  2516. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2517. assert(CAT && "vla in literal type?");
  2518. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2519. if (CAT->getSize().ule(Index)) {
  2520. // Note, it should not be possible to form a pointer with a valid
  2521. // designator which points more than one past the end of the array.
  2522. if (Info.getLangOpts().CPlusPlus11)
  2523. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2524. << handler.AccessKind;
  2525. else
  2526. Info.FFDiag(E);
  2527. return handler.failed();
  2528. }
  2529. ObjType = CAT->getElementType();
  2530. // An array object is represented as either an Array APValue or as an
  2531. // LValue which refers to a string literal.
  2532. if (O->isLValue()) {
  2533. assert(I == N - 1 && "extracting subobject of character?");
  2534. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2535. if (handler.AccessKind != AK_Read)
  2536. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2537. *O);
  2538. else
  2539. return handler.foundString(*O, ObjType, Index);
  2540. }
  2541. if (O->getArrayInitializedElts() > Index)
  2542. O = &O->getArrayInitializedElt(Index);
  2543. else if (handler.AccessKind != AK_Read) {
  2544. expandArray(*O, Index);
  2545. O = &O->getArrayInitializedElt(Index);
  2546. } else
  2547. O = &O->getArrayFiller();
  2548. } else if (ObjType->isAnyComplexType()) {
  2549. // Next subobject is a complex number.
  2550. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2551. if (Index > 1) {
  2552. if (Info.getLangOpts().CPlusPlus11)
  2553. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2554. << handler.AccessKind;
  2555. else
  2556. Info.FFDiag(E);
  2557. return handler.failed();
  2558. }
  2559. bool WasConstQualified = ObjType.isConstQualified();
  2560. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2561. if (WasConstQualified)
  2562. ObjType.addConst();
  2563. assert(I == N - 1 && "extracting subobject of scalar?");
  2564. if (O->isComplexInt()) {
  2565. return handler.found(Index ? O->getComplexIntImag()
  2566. : O->getComplexIntReal(), ObjType);
  2567. } else {
  2568. assert(O->isComplexFloat());
  2569. return handler.found(Index ? O->getComplexFloatImag()
  2570. : O->getComplexFloatReal(), ObjType);
  2571. }
  2572. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2573. // In C++14 onwards, it is permitted to read a mutable member whose
  2574. // lifetime began within the evaluation.
  2575. // FIXME: Should we also allow this in C++11?
  2576. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2577. !MayReadMutableMembers) {
  2578. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2579. << Field;
  2580. Info.Note(Field->getLocation(), diag::note_declared_at);
  2581. return handler.failed();
  2582. }
  2583. // Next subobject is a class, struct or union field.
  2584. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2585. if (RD->isUnion()) {
  2586. const FieldDecl *UnionField = O->getUnionField();
  2587. if (!UnionField ||
  2588. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2589. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2590. << handler.AccessKind << Field << !UnionField << UnionField;
  2591. return handler.failed();
  2592. }
  2593. O = &O->getUnionValue();
  2594. } else
  2595. O = &O->getStructField(Field->getFieldIndex());
  2596. bool WasConstQualified = ObjType.isConstQualified();
  2597. ObjType = Field->getType();
  2598. if (WasConstQualified && !Field->isMutable())
  2599. ObjType.addConst();
  2600. if (ObjType.isVolatileQualified()) {
  2601. if (Info.getLangOpts().CPlusPlus) {
  2602. // FIXME: Include a description of the path to the volatile subobject.
  2603. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2604. << handler.AccessKind << 2 << Field;
  2605. Info.Note(Field->getLocation(), diag::note_declared_at);
  2606. } else {
  2607. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2608. }
  2609. return handler.failed();
  2610. }
  2611. LastField = Field;
  2612. } else {
  2613. // Next subobject is a base class.
  2614. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2615. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2616. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2617. bool WasConstQualified = ObjType.isConstQualified();
  2618. ObjType = Info.Ctx.getRecordType(Base);
  2619. if (WasConstQualified)
  2620. ObjType.addConst();
  2621. }
  2622. }
  2623. }
  2624. namespace {
  2625. struct ExtractSubobjectHandler {
  2626. EvalInfo &Info;
  2627. APValue &Result;
  2628. static const AccessKinds AccessKind = AK_Read;
  2629. typedef bool result_type;
  2630. bool failed() { return false; }
  2631. bool found(APValue &Subobj, QualType SubobjType) {
  2632. Result = Subobj;
  2633. return true;
  2634. }
  2635. bool found(APSInt &Value, QualType SubobjType) {
  2636. Result = APValue(Value);
  2637. return true;
  2638. }
  2639. bool found(APFloat &Value, QualType SubobjType) {
  2640. Result = APValue(Value);
  2641. return true;
  2642. }
  2643. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2644. Result = APValue(extractStringLiteralCharacter(
  2645. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2646. return true;
  2647. }
  2648. };
  2649. } // end anonymous namespace
  2650. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2651. /// Extract the designated sub-object of an rvalue.
  2652. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2653. const CompleteObject &Obj,
  2654. const SubobjectDesignator &Sub,
  2655. APValue &Result) {
  2656. ExtractSubobjectHandler Handler = { Info, Result };
  2657. return findSubobject(Info, E, Obj, Sub, Handler);
  2658. }
  2659. namespace {
  2660. struct ModifySubobjectHandler {
  2661. EvalInfo &Info;
  2662. APValue &NewVal;
  2663. const Expr *E;
  2664. typedef bool result_type;
  2665. static const AccessKinds AccessKind = AK_Assign;
  2666. bool checkConst(QualType QT) {
  2667. // Assigning to a const object has undefined behavior.
  2668. if (QT.isConstQualified()) {
  2669. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2670. return false;
  2671. }
  2672. return true;
  2673. }
  2674. bool failed() { return false; }
  2675. bool found(APValue &Subobj, QualType SubobjType) {
  2676. if (!checkConst(SubobjType))
  2677. return false;
  2678. // We've been given ownership of NewVal, so just swap it in.
  2679. Subobj.swap(NewVal);
  2680. return true;
  2681. }
  2682. bool found(APSInt &Value, QualType SubobjType) {
  2683. if (!checkConst(SubobjType))
  2684. return false;
  2685. if (!NewVal.isInt()) {
  2686. // Maybe trying to write a cast pointer value into a complex?
  2687. Info.FFDiag(E);
  2688. return false;
  2689. }
  2690. Value = NewVal.getInt();
  2691. return true;
  2692. }
  2693. bool found(APFloat &Value, QualType SubobjType) {
  2694. if (!checkConst(SubobjType))
  2695. return false;
  2696. Value = NewVal.getFloat();
  2697. return true;
  2698. }
  2699. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2700. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2701. }
  2702. };
  2703. } // end anonymous namespace
  2704. const AccessKinds ModifySubobjectHandler::AccessKind;
  2705. /// Update the designated sub-object of an rvalue to the given value.
  2706. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2707. const CompleteObject &Obj,
  2708. const SubobjectDesignator &Sub,
  2709. APValue &NewVal) {
  2710. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2711. return findSubobject(Info, E, Obj, Sub, Handler);
  2712. }
  2713. /// Find the position where two subobject designators diverge, or equivalently
  2714. /// the length of the common initial subsequence.
  2715. static unsigned FindDesignatorMismatch(QualType ObjType,
  2716. const SubobjectDesignator &A,
  2717. const SubobjectDesignator &B,
  2718. bool &WasArrayIndex) {
  2719. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2720. for (/**/; I != N; ++I) {
  2721. if (!ObjType.isNull() &&
  2722. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2723. // Next subobject is an array element.
  2724. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2725. WasArrayIndex = true;
  2726. return I;
  2727. }
  2728. if (ObjType->isAnyComplexType())
  2729. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2730. else
  2731. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2732. } else {
  2733. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2734. WasArrayIndex = false;
  2735. return I;
  2736. }
  2737. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2738. // Next subobject is a field.
  2739. ObjType = FD->getType();
  2740. else
  2741. // Next subobject is a base class.
  2742. ObjType = QualType();
  2743. }
  2744. }
  2745. WasArrayIndex = false;
  2746. return I;
  2747. }
  2748. /// Determine whether the given subobject designators refer to elements of the
  2749. /// same array object.
  2750. static bool AreElementsOfSameArray(QualType ObjType,
  2751. const SubobjectDesignator &A,
  2752. const SubobjectDesignator &B) {
  2753. if (A.Entries.size() != B.Entries.size())
  2754. return false;
  2755. bool IsArray = A.MostDerivedIsArrayElement;
  2756. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2757. // A is a subobject of the array element.
  2758. return false;
  2759. // If A (and B) designates an array element, the last entry will be the array
  2760. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2761. // of length 1' case, and the entire path must match.
  2762. bool WasArrayIndex;
  2763. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2764. return CommonLength >= A.Entries.size() - IsArray;
  2765. }
  2766. /// Find the complete object to which an LValue refers.
  2767. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2768. AccessKinds AK, const LValue &LVal,
  2769. QualType LValType) {
  2770. if (!LVal.Base) {
  2771. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2772. return CompleteObject();
  2773. }
  2774. CallStackFrame *Frame = nullptr;
  2775. if (LVal.getLValueCallIndex()) {
  2776. Frame = Info.getCallFrame(LVal.getLValueCallIndex());
  2777. if (!Frame) {
  2778. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2779. << AK << LVal.Base.is<const ValueDecl*>();
  2780. NoteLValueLocation(Info, LVal.Base);
  2781. return CompleteObject();
  2782. }
  2783. }
  2784. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2785. // is not a constant expression (even if the object is non-volatile). We also
  2786. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2787. // semantics.
  2788. if (LValType.isVolatileQualified()) {
  2789. if (Info.getLangOpts().CPlusPlus)
  2790. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2791. << AK << LValType;
  2792. else
  2793. Info.FFDiag(E);
  2794. return CompleteObject();
  2795. }
  2796. // Compute value storage location and type of base object.
  2797. APValue *BaseVal = nullptr;
  2798. QualType BaseType = getType(LVal.Base);
  2799. bool LifetimeStartedInEvaluation = Frame;
  2800. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2801. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2802. // In C++11, constexpr, non-volatile variables initialized with constant
  2803. // expressions are constant expressions too. Inside constexpr functions,
  2804. // parameters are constant expressions even if they're non-const.
  2805. // In C++1y, objects local to a constant expression (those with a Frame) are
  2806. // both readable and writable inside constant expressions.
  2807. // In C, such things can also be folded, although they are not ICEs.
  2808. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2809. if (VD) {
  2810. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2811. VD = VDef;
  2812. }
  2813. if (!VD || VD->isInvalidDecl()) {
  2814. Info.FFDiag(E);
  2815. return CompleteObject();
  2816. }
  2817. // Accesses of volatile-qualified objects are not allowed.
  2818. if (BaseType.isVolatileQualified()) {
  2819. if (Info.getLangOpts().CPlusPlus) {
  2820. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2821. << AK << 1 << VD;
  2822. Info.Note(VD->getLocation(), diag::note_declared_at);
  2823. } else {
  2824. Info.FFDiag(E);
  2825. }
  2826. return CompleteObject();
  2827. }
  2828. // Unless we're looking at a local variable or argument in a constexpr call,
  2829. // the variable we're reading must be const.
  2830. if (!Frame) {
  2831. if (Info.getLangOpts().CPlusPlus14 &&
  2832. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2833. // OK, we can read and modify an object if we're in the process of
  2834. // evaluating its initializer, because its lifetime began in this
  2835. // evaluation.
  2836. } else if (AK != AK_Read) {
  2837. // All the remaining cases only permit reading.
  2838. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2839. return CompleteObject();
  2840. } else if (VD->isConstexpr()) {
  2841. // OK, we can read this variable.
  2842. } else if (BaseType->isIntegralOrEnumerationType()) {
  2843. // In OpenCL if a variable is in constant address space it is a const value.
  2844. if (!(BaseType.isConstQualified() ||
  2845. (Info.getLangOpts().OpenCL &&
  2846. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2847. if (Info.getLangOpts().CPlusPlus) {
  2848. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2849. Info.Note(VD->getLocation(), diag::note_declared_at);
  2850. } else {
  2851. Info.FFDiag(E);
  2852. }
  2853. return CompleteObject();
  2854. }
  2855. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2856. // We support folding of const floating-point types, in order to make
  2857. // static const data members of such types (supported as an extension)
  2858. // more useful.
  2859. if (Info.getLangOpts().CPlusPlus11) {
  2860. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2861. Info.Note(VD->getLocation(), diag::note_declared_at);
  2862. } else {
  2863. Info.CCEDiag(E);
  2864. }
  2865. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  2866. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  2867. // Keep evaluating to see what we can do.
  2868. } else {
  2869. // FIXME: Allow folding of values of any literal type in all languages.
  2870. if (Info.checkingPotentialConstantExpression() &&
  2871. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2872. // The definition of this variable could be constexpr. We can't
  2873. // access it right now, but may be able to in future.
  2874. } else if (Info.getLangOpts().CPlusPlus11) {
  2875. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2876. Info.Note(VD->getLocation(), diag::note_declared_at);
  2877. } else {
  2878. Info.FFDiag(E);
  2879. }
  2880. return CompleteObject();
  2881. }
  2882. }
  2883. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  2884. return CompleteObject();
  2885. } else {
  2886. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2887. if (!Frame) {
  2888. if (const MaterializeTemporaryExpr *MTE =
  2889. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2890. assert(MTE->getStorageDuration() == SD_Static &&
  2891. "should have a frame for a non-global materialized temporary");
  2892. // Per C++1y [expr.const]p2:
  2893. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2894. // - a [...] glvalue of integral or enumeration type that refers to
  2895. // a non-volatile const object [...]
  2896. // [...]
  2897. // - a [...] glvalue of literal type that refers to a non-volatile
  2898. // object whose lifetime began within the evaluation of e.
  2899. //
  2900. // C++11 misses the 'began within the evaluation of e' check and
  2901. // instead allows all temporaries, including things like:
  2902. // int &&r = 1;
  2903. // int x = ++r;
  2904. // constexpr int k = r;
  2905. // Therefore we use the C++14 rules in C++11 too.
  2906. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2907. const ValueDecl *ED = MTE->getExtendingDecl();
  2908. if (!(BaseType.isConstQualified() &&
  2909. BaseType->isIntegralOrEnumerationType()) &&
  2910. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2911. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2912. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2913. return CompleteObject();
  2914. }
  2915. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2916. assert(BaseVal && "got reference to unevaluated temporary");
  2917. LifetimeStartedInEvaluation = true;
  2918. } else {
  2919. Info.FFDiag(E);
  2920. return CompleteObject();
  2921. }
  2922. } else {
  2923. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  2924. assert(BaseVal && "missing value for temporary");
  2925. }
  2926. // Volatile temporary objects cannot be accessed in constant expressions.
  2927. if (BaseType.isVolatileQualified()) {
  2928. if (Info.getLangOpts().CPlusPlus) {
  2929. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2930. << AK << 0;
  2931. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2932. } else {
  2933. Info.FFDiag(E);
  2934. }
  2935. return CompleteObject();
  2936. }
  2937. }
  2938. // During the construction of an object, it is not yet 'const'.
  2939. // FIXME: This doesn't do quite the right thing for const subobjects of the
  2940. // object under construction.
  2941. if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
  2942. LVal.getLValueCallIndex(),
  2943. LVal.getLValueVersion())) {
  2944. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2945. BaseType.removeLocalConst();
  2946. LifetimeStartedInEvaluation = true;
  2947. }
  2948. // In C++14, we can't safely access any mutable state when we might be
  2949. // evaluating after an unmodeled side effect.
  2950. //
  2951. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2952. // to be read here (but take care with 'mutable' fields).
  2953. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2954. Info.EvalStatus.HasSideEffects) ||
  2955. (AK != AK_Read && Info.IsSpeculativelyEvaluating))
  2956. return CompleteObject();
  2957. return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
  2958. }
  2959. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2960. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2961. /// glvalue referred to by an entity of reference type.
  2962. ///
  2963. /// \param Info - Information about the ongoing evaluation.
  2964. /// \param Conv - The expression for which we are performing the conversion.
  2965. /// Used for diagnostics.
  2966. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2967. /// case of a non-class type).
  2968. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2969. /// \param RVal - The produced value will be placed here.
  2970. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2971. QualType Type,
  2972. const LValue &LVal, APValue &RVal) {
  2973. if (LVal.Designator.Invalid)
  2974. return false;
  2975. // Check for special cases where there is no existing APValue to look at.
  2976. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2977. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  2978. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2979. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2980. // initializer until now for such expressions. Such an expression can't be
  2981. // an ICE in C, so this only matters for fold.
  2982. if (Type.isVolatileQualified()) {
  2983. Info.FFDiag(Conv);
  2984. return false;
  2985. }
  2986. APValue Lit;
  2987. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2988. return false;
  2989. CompleteObject LitObj(&Lit, Base->getType(), false);
  2990. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2991. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2992. // We represent a string literal array as an lvalue pointing at the
  2993. // corresponding expression, rather than building an array of chars.
  2994. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2995. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2996. CompleteObject StrObj(&Str, Base->getType(), false);
  2997. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2998. }
  2999. }
  3000. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3001. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3002. }
  3003. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3004. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3005. QualType LValType, APValue &Val) {
  3006. if (LVal.Designator.Invalid)
  3007. return false;
  3008. if (!Info.getLangOpts().CPlusPlus14) {
  3009. Info.FFDiag(E);
  3010. return false;
  3011. }
  3012. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3013. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3014. }
  3015. namespace {
  3016. struct CompoundAssignSubobjectHandler {
  3017. EvalInfo &Info;
  3018. const Expr *E;
  3019. QualType PromotedLHSType;
  3020. BinaryOperatorKind Opcode;
  3021. const APValue &RHS;
  3022. static const AccessKinds AccessKind = AK_Assign;
  3023. typedef bool result_type;
  3024. bool checkConst(QualType QT) {
  3025. // Assigning to a const object has undefined behavior.
  3026. if (QT.isConstQualified()) {
  3027. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3028. return false;
  3029. }
  3030. return true;
  3031. }
  3032. bool failed() { return false; }
  3033. bool found(APValue &Subobj, QualType SubobjType) {
  3034. switch (Subobj.getKind()) {
  3035. case APValue::Int:
  3036. return found(Subobj.getInt(), SubobjType);
  3037. case APValue::Float:
  3038. return found(Subobj.getFloat(), SubobjType);
  3039. case APValue::ComplexInt:
  3040. case APValue::ComplexFloat:
  3041. // FIXME: Implement complex compound assignment.
  3042. Info.FFDiag(E);
  3043. return false;
  3044. case APValue::LValue:
  3045. return foundPointer(Subobj, SubobjType);
  3046. default:
  3047. // FIXME: can this happen?
  3048. Info.FFDiag(E);
  3049. return false;
  3050. }
  3051. }
  3052. bool found(APSInt &Value, QualType SubobjType) {
  3053. if (!checkConst(SubobjType))
  3054. return false;
  3055. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  3056. // We don't support compound assignment on integer-cast-to-pointer
  3057. // values.
  3058. Info.FFDiag(E);
  3059. return false;
  3060. }
  3061. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  3062. SubobjType, Value);
  3063. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3064. return false;
  3065. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3066. return true;
  3067. }
  3068. bool found(APFloat &Value, QualType SubobjType) {
  3069. return checkConst(SubobjType) &&
  3070. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3071. Value) &&
  3072. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3073. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3074. }
  3075. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3076. if (!checkConst(SubobjType))
  3077. return false;
  3078. QualType PointeeType;
  3079. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3080. PointeeType = PT->getPointeeType();
  3081. if (PointeeType.isNull() || !RHS.isInt() ||
  3082. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3083. Info.FFDiag(E);
  3084. return false;
  3085. }
  3086. APSInt Offset = RHS.getInt();
  3087. if (Opcode == BO_Sub)
  3088. negateAsSigned(Offset);
  3089. LValue LVal;
  3090. LVal.setFrom(Info.Ctx, Subobj);
  3091. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3092. return false;
  3093. LVal.moveInto(Subobj);
  3094. return true;
  3095. }
  3096. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3097. llvm_unreachable("shouldn't encounter string elements here");
  3098. }
  3099. };
  3100. } // end anonymous namespace
  3101. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3102. /// Perform a compound assignment of LVal <op>= RVal.
  3103. static bool handleCompoundAssignment(
  3104. EvalInfo &Info, const Expr *E,
  3105. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3106. BinaryOperatorKind Opcode, const APValue &RVal) {
  3107. if (LVal.Designator.Invalid)
  3108. return false;
  3109. if (!Info.getLangOpts().CPlusPlus14) {
  3110. Info.FFDiag(E);
  3111. return false;
  3112. }
  3113. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3114. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3115. RVal };
  3116. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3117. }
  3118. namespace {
  3119. struct IncDecSubobjectHandler {
  3120. EvalInfo &Info;
  3121. const UnaryOperator *E;
  3122. AccessKinds AccessKind;
  3123. APValue *Old;
  3124. typedef bool result_type;
  3125. bool checkConst(QualType QT) {
  3126. // Assigning to a const object has undefined behavior.
  3127. if (QT.isConstQualified()) {
  3128. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3129. return false;
  3130. }
  3131. return true;
  3132. }
  3133. bool failed() { return false; }
  3134. bool found(APValue &Subobj, QualType SubobjType) {
  3135. // Stash the old value. Also clear Old, so we don't clobber it later
  3136. // if we're post-incrementing a complex.
  3137. if (Old) {
  3138. *Old = Subobj;
  3139. Old = nullptr;
  3140. }
  3141. switch (Subobj.getKind()) {
  3142. case APValue::Int:
  3143. return found(Subobj.getInt(), SubobjType);
  3144. case APValue::Float:
  3145. return found(Subobj.getFloat(), SubobjType);
  3146. case APValue::ComplexInt:
  3147. return found(Subobj.getComplexIntReal(),
  3148. SubobjType->castAs<ComplexType>()->getElementType()
  3149. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3150. case APValue::ComplexFloat:
  3151. return found(Subobj.getComplexFloatReal(),
  3152. SubobjType->castAs<ComplexType>()->getElementType()
  3153. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3154. case APValue::LValue:
  3155. return foundPointer(Subobj, SubobjType);
  3156. default:
  3157. // FIXME: can this happen?
  3158. Info.FFDiag(E);
  3159. return false;
  3160. }
  3161. }
  3162. bool found(APSInt &Value, QualType SubobjType) {
  3163. if (!checkConst(SubobjType))
  3164. return false;
  3165. if (!SubobjType->isIntegerType()) {
  3166. // We don't support increment / decrement on integer-cast-to-pointer
  3167. // values.
  3168. Info.FFDiag(E);
  3169. return false;
  3170. }
  3171. if (Old) *Old = APValue(Value);
  3172. // bool arithmetic promotes to int, and the conversion back to bool
  3173. // doesn't reduce mod 2^n, so special-case it.
  3174. if (SubobjType->isBooleanType()) {
  3175. if (AccessKind == AK_Increment)
  3176. Value = 1;
  3177. else
  3178. Value = !Value;
  3179. return true;
  3180. }
  3181. bool WasNegative = Value.isNegative();
  3182. if (AccessKind == AK_Increment) {
  3183. ++Value;
  3184. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3185. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3186. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3187. }
  3188. } else {
  3189. --Value;
  3190. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3191. unsigned BitWidth = Value.getBitWidth();
  3192. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3193. ActualValue.setBit(BitWidth);
  3194. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3195. }
  3196. }
  3197. return true;
  3198. }
  3199. bool found(APFloat &Value, QualType SubobjType) {
  3200. if (!checkConst(SubobjType))
  3201. return false;
  3202. if (Old) *Old = APValue(Value);
  3203. APFloat One(Value.getSemantics(), 1);
  3204. if (AccessKind == AK_Increment)
  3205. Value.add(One, APFloat::rmNearestTiesToEven);
  3206. else
  3207. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3208. return true;
  3209. }
  3210. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3211. if (!checkConst(SubobjType))
  3212. return false;
  3213. QualType PointeeType;
  3214. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3215. PointeeType = PT->getPointeeType();
  3216. else {
  3217. Info.FFDiag(E);
  3218. return false;
  3219. }
  3220. LValue LVal;
  3221. LVal.setFrom(Info.Ctx, Subobj);
  3222. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3223. AccessKind == AK_Increment ? 1 : -1))
  3224. return false;
  3225. LVal.moveInto(Subobj);
  3226. return true;
  3227. }
  3228. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3229. llvm_unreachable("shouldn't encounter string elements here");
  3230. }
  3231. };
  3232. } // end anonymous namespace
  3233. /// Perform an increment or decrement on LVal.
  3234. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3235. QualType LValType, bool IsIncrement, APValue *Old) {
  3236. if (LVal.Designator.Invalid)
  3237. return false;
  3238. if (!Info.getLangOpts().CPlusPlus14) {
  3239. Info.FFDiag(E);
  3240. return false;
  3241. }
  3242. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3243. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3244. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3245. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3246. }
  3247. /// Build an lvalue for the object argument of a member function call.
  3248. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3249. LValue &This) {
  3250. if (Object->getType()->isPointerType())
  3251. return EvaluatePointer(Object, This, Info);
  3252. if (Object->isGLValue())
  3253. return EvaluateLValue(Object, This, Info);
  3254. if (Object->getType()->isLiteralType(Info.Ctx))
  3255. return EvaluateTemporary(Object, This, Info);
  3256. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3257. return false;
  3258. }
  3259. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3260. /// lvalue referring to the result.
  3261. ///
  3262. /// \param Info - Information about the ongoing evaluation.
  3263. /// \param LV - An lvalue referring to the base of the member pointer.
  3264. /// \param RHS - The member pointer expression.
  3265. /// \param IncludeMember - Specifies whether the member itself is included in
  3266. /// the resulting LValue subobject designator. This is not possible when
  3267. /// creating a bound member function.
  3268. /// \return The field or method declaration to which the member pointer refers,
  3269. /// or 0 if evaluation fails.
  3270. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3271. QualType LVType,
  3272. LValue &LV,
  3273. const Expr *RHS,
  3274. bool IncludeMember = true) {
  3275. MemberPtr MemPtr;
  3276. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3277. return nullptr;
  3278. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3279. // member value, the behavior is undefined.
  3280. if (!MemPtr.getDecl()) {
  3281. // FIXME: Specific diagnostic.
  3282. Info.FFDiag(RHS);
  3283. return nullptr;
  3284. }
  3285. if (MemPtr.isDerivedMember()) {
  3286. // This is a member of some derived class. Truncate LV appropriately.
  3287. // The end of the derived-to-base path for the base object must match the
  3288. // derived-to-base path for the member pointer.
  3289. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3290. LV.Designator.Entries.size()) {
  3291. Info.FFDiag(RHS);
  3292. return nullptr;
  3293. }
  3294. unsigned PathLengthToMember =
  3295. LV.Designator.Entries.size() - MemPtr.Path.size();
  3296. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3297. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3298. LV.Designator.Entries[PathLengthToMember + I]);
  3299. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3300. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3301. Info.FFDiag(RHS);
  3302. return nullptr;
  3303. }
  3304. }
  3305. // Truncate the lvalue to the appropriate derived class.
  3306. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3307. PathLengthToMember))
  3308. return nullptr;
  3309. } else if (!MemPtr.Path.empty()) {
  3310. // Extend the LValue path with the member pointer's path.
  3311. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3312. MemPtr.Path.size() + IncludeMember);
  3313. // Walk down to the appropriate base class.
  3314. if (const PointerType *PT = LVType->getAs<PointerType>())
  3315. LVType = PT->getPointeeType();
  3316. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3317. assert(RD && "member pointer access on non-class-type expression");
  3318. // The first class in the path is that of the lvalue.
  3319. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3320. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3321. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3322. return nullptr;
  3323. RD = Base;
  3324. }
  3325. // Finally cast to the class containing the member.
  3326. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3327. MemPtr.getContainingRecord()))
  3328. return nullptr;
  3329. }
  3330. // Add the member. Note that we cannot build bound member functions here.
  3331. if (IncludeMember) {
  3332. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3333. if (!HandleLValueMember(Info, RHS, LV, FD))
  3334. return nullptr;
  3335. } else if (const IndirectFieldDecl *IFD =
  3336. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3337. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3338. return nullptr;
  3339. } else {
  3340. llvm_unreachable("can't construct reference to bound member function");
  3341. }
  3342. }
  3343. return MemPtr.getDecl();
  3344. }
  3345. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3346. const BinaryOperator *BO,
  3347. LValue &LV,
  3348. bool IncludeMember = true) {
  3349. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3350. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3351. if (Info.noteFailure()) {
  3352. MemberPtr MemPtr;
  3353. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3354. }
  3355. return nullptr;
  3356. }
  3357. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3358. BO->getRHS(), IncludeMember);
  3359. }
  3360. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3361. /// the provided lvalue, which currently refers to the base object.
  3362. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3363. LValue &Result) {
  3364. SubobjectDesignator &D = Result.Designator;
  3365. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3366. return false;
  3367. QualType TargetQT = E->getType();
  3368. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3369. TargetQT = PT->getPointeeType();
  3370. // Check this cast lands within the final derived-to-base subobject path.
  3371. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3372. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3373. << D.MostDerivedType << TargetQT;
  3374. return false;
  3375. }
  3376. // Check the type of the final cast. We don't need to check the path,
  3377. // since a cast can only be formed if the path is unique.
  3378. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3379. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3380. const CXXRecordDecl *FinalType;
  3381. if (NewEntriesSize == D.MostDerivedPathLength)
  3382. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3383. else
  3384. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3385. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3386. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3387. << D.MostDerivedType << TargetQT;
  3388. return false;
  3389. }
  3390. // Truncate the lvalue to the appropriate derived class.
  3391. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3392. }
  3393. namespace {
  3394. enum EvalStmtResult {
  3395. /// Evaluation failed.
  3396. ESR_Failed,
  3397. /// Hit a 'return' statement.
  3398. ESR_Returned,
  3399. /// Evaluation succeeded.
  3400. ESR_Succeeded,
  3401. /// Hit a 'continue' statement.
  3402. ESR_Continue,
  3403. /// Hit a 'break' statement.
  3404. ESR_Break,
  3405. /// Still scanning for 'case' or 'default' statement.
  3406. ESR_CaseNotFound
  3407. };
  3408. }
  3409. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3410. // We don't need to evaluate the initializer for a static local.
  3411. if (!VD->hasLocalStorage())
  3412. return true;
  3413. LValue Result;
  3414. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3415. const Expr *InitE = VD->getInit();
  3416. if (!InitE) {
  3417. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3418. << false << VD->getType();
  3419. Val = APValue();
  3420. return false;
  3421. }
  3422. if (InitE->isValueDependent())
  3423. return false;
  3424. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3425. // Wipe out any partially-computed value, to allow tracking that this
  3426. // evaluation failed.
  3427. Val = APValue();
  3428. return false;
  3429. }
  3430. return true;
  3431. }
  3432. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3433. bool OK = true;
  3434. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3435. OK &= EvaluateVarDecl(Info, VD);
  3436. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3437. for (auto *BD : DD->bindings())
  3438. if (auto *VD = BD->getHoldingVar())
  3439. OK &= EvaluateDecl(Info, VD);
  3440. return OK;
  3441. }
  3442. /// Evaluate a condition (either a variable declaration or an expression).
  3443. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3444. const Expr *Cond, bool &Result) {
  3445. FullExpressionRAII Scope(Info);
  3446. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3447. return false;
  3448. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3449. }
  3450. namespace {
  3451. /// A location where the result (returned value) of evaluating a
  3452. /// statement should be stored.
  3453. struct StmtResult {
  3454. /// The APValue that should be filled in with the returned value.
  3455. APValue &Value;
  3456. /// The location containing the result, if any (used to support RVO).
  3457. const LValue *Slot;
  3458. };
  3459. struct TempVersionRAII {
  3460. CallStackFrame &Frame;
  3461. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3462. Frame.pushTempVersion();
  3463. }
  3464. ~TempVersionRAII() {
  3465. Frame.popTempVersion();
  3466. }
  3467. };
  3468. }
  3469. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3470. const Stmt *S,
  3471. const SwitchCase *SC = nullptr);
  3472. /// Evaluate the body of a loop, and translate the result as appropriate.
  3473. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3474. const Stmt *Body,
  3475. const SwitchCase *Case = nullptr) {
  3476. BlockScopeRAII Scope(Info);
  3477. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3478. case ESR_Break:
  3479. return ESR_Succeeded;
  3480. case ESR_Succeeded:
  3481. case ESR_Continue:
  3482. return ESR_Continue;
  3483. case ESR_Failed:
  3484. case ESR_Returned:
  3485. case ESR_CaseNotFound:
  3486. return ESR;
  3487. }
  3488. llvm_unreachable("Invalid EvalStmtResult!");
  3489. }
  3490. /// Evaluate a switch statement.
  3491. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3492. const SwitchStmt *SS) {
  3493. BlockScopeRAII Scope(Info);
  3494. // Evaluate the switch condition.
  3495. APSInt Value;
  3496. {
  3497. FullExpressionRAII Scope(Info);
  3498. if (const Stmt *Init = SS->getInit()) {
  3499. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3500. if (ESR != ESR_Succeeded)
  3501. return ESR;
  3502. }
  3503. if (SS->getConditionVariable() &&
  3504. !EvaluateDecl(Info, SS->getConditionVariable()))
  3505. return ESR_Failed;
  3506. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3507. return ESR_Failed;
  3508. }
  3509. // Find the switch case corresponding to the value of the condition.
  3510. // FIXME: Cache this lookup.
  3511. const SwitchCase *Found = nullptr;
  3512. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3513. SC = SC->getNextSwitchCase()) {
  3514. if (isa<DefaultStmt>(SC)) {
  3515. Found = SC;
  3516. continue;
  3517. }
  3518. const CaseStmt *CS = cast<CaseStmt>(SC);
  3519. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3520. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3521. : LHS;
  3522. if (LHS <= Value && Value <= RHS) {
  3523. Found = SC;
  3524. break;
  3525. }
  3526. }
  3527. if (!Found)
  3528. return ESR_Succeeded;
  3529. // Search the switch body for the switch case and evaluate it from there.
  3530. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3531. case ESR_Break:
  3532. return ESR_Succeeded;
  3533. case ESR_Succeeded:
  3534. case ESR_Continue:
  3535. case ESR_Failed:
  3536. case ESR_Returned:
  3537. return ESR;
  3538. case ESR_CaseNotFound:
  3539. // This can only happen if the switch case is nested within a statement
  3540. // expression. We have no intention of supporting that.
  3541. Info.FFDiag(Found->getBeginLoc(),
  3542. diag::note_constexpr_stmt_expr_unsupported);
  3543. return ESR_Failed;
  3544. }
  3545. llvm_unreachable("Invalid EvalStmtResult!");
  3546. }
  3547. // Evaluate a statement.
  3548. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3549. const Stmt *S, const SwitchCase *Case) {
  3550. if (!Info.nextStep(S))
  3551. return ESR_Failed;
  3552. // If we're hunting down a 'case' or 'default' label, recurse through
  3553. // substatements until we hit the label.
  3554. if (Case) {
  3555. // FIXME: We don't start the lifetime of objects whose initialization we
  3556. // jump over. However, such objects must be of class type with a trivial
  3557. // default constructor that initialize all subobjects, so must be empty,
  3558. // so this almost never matters.
  3559. switch (S->getStmtClass()) {
  3560. case Stmt::CompoundStmtClass:
  3561. // FIXME: Precompute which substatement of a compound statement we
  3562. // would jump to, and go straight there rather than performing a
  3563. // linear scan each time.
  3564. case Stmt::LabelStmtClass:
  3565. case Stmt::AttributedStmtClass:
  3566. case Stmt::DoStmtClass:
  3567. break;
  3568. case Stmt::CaseStmtClass:
  3569. case Stmt::DefaultStmtClass:
  3570. if (Case == S)
  3571. Case = nullptr;
  3572. break;
  3573. case Stmt::IfStmtClass: {
  3574. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3575. // straight there rather than scanning both sides.
  3576. const IfStmt *IS = cast<IfStmt>(S);
  3577. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3578. // preceded by our switch label.
  3579. BlockScopeRAII Scope(Info);
  3580. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3581. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3582. return ESR;
  3583. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3584. }
  3585. case Stmt::WhileStmtClass: {
  3586. EvalStmtResult ESR =
  3587. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3588. if (ESR != ESR_Continue)
  3589. return ESR;
  3590. break;
  3591. }
  3592. case Stmt::ForStmtClass: {
  3593. const ForStmt *FS = cast<ForStmt>(S);
  3594. EvalStmtResult ESR =
  3595. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3596. if (ESR != ESR_Continue)
  3597. return ESR;
  3598. if (FS->getInc()) {
  3599. FullExpressionRAII IncScope(Info);
  3600. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3601. return ESR_Failed;
  3602. }
  3603. break;
  3604. }
  3605. case Stmt::DeclStmtClass:
  3606. // FIXME: If the variable has initialization that can't be jumped over,
  3607. // bail out of any immediately-surrounding compound-statement too.
  3608. default:
  3609. return ESR_CaseNotFound;
  3610. }
  3611. }
  3612. switch (S->getStmtClass()) {
  3613. default:
  3614. if (const Expr *E = dyn_cast<Expr>(S)) {
  3615. // Don't bother evaluating beyond an expression-statement which couldn't
  3616. // be evaluated.
  3617. FullExpressionRAII Scope(Info);
  3618. if (!EvaluateIgnoredValue(Info, E))
  3619. return ESR_Failed;
  3620. return ESR_Succeeded;
  3621. }
  3622. Info.FFDiag(S->getBeginLoc());
  3623. return ESR_Failed;
  3624. case Stmt::NullStmtClass:
  3625. return ESR_Succeeded;
  3626. case Stmt::DeclStmtClass: {
  3627. const DeclStmt *DS = cast<DeclStmt>(S);
  3628. for (const auto *DclIt : DS->decls()) {
  3629. // Each declaration initialization is its own full-expression.
  3630. // FIXME: This isn't quite right; if we're performing aggregate
  3631. // initialization, each braced subexpression is its own full-expression.
  3632. FullExpressionRAII Scope(Info);
  3633. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3634. return ESR_Failed;
  3635. }
  3636. return ESR_Succeeded;
  3637. }
  3638. case Stmt::ReturnStmtClass: {
  3639. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3640. FullExpressionRAII Scope(Info);
  3641. if (RetExpr &&
  3642. !(Result.Slot
  3643. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3644. : Evaluate(Result.Value, Info, RetExpr)))
  3645. return ESR_Failed;
  3646. return ESR_Returned;
  3647. }
  3648. case Stmt::CompoundStmtClass: {
  3649. BlockScopeRAII Scope(Info);
  3650. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3651. for (const auto *BI : CS->body()) {
  3652. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3653. if (ESR == ESR_Succeeded)
  3654. Case = nullptr;
  3655. else if (ESR != ESR_CaseNotFound)
  3656. return ESR;
  3657. }
  3658. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3659. }
  3660. case Stmt::IfStmtClass: {
  3661. const IfStmt *IS = cast<IfStmt>(S);
  3662. // Evaluate the condition, as either a var decl or as an expression.
  3663. BlockScopeRAII Scope(Info);
  3664. if (const Stmt *Init = IS->getInit()) {
  3665. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3666. if (ESR != ESR_Succeeded)
  3667. return ESR;
  3668. }
  3669. bool Cond;
  3670. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3671. return ESR_Failed;
  3672. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3673. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3674. if (ESR != ESR_Succeeded)
  3675. return ESR;
  3676. }
  3677. return ESR_Succeeded;
  3678. }
  3679. case Stmt::WhileStmtClass: {
  3680. const WhileStmt *WS = cast<WhileStmt>(S);
  3681. while (true) {
  3682. BlockScopeRAII Scope(Info);
  3683. bool Continue;
  3684. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3685. Continue))
  3686. return ESR_Failed;
  3687. if (!Continue)
  3688. break;
  3689. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3690. if (ESR != ESR_Continue)
  3691. return ESR;
  3692. }
  3693. return ESR_Succeeded;
  3694. }
  3695. case Stmt::DoStmtClass: {
  3696. const DoStmt *DS = cast<DoStmt>(S);
  3697. bool Continue;
  3698. do {
  3699. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3700. if (ESR != ESR_Continue)
  3701. return ESR;
  3702. Case = nullptr;
  3703. FullExpressionRAII CondScope(Info);
  3704. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3705. return ESR_Failed;
  3706. } while (Continue);
  3707. return ESR_Succeeded;
  3708. }
  3709. case Stmt::ForStmtClass: {
  3710. const ForStmt *FS = cast<ForStmt>(S);
  3711. BlockScopeRAII Scope(Info);
  3712. if (FS->getInit()) {
  3713. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3714. if (ESR != ESR_Succeeded)
  3715. return ESR;
  3716. }
  3717. while (true) {
  3718. BlockScopeRAII Scope(Info);
  3719. bool Continue = true;
  3720. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3721. FS->getCond(), Continue))
  3722. return ESR_Failed;
  3723. if (!Continue)
  3724. break;
  3725. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3726. if (ESR != ESR_Continue)
  3727. return ESR;
  3728. if (FS->getInc()) {
  3729. FullExpressionRAII IncScope(Info);
  3730. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3731. return ESR_Failed;
  3732. }
  3733. }
  3734. return ESR_Succeeded;
  3735. }
  3736. case Stmt::CXXForRangeStmtClass: {
  3737. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3738. BlockScopeRAII Scope(Info);
  3739. // Evaluate the init-statement if present.
  3740. if (FS->getInit()) {
  3741. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3742. if (ESR != ESR_Succeeded)
  3743. return ESR;
  3744. }
  3745. // Initialize the __range variable.
  3746. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3747. if (ESR != ESR_Succeeded)
  3748. return ESR;
  3749. // Create the __begin and __end iterators.
  3750. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3751. if (ESR != ESR_Succeeded)
  3752. return ESR;
  3753. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3754. if (ESR != ESR_Succeeded)
  3755. return ESR;
  3756. while (true) {
  3757. // Condition: __begin != __end.
  3758. {
  3759. bool Continue = true;
  3760. FullExpressionRAII CondExpr(Info);
  3761. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3762. return ESR_Failed;
  3763. if (!Continue)
  3764. break;
  3765. }
  3766. // User's variable declaration, initialized by *__begin.
  3767. BlockScopeRAII InnerScope(Info);
  3768. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3769. if (ESR != ESR_Succeeded)
  3770. return ESR;
  3771. // Loop body.
  3772. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3773. if (ESR != ESR_Continue)
  3774. return ESR;
  3775. // Increment: ++__begin
  3776. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3777. return ESR_Failed;
  3778. }
  3779. return ESR_Succeeded;
  3780. }
  3781. case Stmt::SwitchStmtClass:
  3782. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3783. case Stmt::ContinueStmtClass:
  3784. return ESR_Continue;
  3785. case Stmt::BreakStmtClass:
  3786. return ESR_Break;
  3787. case Stmt::LabelStmtClass:
  3788. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3789. case Stmt::AttributedStmtClass:
  3790. // As a general principle, C++11 attributes can be ignored without
  3791. // any semantic impact.
  3792. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3793. Case);
  3794. case Stmt::CaseStmtClass:
  3795. case Stmt::DefaultStmtClass:
  3796. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3797. }
  3798. }
  3799. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3800. /// default constructor. If so, we'll fold it whether or not it's marked as
  3801. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3802. /// so we need special handling.
  3803. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3804. const CXXConstructorDecl *CD,
  3805. bool IsValueInitialization) {
  3806. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3807. return false;
  3808. // Value-initialization does not call a trivial default constructor, so such a
  3809. // call is a core constant expression whether or not the constructor is
  3810. // constexpr.
  3811. if (!CD->isConstexpr() && !IsValueInitialization) {
  3812. if (Info.getLangOpts().CPlusPlus11) {
  3813. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3814. // we should be much more explicit about why it's not constexpr.
  3815. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3816. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3817. Info.Note(CD->getLocation(), diag::note_declared_at);
  3818. } else {
  3819. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3820. }
  3821. }
  3822. return true;
  3823. }
  3824. /// CheckConstexprFunction - Check that a function can be called in a constant
  3825. /// expression.
  3826. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3827. const FunctionDecl *Declaration,
  3828. const FunctionDecl *Definition,
  3829. const Stmt *Body) {
  3830. // Potential constant expressions can contain calls to declared, but not yet
  3831. // defined, constexpr functions.
  3832. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3833. Declaration->isConstexpr())
  3834. return false;
  3835. // Bail out if the function declaration itself is invalid. We will
  3836. // have produced a relevant diagnostic while parsing it, so just
  3837. // note the problematic sub-expression.
  3838. if (Declaration->isInvalidDecl()) {
  3839. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3840. return false;
  3841. }
  3842. // Can we evaluate this function call?
  3843. if (Definition && Definition->isConstexpr() &&
  3844. !Definition->isInvalidDecl() && Body)
  3845. return true;
  3846. if (Info.getLangOpts().CPlusPlus11) {
  3847. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3848. // If this function is not constexpr because it is an inherited
  3849. // non-constexpr constructor, diagnose that directly.
  3850. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3851. if (CD && CD->isInheritingConstructor()) {
  3852. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3853. if (!Inherited->isConstexpr())
  3854. DiagDecl = CD = Inherited;
  3855. }
  3856. // FIXME: If DiagDecl is an implicitly-declared special member function
  3857. // or an inheriting constructor, we should be much more explicit about why
  3858. // it's not constexpr.
  3859. if (CD && CD->isInheritingConstructor())
  3860. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3861. << CD->getInheritedConstructor().getConstructor()->getParent();
  3862. else
  3863. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3864. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3865. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3866. } else {
  3867. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3868. }
  3869. return false;
  3870. }
  3871. /// Determine if a class has any fields that might need to be copied by a
  3872. /// trivial copy or move operation.
  3873. static bool hasFields(const CXXRecordDecl *RD) {
  3874. if (!RD || RD->isEmpty())
  3875. return false;
  3876. for (auto *FD : RD->fields()) {
  3877. if (FD->isUnnamedBitfield())
  3878. continue;
  3879. return true;
  3880. }
  3881. for (auto &Base : RD->bases())
  3882. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3883. return true;
  3884. return false;
  3885. }
  3886. namespace {
  3887. typedef SmallVector<APValue, 8> ArgVector;
  3888. }
  3889. /// EvaluateArgs - Evaluate the arguments to a function call.
  3890. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3891. EvalInfo &Info) {
  3892. bool Success = true;
  3893. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3894. I != E; ++I) {
  3895. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3896. // If we're checking for a potential constant expression, evaluate all
  3897. // initializers even if some of them fail.
  3898. if (!Info.noteFailure())
  3899. return false;
  3900. Success = false;
  3901. }
  3902. }
  3903. return Success;
  3904. }
  3905. /// Evaluate a function call.
  3906. static bool HandleFunctionCall(SourceLocation CallLoc,
  3907. const FunctionDecl *Callee, const LValue *This,
  3908. ArrayRef<const Expr*> Args, const Stmt *Body,
  3909. EvalInfo &Info, APValue &Result,
  3910. const LValue *ResultSlot) {
  3911. ArgVector ArgValues(Args.size());
  3912. if (!EvaluateArgs(Args, ArgValues, Info))
  3913. return false;
  3914. if (!Info.CheckCallLimit(CallLoc))
  3915. return false;
  3916. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3917. // For a trivial copy or move assignment, perform an APValue copy. This is
  3918. // essential for unions, where the operations performed by the assignment
  3919. // operator cannot be represented as statements.
  3920. //
  3921. // Skip this for non-union classes with no fields; in that case, the defaulted
  3922. // copy/move does not actually read the object.
  3923. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3924. if (MD && MD->isDefaulted() &&
  3925. (MD->getParent()->isUnion() ||
  3926. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3927. assert(This &&
  3928. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3929. LValue RHS;
  3930. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3931. APValue RHSValue;
  3932. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3933. RHS, RHSValue))
  3934. return false;
  3935. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3936. RHSValue))
  3937. return false;
  3938. This->moveInto(Result);
  3939. return true;
  3940. } else if (MD && isLambdaCallOperator(MD)) {
  3941. // We're in a lambda; determine the lambda capture field maps unless we're
  3942. // just constexpr checking a lambda's call operator. constexpr checking is
  3943. // done before the captures have been added to the closure object (unless
  3944. // we're inferring constexpr-ness), so we don't have access to them in this
  3945. // case. But since we don't need the captures to constexpr check, we can
  3946. // just ignore them.
  3947. if (!Info.checkingPotentialConstantExpression())
  3948. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  3949. Frame.LambdaThisCaptureField);
  3950. }
  3951. StmtResult Ret = {Result, ResultSlot};
  3952. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  3953. if (ESR == ESR_Succeeded) {
  3954. if (Callee->getReturnType()->isVoidType())
  3955. return true;
  3956. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  3957. }
  3958. return ESR == ESR_Returned;
  3959. }
  3960. /// Evaluate a constructor call.
  3961. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3962. APValue *ArgValues,
  3963. const CXXConstructorDecl *Definition,
  3964. EvalInfo &Info, APValue &Result) {
  3965. SourceLocation CallLoc = E->getExprLoc();
  3966. if (!Info.CheckCallLimit(CallLoc))
  3967. return false;
  3968. const CXXRecordDecl *RD = Definition->getParent();
  3969. if (RD->getNumVBases()) {
  3970. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3971. return false;
  3972. }
  3973. EvalInfo::EvaluatingConstructorRAII EvalObj(
  3974. Info, {This.getLValueBase(),
  3975. {This.getLValueCallIndex(), This.getLValueVersion()}});
  3976. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  3977. // FIXME: Creating an APValue just to hold a nonexistent return value is
  3978. // wasteful.
  3979. APValue RetVal;
  3980. StmtResult Ret = {RetVal, nullptr};
  3981. // If it's a delegating constructor, delegate.
  3982. if (Definition->isDelegatingConstructor()) {
  3983. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3984. {
  3985. FullExpressionRAII InitScope(Info);
  3986. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3987. return false;
  3988. }
  3989. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3990. }
  3991. // For a trivial copy or move constructor, perform an APValue copy. This is
  3992. // essential for unions (or classes with anonymous union members), where the
  3993. // operations performed by the constructor cannot be represented by
  3994. // ctor-initializers.
  3995. //
  3996. // Skip this for empty non-union classes; we should not perform an
  3997. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3998. // actually read them.
  3999. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4000. (Definition->getParent()->isUnion() ||
  4001. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4002. LValue RHS;
  4003. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4004. return handleLValueToRValueConversion(
  4005. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4006. RHS, Result);
  4007. }
  4008. // Reserve space for the struct members.
  4009. if (!RD->isUnion() && Result.isUninit())
  4010. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4011. std::distance(RD->field_begin(), RD->field_end()));
  4012. if (RD->isInvalidDecl()) return false;
  4013. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4014. // A scope for temporaries lifetime-extended by reference members.
  4015. BlockScopeRAII LifetimeExtendedScope(Info);
  4016. bool Success = true;
  4017. unsigned BasesSeen = 0;
  4018. #ifndef NDEBUG
  4019. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4020. #endif
  4021. for (const auto *I : Definition->inits()) {
  4022. LValue Subobject = This;
  4023. LValue SubobjectParent = This;
  4024. APValue *Value = &Result;
  4025. // Determine the subobject to initialize.
  4026. FieldDecl *FD = nullptr;
  4027. if (I->isBaseInitializer()) {
  4028. QualType BaseType(I->getBaseClass(), 0);
  4029. #ifndef NDEBUG
  4030. // Non-virtual base classes are initialized in the order in the class
  4031. // definition. We have already checked for virtual base classes.
  4032. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4033. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4034. "base class initializers not in expected order");
  4035. ++BaseIt;
  4036. #endif
  4037. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4038. BaseType->getAsCXXRecordDecl(), &Layout))
  4039. return false;
  4040. Value = &Result.getStructBase(BasesSeen++);
  4041. } else if ((FD = I->getMember())) {
  4042. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4043. return false;
  4044. if (RD->isUnion()) {
  4045. Result = APValue(FD);
  4046. Value = &Result.getUnionValue();
  4047. } else {
  4048. Value = &Result.getStructField(FD->getFieldIndex());
  4049. }
  4050. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4051. // Walk the indirect field decl's chain to find the object to initialize,
  4052. // and make sure we've initialized every step along it.
  4053. auto IndirectFieldChain = IFD->chain();
  4054. for (auto *C : IndirectFieldChain) {
  4055. FD = cast<FieldDecl>(C);
  4056. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4057. // Switch the union field if it differs. This happens if we had
  4058. // preceding zero-initialization, and we're now initializing a union
  4059. // subobject other than the first.
  4060. // FIXME: In this case, the values of the other subobjects are
  4061. // specified, since zero-initialization sets all padding bits to zero.
  4062. if (Value->isUninit() ||
  4063. (Value->isUnion() && Value->getUnionField() != FD)) {
  4064. if (CD->isUnion())
  4065. *Value = APValue(FD);
  4066. else
  4067. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4068. std::distance(CD->field_begin(), CD->field_end()));
  4069. }
  4070. // Store Subobject as its parent before updating it for the last element
  4071. // in the chain.
  4072. if (C == IndirectFieldChain.back())
  4073. SubobjectParent = Subobject;
  4074. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4075. return false;
  4076. if (CD->isUnion())
  4077. Value = &Value->getUnionValue();
  4078. else
  4079. Value = &Value->getStructField(FD->getFieldIndex());
  4080. }
  4081. } else {
  4082. llvm_unreachable("unknown base initializer kind");
  4083. }
  4084. // Need to override This for implicit field initializers as in this case
  4085. // This refers to innermost anonymous struct/union containing initializer,
  4086. // not to currently constructed class.
  4087. const Expr *Init = I->getInit();
  4088. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4089. isa<CXXDefaultInitExpr>(Init));
  4090. FullExpressionRAII InitScope(Info);
  4091. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4092. (FD && FD->isBitField() &&
  4093. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4094. // If we're checking for a potential constant expression, evaluate all
  4095. // initializers even if some of them fail.
  4096. if (!Info.noteFailure())
  4097. return false;
  4098. Success = false;
  4099. }
  4100. }
  4101. return Success &&
  4102. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4103. }
  4104. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4105. ArrayRef<const Expr*> Args,
  4106. const CXXConstructorDecl *Definition,
  4107. EvalInfo &Info, APValue &Result) {
  4108. ArgVector ArgValues(Args.size());
  4109. if (!EvaluateArgs(Args, ArgValues, Info))
  4110. return false;
  4111. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4112. Info, Result);
  4113. }
  4114. //===----------------------------------------------------------------------===//
  4115. // Generic Evaluation
  4116. //===----------------------------------------------------------------------===//
  4117. namespace {
  4118. template <class Derived>
  4119. class ExprEvaluatorBase
  4120. : public ConstStmtVisitor<Derived, bool> {
  4121. private:
  4122. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4123. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4124. return getDerived().Success(V, E);
  4125. }
  4126. bool DerivedZeroInitialization(const Expr *E) {
  4127. return getDerived().ZeroInitialization(E);
  4128. }
  4129. // Check whether a conditional operator with a non-constant condition is a
  4130. // potential constant expression. If neither arm is a potential constant
  4131. // expression, then the conditional operator is not either.
  4132. template<typename ConditionalOperator>
  4133. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4134. assert(Info.checkingPotentialConstantExpression());
  4135. // Speculatively evaluate both arms.
  4136. SmallVector<PartialDiagnosticAt, 8> Diag;
  4137. {
  4138. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4139. StmtVisitorTy::Visit(E->getFalseExpr());
  4140. if (Diag.empty())
  4141. return;
  4142. }
  4143. {
  4144. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4145. Diag.clear();
  4146. StmtVisitorTy::Visit(E->getTrueExpr());
  4147. if (Diag.empty())
  4148. return;
  4149. }
  4150. Error(E, diag::note_constexpr_conditional_never_const);
  4151. }
  4152. template<typename ConditionalOperator>
  4153. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4154. bool BoolResult;
  4155. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4156. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4157. CheckPotentialConstantConditional(E);
  4158. return false;
  4159. }
  4160. if (Info.noteFailure()) {
  4161. StmtVisitorTy::Visit(E->getTrueExpr());
  4162. StmtVisitorTy::Visit(E->getFalseExpr());
  4163. }
  4164. return false;
  4165. }
  4166. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4167. return StmtVisitorTy::Visit(EvalExpr);
  4168. }
  4169. protected:
  4170. EvalInfo &Info;
  4171. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4172. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4173. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4174. return Info.CCEDiag(E, D);
  4175. }
  4176. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4177. public:
  4178. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4179. EvalInfo &getEvalInfo() { return Info; }
  4180. /// Report an evaluation error. This should only be called when an error is
  4181. /// first discovered. When propagating an error, just return false.
  4182. bool Error(const Expr *E, diag::kind D) {
  4183. Info.FFDiag(E, D);
  4184. return false;
  4185. }
  4186. bool Error(const Expr *E) {
  4187. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4188. }
  4189. bool VisitStmt(const Stmt *) {
  4190. llvm_unreachable("Expression evaluator should not be called on stmts");
  4191. }
  4192. bool VisitExpr(const Expr *E) {
  4193. return Error(E);
  4194. }
  4195. bool VisitParenExpr(const ParenExpr *E)
  4196. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4197. bool VisitUnaryExtension(const UnaryOperator *E)
  4198. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4199. bool VisitUnaryPlus(const UnaryOperator *E)
  4200. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4201. bool VisitChooseExpr(const ChooseExpr *E)
  4202. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4203. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4204. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4205. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4206. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4207. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4208. TempVersionRAII RAII(*Info.CurrentCall);
  4209. return StmtVisitorTy::Visit(E->getExpr());
  4210. }
  4211. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4212. TempVersionRAII RAII(*Info.CurrentCall);
  4213. // The initializer may not have been parsed yet, or might be erroneous.
  4214. if (!E->getExpr())
  4215. return Error(E);
  4216. return StmtVisitorTy::Visit(E->getExpr());
  4217. }
  4218. // We cannot create any objects for which cleanups are required, so there is
  4219. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4220. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4221. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4222. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4223. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4224. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4225. }
  4226. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4227. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4228. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4229. }
  4230. bool VisitBinaryOperator(const BinaryOperator *E) {
  4231. switch (E->getOpcode()) {
  4232. default:
  4233. return Error(E);
  4234. case BO_Comma:
  4235. VisitIgnoredValue(E->getLHS());
  4236. return StmtVisitorTy::Visit(E->getRHS());
  4237. case BO_PtrMemD:
  4238. case BO_PtrMemI: {
  4239. LValue Obj;
  4240. if (!HandleMemberPointerAccess(Info, E, Obj))
  4241. return false;
  4242. APValue Result;
  4243. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4244. return false;
  4245. return DerivedSuccess(Result, E);
  4246. }
  4247. }
  4248. }
  4249. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4250. // Evaluate and cache the common expression. We treat it as a temporary,
  4251. // even though it's not quite the same thing.
  4252. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4253. Info, E->getCommon()))
  4254. return false;
  4255. return HandleConditionalOperator(E);
  4256. }
  4257. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4258. bool IsBcpCall = false;
  4259. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4260. // the result is a constant expression if it can be folded without
  4261. // side-effects. This is an important GNU extension. See GCC PR38377
  4262. // for discussion.
  4263. if (const CallExpr *CallCE =
  4264. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4265. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4266. IsBcpCall = true;
  4267. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4268. // constant expression; we can't check whether it's potentially foldable.
  4269. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4270. return false;
  4271. FoldConstant Fold(Info, IsBcpCall);
  4272. if (!HandleConditionalOperator(E)) {
  4273. Fold.keepDiagnostics();
  4274. return false;
  4275. }
  4276. return true;
  4277. }
  4278. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4279. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4280. return DerivedSuccess(*Value, E);
  4281. const Expr *Source = E->getSourceExpr();
  4282. if (!Source)
  4283. return Error(E);
  4284. if (Source == E) { // sanity checking.
  4285. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4286. return Error(E);
  4287. }
  4288. return StmtVisitorTy::Visit(Source);
  4289. }
  4290. bool VisitCallExpr(const CallExpr *E) {
  4291. APValue Result;
  4292. if (!handleCallExpr(E, Result, nullptr))
  4293. return false;
  4294. return DerivedSuccess(Result, E);
  4295. }
  4296. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4297. const LValue *ResultSlot) {
  4298. const Expr *Callee = E->getCallee()->IgnoreParens();
  4299. QualType CalleeType = Callee->getType();
  4300. const FunctionDecl *FD = nullptr;
  4301. LValue *This = nullptr, ThisVal;
  4302. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4303. bool HasQualifier = false;
  4304. // Extract function decl and 'this' pointer from the callee.
  4305. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4306. const ValueDecl *Member = nullptr;
  4307. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4308. // Explicit bound member calls, such as x.f() or p->g();
  4309. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4310. return false;
  4311. Member = ME->getMemberDecl();
  4312. This = &ThisVal;
  4313. HasQualifier = ME->hasQualifier();
  4314. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4315. // Indirect bound member calls ('.*' or '->*').
  4316. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  4317. if (!Member) return false;
  4318. This = &ThisVal;
  4319. } else
  4320. return Error(Callee);
  4321. FD = dyn_cast<FunctionDecl>(Member);
  4322. if (!FD)
  4323. return Error(Callee);
  4324. } else if (CalleeType->isFunctionPointerType()) {
  4325. LValue Call;
  4326. if (!EvaluatePointer(Callee, Call, Info))
  4327. return false;
  4328. if (!Call.getLValueOffset().isZero())
  4329. return Error(Callee);
  4330. FD = dyn_cast_or_null<FunctionDecl>(
  4331. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4332. if (!FD)
  4333. return Error(Callee);
  4334. // Don't call function pointers which have been cast to some other type.
  4335. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4336. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4337. CalleeType->getPointeeType(), FD->getType())) {
  4338. return Error(E);
  4339. }
  4340. // Overloaded operator calls to member functions are represented as normal
  4341. // calls with '*this' as the first argument.
  4342. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4343. if (MD && !MD->isStatic()) {
  4344. // FIXME: When selecting an implicit conversion for an overloaded
  4345. // operator delete, we sometimes try to evaluate calls to conversion
  4346. // operators without a 'this' parameter!
  4347. if (Args.empty())
  4348. return Error(E);
  4349. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4350. return false;
  4351. This = &ThisVal;
  4352. Args = Args.slice(1);
  4353. } else if (MD && MD->isLambdaStaticInvoker()) {
  4354. // Map the static invoker for the lambda back to the call operator.
  4355. // Conveniently, we don't have to slice out the 'this' argument (as is
  4356. // being done for the non-static case), since a static member function
  4357. // doesn't have an implicit argument passed in.
  4358. const CXXRecordDecl *ClosureClass = MD->getParent();
  4359. assert(
  4360. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  4361. "Number of captures must be zero for conversion to function-ptr");
  4362. const CXXMethodDecl *LambdaCallOp =
  4363. ClosureClass->getLambdaCallOperator();
  4364. // Set 'FD', the function that will be called below, to the call
  4365. // operator. If the closure object represents a generic lambda, find
  4366. // the corresponding specialization of the call operator.
  4367. if (ClosureClass->isGenericLambda()) {
  4368. assert(MD->isFunctionTemplateSpecialization() &&
  4369. "A generic lambda's static-invoker function must be a "
  4370. "template specialization");
  4371. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  4372. FunctionTemplateDecl *CallOpTemplate =
  4373. LambdaCallOp->getDescribedFunctionTemplate();
  4374. void *InsertPos = nullptr;
  4375. FunctionDecl *CorrespondingCallOpSpecialization =
  4376. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  4377. assert(CorrespondingCallOpSpecialization &&
  4378. "We must always have a function call operator specialization "
  4379. "that corresponds to our static invoker specialization");
  4380. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  4381. } else
  4382. FD = LambdaCallOp;
  4383. }
  4384. } else
  4385. return Error(E);
  4386. if (This && !This->checkSubobject(Info, E, CSK_This))
  4387. return false;
  4388. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  4389. // calls to such functions in constant expressions.
  4390. if (This && !HasQualifier &&
  4391. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  4392. return Error(E, diag::note_constexpr_virtual_call);
  4393. const FunctionDecl *Definition = nullptr;
  4394. Stmt *Body = FD->getBody(Definition);
  4395. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  4396. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  4397. Result, ResultSlot))
  4398. return false;
  4399. return true;
  4400. }
  4401. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4402. return StmtVisitorTy::Visit(E->getInitializer());
  4403. }
  4404. bool VisitInitListExpr(const InitListExpr *E) {
  4405. if (E->getNumInits() == 0)
  4406. return DerivedZeroInitialization(E);
  4407. if (E->getNumInits() == 1)
  4408. return StmtVisitorTy::Visit(E->getInit(0));
  4409. return Error(E);
  4410. }
  4411. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  4412. return DerivedZeroInitialization(E);
  4413. }
  4414. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  4415. return DerivedZeroInitialization(E);
  4416. }
  4417. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  4418. return DerivedZeroInitialization(E);
  4419. }
  4420. /// A member expression where the object is a prvalue is itself a prvalue.
  4421. bool VisitMemberExpr(const MemberExpr *E) {
  4422. assert(!E->isArrow() && "missing call to bound member function?");
  4423. APValue Val;
  4424. if (!Evaluate(Val, Info, E->getBase()))
  4425. return false;
  4426. QualType BaseTy = E->getBase()->getType();
  4427. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4428. if (!FD) return Error(E);
  4429. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4430. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4431. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4432. CompleteObject Obj(&Val, BaseTy, true);
  4433. SubobjectDesignator Designator(BaseTy);
  4434. Designator.addDeclUnchecked(FD);
  4435. APValue Result;
  4436. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4437. DerivedSuccess(Result, E);
  4438. }
  4439. bool VisitCastExpr(const CastExpr *E) {
  4440. switch (E->getCastKind()) {
  4441. default:
  4442. break;
  4443. case CK_AtomicToNonAtomic: {
  4444. APValue AtomicVal;
  4445. // This does not need to be done in place even for class/array types:
  4446. // atomic-to-non-atomic conversion implies copying the object
  4447. // representation.
  4448. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  4449. return false;
  4450. return DerivedSuccess(AtomicVal, E);
  4451. }
  4452. case CK_NoOp:
  4453. case CK_UserDefinedConversion:
  4454. return StmtVisitorTy::Visit(E->getSubExpr());
  4455. case CK_LValueToRValue: {
  4456. LValue LVal;
  4457. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4458. return false;
  4459. APValue RVal;
  4460. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4461. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4462. LVal, RVal))
  4463. return false;
  4464. return DerivedSuccess(RVal, E);
  4465. }
  4466. }
  4467. return Error(E);
  4468. }
  4469. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4470. return VisitUnaryPostIncDec(UO);
  4471. }
  4472. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4473. return VisitUnaryPostIncDec(UO);
  4474. }
  4475. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4476. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4477. return Error(UO);
  4478. LValue LVal;
  4479. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4480. return false;
  4481. APValue RVal;
  4482. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4483. UO->isIncrementOp(), &RVal))
  4484. return false;
  4485. return DerivedSuccess(RVal, UO);
  4486. }
  4487. bool VisitStmtExpr(const StmtExpr *E) {
  4488. // We will have checked the full-expressions inside the statement expression
  4489. // when they were completed, and don't need to check them again now.
  4490. if (Info.checkingForOverflow())
  4491. return Error(E);
  4492. BlockScopeRAII Scope(Info);
  4493. const CompoundStmt *CS = E->getSubStmt();
  4494. if (CS->body_empty())
  4495. return true;
  4496. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4497. BE = CS->body_end();
  4498. /**/; ++BI) {
  4499. if (BI + 1 == BE) {
  4500. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4501. if (!FinalExpr) {
  4502. Info.FFDiag((*BI)->getBeginLoc(),
  4503. diag::note_constexpr_stmt_expr_unsupported);
  4504. return false;
  4505. }
  4506. return this->Visit(FinalExpr);
  4507. }
  4508. APValue ReturnValue;
  4509. StmtResult Result = { ReturnValue, nullptr };
  4510. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4511. if (ESR != ESR_Succeeded) {
  4512. // FIXME: If the statement-expression terminated due to 'return',
  4513. // 'break', or 'continue', it would be nice to propagate that to
  4514. // the outer statement evaluation rather than bailing out.
  4515. if (ESR != ESR_Failed)
  4516. Info.FFDiag((*BI)->getBeginLoc(),
  4517. diag::note_constexpr_stmt_expr_unsupported);
  4518. return false;
  4519. }
  4520. }
  4521. llvm_unreachable("Return from function from the loop above.");
  4522. }
  4523. /// Visit a value which is evaluated, but whose value is ignored.
  4524. void VisitIgnoredValue(const Expr *E) {
  4525. EvaluateIgnoredValue(Info, E);
  4526. }
  4527. /// Potentially visit a MemberExpr's base expression.
  4528. void VisitIgnoredBaseExpression(const Expr *E) {
  4529. // While MSVC doesn't evaluate the base expression, it does diagnose the
  4530. // presence of side-effecting behavior.
  4531. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  4532. return;
  4533. VisitIgnoredValue(E);
  4534. }
  4535. };
  4536. } // namespace
  4537. //===----------------------------------------------------------------------===//
  4538. // Common base class for lvalue and temporary evaluation.
  4539. //===----------------------------------------------------------------------===//
  4540. namespace {
  4541. template<class Derived>
  4542. class LValueExprEvaluatorBase
  4543. : public ExprEvaluatorBase<Derived> {
  4544. protected:
  4545. LValue &Result;
  4546. bool InvalidBaseOK;
  4547. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  4548. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  4549. bool Success(APValue::LValueBase B) {
  4550. Result.set(B);
  4551. return true;
  4552. }
  4553. bool evaluatePointer(const Expr *E, LValue &Result) {
  4554. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  4555. }
  4556. public:
  4557. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  4558. : ExprEvaluatorBaseTy(Info), Result(Result),
  4559. InvalidBaseOK(InvalidBaseOK) {}
  4560. bool Success(const APValue &V, const Expr *E) {
  4561. Result.setFrom(this->Info.Ctx, V);
  4562. return true;
  4563. }
  4564. bool VisitMemberExpr(const MemberExpr *E) {
  4565. // Handle non-static data members.
  4566. QualType BaseTy;
  4567. bool EvalOK;
  4568. if (E->isArrow()) {
  4569. EvalOK = evaluatePointer(E->getBase(), Result);
  4570. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  4571. } else if (E->getBase()->isRValue()) {
  4572. assert(E->getBase()->getType()->isRecordType());
  4573. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  4574. BaseTy = E->getBase()->getType();
  4575. } else {
  4576. EvalOK = this->Visit(E->getBase());
  4577. BaseTy = E->getBase()->getType();
  4578. }
  4579. if (!EvalOK) {
  4580. if (!InvalidBaseOK)
  4581. return false;
  4582. Result.setInvalid(E);
  4583. return true;
  4584. }
  4585. const ValueDecl *MD = E->getMemberDecl();
  4586. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  4587. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4588. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4589. (void)BaseTy;
  4590. if (!HandleLValueMember(this->Info, E, Result, FD))
  4591. return false;
  4592. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  4593. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  4594. return false;
  4595. } else
  4596. return this->Error(E);
  4597. if (MD->getType()->isReferenceType()) {
  4598. APValue RefValue;
  4599. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  4600. RefValue))
  4601. return false;
  4602. return Success(RefValue, E);
  4603. }
  4604. return true;
  4605. }
  4606. bool VisitBinaryOperator(const BinaryOperator *E) {
  4607. switch (E->getOpcode()) {
  4608. default:
  4609. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4610. case BO_PtrMemD:
  4611. case BO_PtrMemI:
  4612. return HandleMemberPointerAccess(this->Info, E, Result);
  4613. }
  4614. }
  4615. bool VisitCastExpr(const CastExpr *E) {
  4616. switch (E->getCastKind()) {
  4617. default:
  4618. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4619. case CK_DerivedToBase:
  4620. case CK_UncheckedDerivedToBase:
  4621. if (!this->Visit(E->getSubExpr()))
  4622. return false;
  4623. // Now figure out the necessary offset to add to the base LV to get from
  4624. // the derived class to the base class.
  4625. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4626. Result);
  4627. }
  4628. }
  4629. };
  4630. }
  4631. //===----------------------------------------------------------------------===//
  4632. // LValue Evaluation
  4633. //
  4634. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4635. // function designators (in C), decl references to void objects (in C), and
  4636. // temporaries (if building with -Wno-address-of-temporary).
  4637. //
  4638. // LValue evaluation produces values comprising a base expression of one of the
  4639. // following types:
  4640. // - Declarations
  4641. // * VarDecl
  4642. // * FunctionDecl
  4643. // - Literals
  4644. // * CompoundLiteralExpr in C (and in global scope in C++)
  4645. // * StringLiteral
  4646. // * CXXTypeidExpr
  4647. // * PredefinedExpr
  4648. // * ObjCStringLiteralExpr
  4649. // * ObjCEncodeExpr
  4650. // * AddrLabelExpr
  4651. // * BlockExpr
  4652. // * CallExpr for a MakeStringConstant builtin
  4653. // - Locals and temporaries
  4654. // * MaterializeTemporaryExpr
  4655. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4656. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4657. // from the AST (FIXME).
  4658. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4659. // CallIndex, for a lifetime-extended temporary.
  4660. // plus an offset in bytes.
  4661. //===----------------------------------------------------------------------===//
  4662. namespace {
  4663. class LValueExprEvaluator
  4664. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4665. public:
  4666. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  4667. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  4668. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4669. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4670. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4671. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4672. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4673. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4674. bool VisitMemberExpr(const MemberExpr *E);
  4675. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4676. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4677. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4678. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4679. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4680. bool VisitUnaryDeref(const UnaryOperator *E);
  4681. bool VisitUnaryReal(const UnaryOperator *E);
  4682. bool VisitUnaryImag(const UnaryOperator *E);
  4683. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4684. return VisitUnaryPreIncDec(UO);
  4685. }
  4686. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4687. return VisitUnaryPreIncDec(UO);
  4688. }
  4689. bool VisitBinAssign(const BinaryOperator *BO);
  4690. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4691. bool VisitCastExpr(const CastExpr *E) {
  4692. switch (E->getCastKind()) {
  4693. default:
  4694. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4695. case CK_LValueBitCast:
  4696. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4697. if (!Visit(E->getSubExpr()))
  4698. return false;
  4699. Result.Designator.setInvalid();
  4700. return true;
  4701. case CK_BaseToDerived:
  4702. if (!Visit(E->getSubExpr()))
  4703. return false;
  4704. return HandleBaseToDerivedCast(Info, E, Result);
  4705. }
  4706. }
  4707. };
  4708. } // end anonymous namespace
  4709. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4710. /// expressions which are not glvalues, in three cases:
  4711. /// * function designators in C, and
  4712. /// * "extern void" objects
  4713. /// * @selector() expressions in Objective-C
  4714. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  4715. bool InvalidBaseOK) {
  4716. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4717. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  4718. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  4719. }
  4720. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4721. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4722. return Success(FD);
  4723. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4724. return VisitVarDecl(E, VD);
  4725. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  4726. return Visit(BD->getBinding());
  4727. return Error(E);
  4728. }
  4729. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4730. // If we are within a lambda's call operator, check whether the 'VD' referred
  4731. // to within 'E' actually represents a lambda-capture that maps to a
  4732. // data-member/field within the closure object, and if so, evaluate to the
  4733. // field or what the field refers to.
  4734. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  4735. isa<DeclRefExpr>(E) &&
  4736. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  4737. // We don't always have a complete capture-map when checking or inferring if
  4738. // the function call operator meets the requirements of a constexpr function
  4739. // - but we don't need to evaluate the captures to determine constexprness
  4740. // (dcl.constexpr C++17).
  4741. if (Info.checkingPotentialConstantExpression())
  4742. return false;
  4743. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  4744. // Start with 'Result' referring to the complete closure object...
  4745. Result = *Info.CurrentCall->This;
  4746. // ... then update it to refer to the field of the closure object
  4747. // that represents the capture.
  4748. if (!HandleLValueMember(Info, E, Result, FD))
  4749. return false;
  4750. // And if the field is of reference type, update 'Result' to refer to what
  4751. // the field refers to.
  4752. if (FD->getType()->isReferenceType()) {
  4753. APValue RVal;
  4754. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  4755. RVal))
  4756. return false;
  4757. Result.setFrom(Info.Ctx, RVal);
  4758. }
  4759. return true;
  4760. }
  4761. }
  4762. CallStackFrame *Frame = nullptr;
  4763. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  4764. // Only if a local variable was declared in the function currently being
  4765. // evaluated, do we expect to be able to find its value in the current
  4766. // frame. (Otherwise it was likely declared in an enclosing context and
  4767. // could either have a valid evaluatable value (for e.g. a constexpr
  4768. // variable) or be ill-formed (and trigger an appropriate evaluation
  4769. // diagnostic)).
  4770. if (Info.CurrentCall->Callee &&
  4771. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  4772. Frame = Info.CurrentCall;
  4773. }
  4774. }
  4775. if (!VD->getType()->isReferenceType()) {
  4776. if (Frame) {
  4777. Result.set({VD, Frame->Index,
  4778. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  4779. return true;
  4780. }
  4781. return Success(VD);
  4782. }
  4783. APValue *V;
  4784. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  4785. return false;
  4786. if (V->isUninit()) {
  4787. if (!Info.checkingPotentialConstantExpression())
  4788. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  4789. return false;
  4790. }
  4791. return Success(*V, E);
  4792. }
  4793. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4794. const MaterializeTemporaryExpr *E) {
  4795. // Walk through the expression to find the materialized temporary itself.
  4796. SmallVector<const Expr *, 2> CommaLHSs;
  4797. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4798. const Expr *Inner = E->GetTemporaryExpr()->
  4799. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4800. // If we passed any comma operators, evaluate their LHSs.
  4801. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4802. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4803. return false;
  4804. // A materialized temporary with static storage duration can appear within the
  4805. // result of a constant expression evaluation, so we need to preserve its
  4806. // value for use outside this evaluation.
  4807. APValue *Value;
  4808. if (E->getStorageDuration() == SD_Static) {
  4809. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4810. *Value = APValue();
  4811. Result.set(E);
  4812. } else {
  4813. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  4814. *Info.CurrentCall);
  4815. }
  4816. QualType Type = Inner->getType();
  4817. // Materialize the temporary itself.
  4818. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4819. (E->getStorageDuration() == SD_Static &&
  4820. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4821. *Value = APValue();
  4822. return false;
  4823. }
  4824. // Adjust our lvalue to refer to the desired subobject.
  4825. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4826. --I;
  4827. switch (Adjustments[I].Kind) {
  4828. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4829. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4830. Type, Result))
  4831. return false;
  4832. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4833. break;
  4834. case SubobjectAdjustment::FieldAdjustment:
  4835. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4836. return false;
  4837. Type = Adjustments[I].Field->getType();
  4838. break;
  4839. case SubobjectAdjustment::MemberPointerAdjustment:
  4840. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4841. Adjustments[I].Ptr.RHS))
  4842. return false;
  4843. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4844. break;
  4845. }
  4846. }
  4847. return true;
  4848. }
  4849. bool
  4850. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4851. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  4852. "lvalue compound literal in c++?");
  4853. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4854. // only see this when folding in C, so there's no standard to follow here.
  4855. return Success(E);
  4856. }
  4857. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4858. if (!E->isPotentiallyEvaluated())
  4859. return Success(E);
  4860. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  4861. << E->getExprOperand()->getType()
  4862. << E->getExprOperand()->getSourceRange();
  4863. return false;
  4864. }
  4865. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4866. return Success(E);
  4867. }
  4868. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4869. // Handle static data members.
  4870. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4871. VisitIgnoredBaseExpression(E->getBase());
  4872. return VisitVarDecl(E, VD);
  4873. }
  4874. // Handle static member functions.
  4875. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4876. if (MD->isStatic()) {
  4877. VisitIgnoredBaseExpression(E->getBase());
  4878. return Success(MD);
  4879. }
  4880. }
  4881. // Handle non-static data members.
  4882. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4883. }
  4884. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4885. // FIXME: Deal with vectors as array subscript bases.
  4886. if (E->getBase()->getType()->isVectorType())
  4887. return Error(E);
  4888. bool Success = true;
  4889. if (!evaluatePointer(E->getBase(), Result)) {
  4890. if (!Info.noteFailure())
  4891. return false;
  4892. Success = false;
  4893. }
  4894. APSInt Index;
  4895. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4896. return false;
  4897. return Success &&
  4898. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  4899. }
  4900. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4901. return evaluatePointer(E->getSubExpr(), Result);
  4902. }
  4903. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4904. if (!Visit(E->getSubExpr()))
  4905. return false;
  4906. // __real is a no-op on scalar lvalues.
  4907. if (E->getSubExpr()->getType()->isAnyComplexType())
  4908. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4909. return true;
  4910. }
  4911. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4912. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4913. "lvalue __imag__ on scalar?");
  4914. if (!Visit(E->getSubExpr()))
  4915. return false;
  4916. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4917. return true;
  4918. }
  4919. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4920. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4921. return Error(UO);
  4922. if (!this->Visit(UO->getSubExpr()))
  4923. return false;
  4924. return handleIncDec(
  4925. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4926. UO->isIncrementOp(), nullptr);
  4927. }
  4928. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4929. const CompoundAssignOperator *CAO) {
  4930. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4931. return Error(CAO);
  4932. APValue RHS;
  4933. // The overall lvalue result is the result of evaluating the LHS.
  4934. if (!this->Visit(CAO->getLHS())) {
  4935. if (Info.noteFailure())
  4936. Evaluate(RHS, this->Info, CAO->getRHS());
  4937. return false;
  4938. }
  4939. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4940. return false;
  4941. return handleCompoundAssignment(
  4942. this->Info, CAO,
  4943. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4944. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4945. }
  4946. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4947. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4948. return Error(E);
  4949. APValue NewVal;
  4950. if (!this->Visit(E->getLHS())) {
  4951. if (Info.noteFailure())
  4952. Evaluate(NewVal, this->Info, E->getRHS());
  4953. return false;
  4954. }
  4955. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4956. return false;
  4957. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4958. NewVal);
  4959. }
  4960. //===----------------------------------------------------------------------===//
  4961. // Pointer Evaluation
  4962. //===----------------------------------------------------------------------===//
  4963. /// Attempts to compute the number of bytes available at the pointer
  4964. /// returned by a function with the alloc_size attribute. Returns true if we
  4965. /// were successful. Places an unsigned number into `Result`.
  4966. ///
  4967. /// This expects the given CallExpr to be a call to a function with an
  4968. /// alloc_size attribute.
  4969. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  4970. const CallExpr *Call,
  4971. llvm::APInt &Result) {
  4972. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  4973. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  4974. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  4975. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  4976. if (Call->getNumArgs() <= SizeArgNo)
  4977. return false;
  4978. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  4979. if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
  4980. return false;
  4981. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  4982. return false;
  4983. Into = Into.zextOrSelf(BitsInSizeT);
  4984. return true;
  4985. };
  4986. APSInt SizeOfElem;
  4987. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  4988. return false;
  4989. if (!AllocSize->getNumElemsParam().isValid()) {
  4990. Result = std::move(SizeOfElem);
  4991. return true;
  4992. }
  4993. APSInt NumberOfElems;
  4994. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  4995. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  4996. return false;
  4997. bool Overflow;
  4998. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  4999. if (Overflow)
  5000. return false;
  5001. Result = std::move(BytesAvailable);
  5002. return true;
  5003. }
  5004. /// Convenience function. LVal's base must be a call to an alloc_size
  5005. /// function.
  5006. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5007. const LValue &LVal,
  5008. llvm::APInt &Result) {
  5009. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  5010. "Can't get the size of a non alloc_size function");
  5011. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  5012. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  5013. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  5014. }
  5015. /// Attempts to evaluate the given LValueBase as the result of a call to
  5016. /// a function with the alloc_size attribute. If it was possible to do so, this
  5017. /// function will return true, make Result's Base point to said function call,
  5018. /// and mark Result's Base as invalid.
  5019. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  5020. LValue &Result) {
  5021. if (Base.isNull())
  5022. return false;
  5023. // Because we do no form of static analysis, we only support const variables.
  5024. //
  5025. // Additionally, we can't support parameters, nor can we support static
  5026. // variables (in the latter case, use-before-assign isn't UB; in the former,
  5027. // we have no clue what they'll be assigned to).
  5028. const auto *VD =
  5029. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  5030. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  5031. return false;
  5032. const Expr *Init = VD->getAnyInitializer();
  5033. if (!Init)
  5034. return false;
  5035. const Expr *E = Init->IgnoreParens();
  5036. if (!tryUnwrapAllocSizeCall(E))
  5037. return false;
  5038. // Store E instead of E unwrapped so that the type of the LValue's base is
  5039. // what the user wanted.
  5040. Result.setInvalid(E);
  5041. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5042. Result.addUnsizedArray(Info, E, Pointee);
  5043. return true;
  5044. }
  5045. namespace {
  5046. class PointerExprEvaluator
  5047. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5048. LValue &Result;
  5049. bool InvalidBaseOK;
  5050. bool Success(const Expr *E) {
  5051. Result.set(E);
  5052. return true;
  5053. }
  5054. bool evaluateLValue(const Expr *E, LValue &Result) {
  5055. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5056. }
  5057. bool evaluatePointer(const Expr *E, LValue &Result) {
  5058. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5059. }
  5060. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5061. public:
  5062. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5063. : ExprEvaluatorBaseTy(info), Result(Result),
  5064. InvalidBaseOK(InvalidBaseOK) {}
  5065. bool Success(const APValue &V, const Expr *E) {
  5066. Result.setFrom(Info.Ctx, V);
  5067. return true;
  5068. }
  5069. bool ZeroInitialization(const Expr *E) {
  5070. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5071. Result.setNull(E->getType(), TargetVal);
  5072. return true;
  5073. }
  5074. bool VisitBinaryOperator(const BinaryOperator *E);
  5075. bool VisitCastExpr(const CastExpr* E);
  5076. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5077. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5078. { return Success(E); }
  5079. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5080. if (Info.noteFailure())
  5081. EvaluateIgnoredValue(Info, E->getSubExpr());
  5082. return Error(E);
  5083. }
  5084. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5085. { return Success(E); }
  5086. bool VisitCallExpr(const CallExpr *E);
  5087. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5088. bool VisitBlockExpr(const BlockExpr *E) {
  5089. if (!E->getBlockDecl()->hasCaptures())
  5090. return Success(E);
  5091. return Error(E);
  5092. }
  5093. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5094. // Can't look at 'this' when checking a potential constant expression.
  5095. if (Info.checkingPotentialConstantExpression())
  5096. return false;
  5097. if (!Info.CurrentCall->This) {
  5098. if (Info.getLangOpts().CPlusPlus11)
  5099. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5100. else
  5101. Info.FFDiag(E);
  5102. return false;
  5103. }
  5104. Result = *Info.CurrentCall->This;
  5105. // If we are inside a lambda's call operator, the 'this' expression refers
  5106. // to the enclosing '*this' object (either by value or reference) which is
  5107. // either copied into the closure object's field that represents the '*this'
  5108. // or refers to '*this'.
  5109. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5110. // Update 'Result' to refer to the data member/field of the closure object
  5111. // that represents the '*this' capture.
  5112. if (!HandleLValueMember(Info, E, Result,
  5113. Info.CurrentCall->LambdaThisCaptureField))
  5114. return false;
  5115. // If we captured '*this' by reference, replace the field with its referent.
  5116. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5117. ->isPointerType()) {
  5118. APValue RVal;
  5119. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5120. RVal))
  5121. return false;
  5122. Result.setFrom(Info.Ctx, RVal);
  5123. }
  5124. }
  5125. return true;
  5126. }
  5127. // FIXME: Missing: @protocol, @selector
  5128. };
  5129. } // end anonymous namespace
  5130. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5131. bool InvalidBaseOK) {
  5132. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5133. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5134. }
  5135. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5136. if (E->getOpcode() != BO_Add &&
  5137. E->getOpcode() != BO_Sub)
  5138. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5139. const Expr *PExp = E->getLHS();
  5140. const Expr *IExp = E->getRHS();
  5141. if (IExp->getType()->isPointerType())
  5142. std::swap(PExp, IExp);
  5143. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5144. if (!EvalPtrOK && !Info.noteFailure())
  5145. return false;
  5146. llvm::APSInt Offset;
  5147. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5148. return false;
  5149. if (E->getOpcode() == BO_Sub)
  5150. negateAsSigned(Offset);
  5151. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5152. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5153. }
  5154. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5155. return evaluateLValue(E->getSubExpr(), Result);
  5156. }
  5157. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5158. const Expr *SubExpr = E->getSubExpr();
  5159. switch (E->getCastKind()) {
  5160. default:
  5161. break;
  5162. case CK_BitCast:
  5163. case CK_CPointerToObjCPointerCast:
  5164. case CK_BlockPointerToObjCPointerCast:
  5165. case CK_AnyPointerToBlockPointerCast:
  5166. case CK_AddressSpaceConversion:
  5167. if (!Visit(SubExpr))
  5168. return false;
  5169. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5170. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5171. // also static_casts, but we disallow them as a resolution to DR1312.
  5172. if (!E->getType()->isVoidPointerType()) {
  5173. Result.Designator.setInvalid();
  5174. if (SubExpr->getType()->isVoidPointerType())
  5175. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5176. << 3 << SubExpr->getType();
  5177. else
  5178. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5179. }
  5180. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5181. ZeroInitialization(E);
  5182. return true;
  5183. case CK_DerivedToBase:
  5184. case CK_UncheckedDerivedToBase:
  5185. if (!evaluatePointer(E->getSubExpr(), Result))
  5186. return false;
  5187. if (!Result.Base && Result.Offset.isZero())
  5188. return true;
  5189. // Now figure out the necessary offset to add to the base LV to get from
  5190. // the derived class to the base class.
  5191. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5192. castAs<PointerType>()->getPointeeType(),
  5193. Result);
  5194. case CK_BaseToDerived:
  5195. if (!Visit(E->getSubExpr()))
  5196. return false;
  5197. if (!Result.Base && Result.Offset.isZero())
  5198. return true;
  5199. return HandleBaseToDerivedCast(Info, E, Result);
  5200. case CK_NullToPointer:
  5201. VisitIgnoredValue(E->getSubExpr());
  5202. return ZeroInitialization(E);
  5203. case CK_IntegralToPointer: {
  5204. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5205. APValue Value;
  5206. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5207. break;
  5208. if (Value.isInt()) {
  5209. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5210. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5211. Result.Base = (Expr*)nullptr;
  5212. Result.InvalidBase = false;
  5213. Result.Offset = CharUnits::fromQuantity(N);
  5214. Result.Designator.setInvalid();
  5215. Result.IsNullPtr = false;
  5216. return true;
  5217. } else {
  5218. // Cast is of an lvalue, no need to change value.
  5219. Result.setFrom(Info.Ctx, Value);
  5220. return true;
  5221. }
  5222. }
  5223. case CK_ArrayToPointerDecay: {
  5224. if (SubExpr->isGLValue()) {
  5225. if (!evaluateLValue(SubExpr, Result))
  5226. return false;
  5227. } else {
  5228. APValue &Value = createTemporary(SubExpr, false, Result,
  5229. *Info.CurrentCall);
  5230. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5231. return false;
  5232. }
  5233. // The result is a pointer to the first element of the array.
  5234. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5235. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5236. Result.addArray(Info, E, CAT);
  5237. else
  5238. Result.addUnsizedArray(Info, E, AT->getElementType());
  5239. return true;
  5240. }
  5241. case CK_FunctionToPointerDecay:
  5242. return evaluateLValue(SubExpr, Result);
  5243. case CK_LValueToRValue: {
  5244. LValue LVal;
  5245. if (!evaluateLValue(E->getSubExpr(), LVal))
  5246. return false;
  5247. APValue RVal;
  5248. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5249. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5250. LVal, RVal))
  5251. return InvalidBaseOK &&
  5252. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5253. return Success(RVal, E);
  5254. }
  5255. }
  5256. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5257. }
  5258. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  5259. UnaryExprOrTypeTrait ExprKind) {
  5260. // C++ [expr.alignof]p3:
  5261. // When alignof is applied to a reference type, the result is the
  5262. // alignment of the referenced type.
  5263. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5264. T = Ref->getPointeeType();
  5265. if (T.getQualifiers().hasUnaligned())
  5266. return CharUnits::One();
  5267. const bool AlignOfReturnsPreferred =
  5268. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  5269. // __alignof is defined to return the preferred alignment.
  5270. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  5271. // as well.
  5272. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  5273. return Info.Ctx.toCharUnitsFromBits(
  5274. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5275. // alignof and _Alignof are defined to return the ABI alignment.
  5276. else if (ExprKind == UETT_AlignOf)
  5277. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  5278. else
  5279. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  5280. }
  5281. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  5282. UnaryExprOrTypeTrait ExprKind) {
  5283. E = E->IgnoreParens();
  5284. // The kinds of expressions that we have special-case logic here for
  5285. // should be kept up to date with the special checks for those
  5286. // expressions in Sema.
  5287. // alignof decl is always accepted, even if it doesn't make sense: we default
  5288. // to 1 in those cases.
  5289. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5290. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5291. /*RefAsPointee*/true);
  5292. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5293. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5294. /*RefAsPointee*/true);
  5295. return GetAlignOfType(Info, E->getType(), ExprKind);
  5296. }
  5297. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5298. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  5299. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  5300. return true;
  5301. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  5302. return false;
  5303. Result.setInvalid(E);
  5304. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  5305. Result.addUnsizedArray(Info, E, PointeeTy);
  5306. return true;
  5307. }
  5308. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5309. if (IsStringLiteralCall(E))
  5310. return Success(E);
  5311. if (unsigned BuiltinOp = E->getBuiltinCallee())
  5312. return VisitBuiltinCallExpr(E, BuiltinOp);
  5313. return visitNonBuiltinCallExpr(E);
  5314. }
  5315. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  5316. unsigned BuiltinOp) {
  5317. switch (BuiltinOp) {
  5318. case Builtin::BI__builtin_addressof:
  5319. return evaluateLValue(E->getArg(0), Result);
  5320. case Builtin::BI__builtin_assume_aligned: {
  5321. // We need to be very careful here because: if the pointer does not have the
  5322. // asserted alignment, then the behavior is undefined, and undefined
  5323. // behavior is non-constant.
  5324. if (!evaluatePointer(E->getArg(0), Result))
  5325. return false;
  5326. LValue OffsetResult(Result);
  5327. APSInt Alignment;
  5328. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  5329. return false;
  5330. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  5331. if (E->getNumArgs() > 2) {
  5332. APSInt Offset;
  5333. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  5334. return false;
  5335. int64_t AdditionalOffset = -Offset.getZExtValue();
  5336. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  5337. }
  5338. // If there is a base object, then it must have the correct alignment.
  5339. if (OffsetResult.Base) {
  5340. CharUnits BaseAlignment;
  5341. if (const ValueDecl *VD =
  5342. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  5343. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  5344. } else {
  5345. BaseAlignment = GetAlignOfExpr(
  5346. Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
  5347. }
  5348. if (BaseAlignment < Align) {
  5349. Result.Designator.setInvalid();
  5350. // FIXME: Add support to Diagnostic for long / long long.
  5351. CCEDiag(E->getArg(0),
  5352. diag::note_constexpr_baa_insufficient_alignment) << 0
  5353. << (unsigned)BaseAlignment.getQuantity()
  5354. << (unsigned)Align.getQuantity();
  5355. return false;
  5356. }
  5357. }
  5358. // The offset must also have the correct alignment.
  5359. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  5360. Result.Designator.setInvalid();
  5361. (OffsetResult.Base
  5362. ? CCEDiag(E->getArg(0),
  5363. diag::note_constexpr_baa_insufficient_alignment) << 1
  5364. : CCEDiag(E->getArg(0),
  5365. diag::note_constexpr_baa_value_insufficient_alignment))
  5366. << (int)OffsetResult.Offset.getQuantity()
  5367. << (unsigned)Align.getQuantity();
  5368. return false;
  5369. }
  5370. return true;
  5371. }
  5372. case Builtin::BIstrchr:
  5373. case Builtin::BIwcschr:
  5374. case Builtin::BImemchr:
  5375. case Builtin::BIwmemchr:
  5376. if (Info.getLangOpts().CPlusPlus11)
  5377. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5378. << /*isConstexpr*/0 << /*isConstructor*/0
  5379. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5380. else
  5381. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5382. LLVM_FALLTHROUGH;
  5383. case Builtin::BI__builtin_strchr:
  5384. case Builtin::BI__builtin_wcschr:
  5385. case Builtin::BI__builtin_memchr:
  5386. case Builtin::BI__builtin_char_memchr:
  5387. case Builtin::BI__builtin_wmemchr: {
  5388. if (!Visit(E->getArg(0)))
  5389. return false;
  5390. APSInt Desired;
  5391. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  5392. return false;
  5393. uint64_t MaxLength = uint64_t(-1);
  5394. if (BuiltinOp != Builtin::BIstrchr &&
  5395. BuiltinOp != Builtin::BIwcschr &&
  5396. BuiltinOp != Builtin::BI__builtin_strchr &&
  5397. BuiltinOp != Builtin::BI__builtin_wcschr) {
  5398. APSInt N;
  5399. if (!EvaluateInteger(E->getArg(2), N, Info))
  5400. return false;
  5401. MaxLength = N.getExtValue();
  5402. }
  5403. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5404. // Figure out what value we're actually looking for (after converting to
  5405. // the corresponding unsigned type if necessary).
  5406. uint64_t DesiredVal;
  5407. bool StopAtNull = false;
  5408. switch (BuiltinOp) {
  5409. case Builtin::BIstrchr:
  5410. case Builtin::BI__builtin_strchr:
  5411. // strchr compares directly to the passed integer, and therefore
  5412. // always fails if given an int that is not a char.
  5413. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  5414. E->getArg(1)->getType(),
  5415. Desired),
  5416. Desired))
  5417. return ZeroInitialization(E);
  5418. StopAtNull = true;
  5419. LLVM_FALLTHROUGH;
  5420. case Builtin::BImemchr:
  5421. case Builtin::BI__builtin_memchr:
  5422. case Builtin::BI__builtin_char_memchr:
  5423. // memchr compares by converting both sides to unsigned char. That's also
  5424. // correct for strchr if we get this far (to cope with plain char being
  5425. // unsigned in the strchr case).
  5426. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  5427. break;
  5428. case Builtin::BIwcschr:
  5429. case Builtin::BI__builtin_wcschr:
  5430. StopAtNull = true;
  5431. LLVM_FALLTHROUGH;
  5432. case Builtin::BIwmemchr:
  5433. case Builtin::BI__builtin_wmemchr:
  5434. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  5435. DesiredVal = Desired.getZExtValue();
  5436. break;
  5437. }
  5438. for (; MaxLength; --MaxLength) {
  5439. APValue Char;
  5440. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  5441. !Char.isInt())
  5442. return false;
  5443. if (Char.getInt().getZExtValue() == DesiredVal)
  5444. return true;
  5445. if (StopAtNull && !Char.getInt())
  5446. break;
  5447. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  5448. return false;
  5449. }
  5450. // Not found: return nullptr.
  5451. return ZeroInitialization(E);
  5452. }
  5453. case Builtin::BImemcpy:
  5454. case Builtin::BImemmove:
  5455. case Builtin::BIwmemcpy:
  5456. case Builtin::BIwmemmove:
  5457. if (Info.getLangOpts().CPlusPlus11)
  5458. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5459. << /*isConstexpr*/0 << /*isConstructor*/0
  5460. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5461. else
  5462. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5463. LLVM_FALLTHROUGH;
  5464. case Builtin::BI__builtin_memcpy:
  5465. case Builtin::BI__builtin_memmove:
  5466. case Builtin::BI__builtin_wmemcpy:
  5467. case Builtin::BI__builtin_wmemmove: {
  5468. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  5469. BuiltinOp == Builtin::BIwmemmove ||
  5470. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  5471. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5472. bool Move = BuiltinOp == Builtin::BImemmove ||
  5473. BuiltinOp == Builtin::BIwmemmove ||
  5474. BuiltinOp == Builtin::BI__builtin_memmove ||
  5475. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5476. // The result of mem* is the first argument.
  5477. if (!Visit(E->getArg(0)))
  5478. return false;
  5479. LValue Dest = Result;
  5480. LValue Src;
  5481. if (!EvaluatePointer(E->getArg(1), Src, Info))
  5482. return false;
  5483. APSInt N;
  5484. if (!EvaluateInteger(E->getArg(2), N, Info))
  5485. return false;
  5486. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  5487. // If the size is zero, we treat this as always being a valid no-op.
  5488. // (Even if one of the src and dest pointers is null.)
  5489. if (!N)
  5490. return true;
  5491. // Otherwise, if either of the operands is null, we can't proceed. Don't
  5492. // try to determine the type of the copied objects, because there aren't
  5493. // any.
  5494. if (!Src.Base || !Dest.Base) {
  5495. APValue Val;
  5496. (!Src.Base ? Src : Dest).moveInto(Val);
  5497. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  5498. << Move << WChar << !!Src.Base
  5499. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  5500. return false;
  5501. }
  5502. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  5503. return false;
  5504. // We require that Src and Dest are both pointers to arrays of
  5505. // trivially-copyable type. (For the wide version, the designator will be
  5506. // invalid if the designated object is not a wchar_t.)
  5507. QualType T = Dest.Designator.getType(Info.Ctx);
  5508. QualType SrcT = Src.Designator.getType(Info.Ctx);
  5509. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  5510. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  5511. return false;
  5512. }
  5513. if (T->isIncompleteType()) {
  5514. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  5515. return false;
  5516. }
  5517. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  5518. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  5519. return false;
  5520. }
  5521. // Figure out how many T's we're copying.
  5522. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  5523. if (!WChar) {
  5524. uint64_t Remainder;
  5525. llvm::APInt OrigN = N;
  5526. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  5527. if (Remainder) {
  5528. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5529. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  5530. << (unsigned)TSize;
  5531. return false;
  5532. }
  5533. }
  5534. // Check that the copying will remain within the arrays, just so that we
  5535. // can give a more meaningful diagnostic. This implicitly also checks that
  5536. // N fits into 64 bits.
  5537. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  5538. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  5539. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  5540. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5541. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  5542. << N.toString(10, /*Signed*/false);
  5543. return false;
  5544. }
  5545. uint64_t NElems = N.getZExtValue();
  5546. uint64_t NBytes = NElems * TSize;
  5547. // Check for overlap.
  5548. int Direction = 1;
  5549. if (HasSameBase(Src, Dest)) {
  5550. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  5551. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  5552. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  5553. // Dest is inside the source region.
  5554. if (!Move) {
  5555. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5556. return false;
  5557. }
  5558. // For memmove and friends, copy backwards.
  5559. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  5560. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  5561. return false;
  5562. Direction = -1;
  5563. } else if (!Move && SrcOffset >= DestOffset &&
  5564. SrcOffset - DestOffset < NBytes) {
  5565. // Src is inside the destination region for memcpy: invalid.
  5566. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5567. return false;
  5568. }
  5569. }
  5570. while (true) {
  5571. APValue Val;
  5572. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  5573. !handleAssignment(Info, E, Dest, T, Val))
  5574. return false;
  5575. // Do not iterate past the last element; if we're copying backwards, that
  5576. // might take us off the start of the array.
  5577. if (--NElems == 0)
  5578. return true;
  5579. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  5580. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  5581. return false;
  5582. }
  5583. }
  5584. default:
  5585. return visitNonBuiltinCallExpr(E);
  5586. }
  5587. }
  5588. //===----------------------------------------------------------------------===//
  5589. // Member Pointer Evaluation
  5590. //===----------------------------------------------------------------------===//
  5591. namespace {
  5592. class MemberPointerExprEvaluator
  5593. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  5594. MemberPtr &Result;
  5595. bool Success(const ValueDecl *D) {
  5596. Result = MemberPtr(D);
  5597. return true;
  5598. }
  5599. public:
  5600. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  5601. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  5602. bool Success(const APValue &V, const Expr *E) {
  5603. Result.setFrom(V);
  5604. return true;
  5605. }
  5606. bool ZeroInitialization(const Expr *E) {
  5607. return Success((const ValueDecl*)nullptr);
  5608. }
  5609. bool VisitCastExpr(const CastExpr *E);
  5610. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5611. };
  5612. } // end anonymous namespace
  5613. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  5614. EvalInfo &Info) {
  5615. assert(E->isRValue() && E->getType()->isMemberPointerType());
  5616. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  5617. }
  5618. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5619. switch (E->getCastKind()) {
  5620. default:
  5621. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5622. case CK_NullToMemberPointer:
  5623. VisitIgnoredValue(E->getSubExpr());
  5624. return ZeroInitialization(E);
  5625. case CK_BaseToDerivedMemberPointer: {
  5626. if (!Visit(E->getSubExpr()))
  5627. return false;
  5628. if (E->path_empty())
  5629. return true;
  5630. // Base-to-derived member pointer casts store the path in derived-to-base
  5631. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  5632. // the wrong end of the derived->base arc, so stagger the path by one class.
  5633. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  5634. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  5635. PathI != PathE; ++PathI) {
  5636. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5637. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  5638. if (!Result.castToDerived(Derived))
  5639. return Error(E);
  5640. }
  5641. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  5642. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  5643. return Error(E);
  5644. return true;
  5645. }
  5646. case CK_DerivedToBaseMemberPointer:
  5647. if (!Visit(E->getSubExpr()))
  5648. return false;
  5649. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5650. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5651. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5652. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5653. if (!Result.castToBase(Base))
  5654. return Error(E);
  5655. }
  5656. return true;
  5657. }
  5658. }
  5659. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5660. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  5661. // member can be formed.
  5662. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  5663. }
  5664. //===----------------------------------------------------------------------===//
  5665. // Record Evaluation
  5666. //===----------------------------------------------------------------------===//
  5667. namespace {
  5668. class RecordExprEvaluator
  5669. : public ExprEvaluatorBase<RecordExprEvaluator> {
  5670. const LValue &This;
  5671. APValue &Result;
  5672. public:
  5673. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  5674. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  5675. bool Success(const APValue &V, const Expr *E) {
  5676. Result = V;
  5677. return true;
  5678. }
  5679. bool ZeroInitialization(const Expr *E) {
  5680. return ZeroInitialization(E, E->getType());
  5681. }
  5682. bool ZeroInitialization(const Expr *E, QualType T);
  5683. bool VisitCallExpr(const CallExpr *E) {
  5684. return handleCallExpr(E, Result, &This);
  5685. }
  5686. bool VisitCastExpr(const CastExpr *E);
  5687. bool VisitInitListExpr(const InitListExpr *E);
  5688. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5689. return VisitCXXConstructExpr(E, E->getType());
  5690. }
  5691. bool VisitLambdaExpr(const LambdaExpr *E);
  5692. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  5693. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  5694. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  5695. bool VisitBinCmp(const BinaryOperator *E);
  5696. };
  5697. }
  5698. /// Perform zero-initialization on an object of non-union class type.
  5699. /// C++11 [dcl.init]p5:
  5700. /// To zero-initialize an object or reference of type T means:
  5701. /// [...]
  5702. /// -- if T is a (possibly cv-qualified) non-union class type,
  5703. /// each non-static data member and each base-class subobject is
  5704. /// zero-initialized
  5705. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  5706. const RecordDecl *RD,
  5707. const LValue &This, APValue &Result) {
  5708. assert(!RD->isUnion() && "Expected non-union class type");
  5709. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  5710. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  5711. std::distance(RD->field_begin(), RD->field_end()));
  5712. if (RD->isInvalidDecl()) return false;
  5713. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5714. if (CD) {
  5715. unsigned Index = 0;
  5716. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  5717. End = CD->bases_end(); I != End; ++I, ++Index) {
  5718. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  5719. LValue Subobject = This;
  5720. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  5721. return false;
  5722. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  5723. Result.getStructBase(Index)))
  5724. return false;
  5725. }
  5726. }
  5727. for (const auto *I : RD->fields()) {
  5728. // -- if T is a reference type, no initialization is performed.
  5729. if (I->getType()->isReferenceType())
  5730. continue;
  5731. LValue Subobject = This;
  5732. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  5733. return false;
  5734. ImplicitValueInitExpr VIE(I->getType());
  5735. if (!EvaluateInPlace(
  5736. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  5737. return false;
  5738. }
  5739. return true;
  5740. }
  5741. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  5742. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  5743. if (RD->isInvalidDecl()) return false;
  5744. if (RD->isUnion()) {
  5745. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  5746. // object's first non-static named data member is zero-initialized
  5747. RecordDecl::field_iterator I = RD->field_begin();
  5748. if (I == RD->field_end()) {
  5749. Result = APValue((const FieldDecl*)nullptr);
  5750. return true;
  5751. }
  5752. LValue Subobject = This;
  5753. if (!HandleLValueMember(Info, E, Subobject, *I))
  5754. return false;
  5755. Result = APValue(*I);
  5756. ImplicitValueInitExpr VIE(I->getType());
  5757. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  5758. }
  5759. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  5760. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  5761. return false;
  5762. }
  5763. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  5764. }
  5765. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5766. switch (E->getCastKind()) {
  5767. default:
  5768. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5769. case CK_ConstructorConversion:
  5770. return Visit(E->getSubExpr());
  5771. case CK_DerivedToBase:
  5772. case CK_UncheckedDerivedToBase: {
  5773. APValue DerivedObject;
  5774. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  5775. return false;
  5776. if (!DerivedObject.isStruct())
  5777. return Error(E->getSubExpr());
  5778. // Derived-to-base rvalue conversion: just slice off the derived part.
  5779. APValue *Value = &DerivedObject;
  5780. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  5781. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5782. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5783. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  5784. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5785. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  5786. RD = Base;
  5787. }
  5788. Result = *Value;
  5789. return true;
  5790. }
  5791. }
  5792. }
  5793. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5794. if (E->isTransparent())
  5795. return Visit(E->getInit(0));
  5796. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  5797. if (RD->isInvalidDecl()) return false;
  5798. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5799. if (RD->isUnion()) {
  5800. const FieldDecl *Field = E->getInitializedFieldInUnion();
  5801. Result = APValue(Field);
  5802. if (!Field)
  5803. return true;
  5804. // If the initializer list for a union does not contain any elements, the
  5805. // first element of the union is value-initialized.
  5806. // FIXME: The element should be initialized from an initializer list.
  5807. // Is this difference ever observable for initializer lists which
  5808. // we don't build?
  5809. ImplicitValueInitExpr VIE(Field->getType());
  5810. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  5811. LValue Subobject = This;
  5812. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  5813. return false;
  5814. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5815. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5816. isa<CXXDefaultInitExpr>(InitExpr));
  5817. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  5818. }
  5819. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  5820. if (Result.isUninit())
  5821. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  5822. std::distance(RD->field_begin(), RD->field_end()));
  5823. unsigned ElementNo = 0;
  5824. bool Success = true;
  5825. // Initialize base classes.
  5826. if (CXXRD) {
  5827. for (const auto &Base : CXXRD->bases()) {
  5828. assert(ElementNo < E->getNumInits() && "missing init for base class");
  5829. const Expr *Init = E->getInit(ElementNo);
  5830. LValue Subobject = This;
  5831. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  5832. return false;
  5833. APValue &FieldVal = Result.getStructBase(ElementNo);
  5834. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  5835. if (!Info.noteFailure())
  5836. return false;
  5837. Success = false;
  5838. }
  5839. ++ElementNo;
  5840. }
  5841. }
  5842. // Initialize members.
  5843. for (const auto *Field : RD->fields()) {
  5844. // Anonymous bit-fields are not considered members of the class for
  5845. // purposes of aggregate initialization.
  5846. if (Field->isUnnamedBitfield())
  5847. continue;
  5848. LValue Subobject = This;
  5849. bool HaveInit = ElementNo < E->getNumInits();
  5850. // FIXME: Diagnostics here should point to the end of the initializer
  5851. // list, not the start.
  5852. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  5853. Subobject, Field, &Layout))
  5854. return false;
  5855. // Perform an implicit value-initialization for members beyond the end of
  5856. // the initializer list.
  5857. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  5858. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  5859. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5860. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5861. isa<CXXDefaultInitExpr>(Init));
  5862. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5863. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  5864. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  5865. FieldVal, Field))) {
  5866. if (!Info.noteFailure())
  5867. return false;
  5868. Success = false;
  5869. }
  5870. }
  5871. return Success;
  5872. }
  5873. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5874. QualType T) {
  5875. // Note that E's type is not necessarily the type of our class here; we might
  5876. // be initializing an array element instead.
  5877. const CXXConstructorDecl *FD = E->getConstructor();
  5878. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  5879. bool ZeroInit = E->requiresZeroInitialization();
  5880. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5881. // If we've already performed zero-initialization, we're already done.
  5882. if (!Result.isUninit())
  5883. return true;
  5884. // We can get here in two different ways:
  5885. // 1) We're performing value-initialization, and should zero-initialize
  5886. // the object, or
  5887. // 2) We're performing default-initialization of an object with a trivial
  5888. // constexpr default constructor, in which case we should start the
  5889. // lifetimes of all the base subobjects (there can be no data member
  5890. // subobjects in this case) per [basic.life]p1.
  5891. // Either way, ZeroInitialization is appropriate.
  5892. return ZeroInitialization(E, T);
  5893. }
  5894. const FunctionDecl *Definition = nullptr;
  5895. auto Body = FD->getBody(Definition);
  5896. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5897. return false;
  5898. // Avoid materializing a temporary for an elidable copy/move constructor.
  5899. if (E->isElidable() && !ZeroInit)
  5900. if (const MaterializeTemporaryExpr *ME
  5901. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  5902. return Visit(ME->GetTemporaryExpr());
  5903. if (ZeroInit && !ZeroInitialization(E, T))
  5904. return false;
  5905. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5906. return HandleConstructorCall(E, This, Args,
  5907. cast<CXXConstructorDecl>(Definition), Info,
  5908. Result);
  5909. }
  5910. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  5911. const CXXInheritedCtorInitExpr *E) {
  5912. if (!Info.CurrentCall) {
  5913. assert(Info.checkingPotentialConstantExpression());
  5914. return false;
  5915. }
  5916. const CXXConstructorDecl *FD = E->getConstructor();
  5917. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  5918. return false;
  5919. const FunctionDecl *Definition = nullptr;
  5920. auto Body = FD->getBody(Definition);
  5921. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5922. return false;
  5923. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  5924. cast<CXXConstructorDecl>(Definition), Info,
  5925. Result);
  5926. }
  5927. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  5928. const CXXStdInitializerListExpr *E) {
  5929. const ConstantArrayType *ArrayType =
  5930. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  5931. LValue Array;
  5932. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  5933. return false;
  5934. // Get a pointer to the first element of the array.
  5935. Array.addArray(Info, E, ArrayType);
  5936. // FIXME: Perform the checks on the field types in SemaInit.
  5937. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  5938. RecordDecl::field_iterator Field = Record->field_begin();
  5939. if (Field == Record->field_end())
  5940. return Error(E);
  5941. // Start pointer.
  5942. if (!Field->getType()->isPointerType() ||
  5943. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5944. ArrayType->getElementType()))
  5945. return Error(E);
  5946. // FIXME: What if the initializer_list type has base classes, etc?
  5947. Result = APValue(APValue::UninitStruct(), 0, 2);
  5948. Array.moveInto(Result.getStructField(0));
  5949. if (++Field == Record->field_end())
  5950. return Error(E);
  5951. if (Field->getType()->isPointerType() &&
  5952. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5953. ArrayType->getElementType())) {
  5954. // End pointer.
  5955. if (!HandleLValueArrayAdjustment(Info, E, Array,
  5956. ArrayType->getElementType(),
  5957. ArrayType->getSize().getZExtValue()))
  5958. return false;
  5959. Array.moveInto(Result.getStructField(1));
  5960. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  5961. // Length.
  5962. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  5963. else
  5964. return Error(E);
  5965. if (++Field != Record->field_end())
  5966. return Error(E);
  5967. return true;
  5968. }
  5969. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  5970. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  5971. if (ClosureClass->isInvalidDecl()) return false;
  5972. if (Info.checkingPotentialConstantExpression()) return true;
  5973. const size_t NumFields =
  5974. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  5975. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  5976. E->capture_init_end()) &&
  5977. "The number of lambda capture initializers should equal the number of "
  5978. "fields within the closure type");
  5979. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  5980. // Iterate through all the lambda's closure object's fields and initialize
  5981. // them.
  5982. auto *CaptureInitIt = E->capture_init_begin();
  5983. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  5984. bool Success = true;
  5985. for (const auto *Field : ClosureClass->fields()) {
  5986. assert(CaptureInitIt != E->capture_init_end());
  5987. // Get the initializer for this field
  5988. Expr *const CurFieldInit = *CaptureInitIt++;
  5989. // If there is no initializer, either this is a VLA or an error has
  5990. // occurred.
  5991. if (!CurFieldInit)
  5992. return Error(E);
  5993. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5994. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  5995. if (!Info.keepEvaluatingAfterFailure())
  5996. return false;
  5997. Success = false;
  5998. }
  5999. ++CaptureIt;
  6000. }
  6001. return Success;
  6002. }
  6003. static bool EvaluateRecord(const Expr *E, const LValue &This,
  6004. APValue &Result, EvalInfo &Info) {
  6005. assert(E->isRValue() && E->getType()->isRecordType() &&
  6006. "can't evaluate expression as a record rvalue");
  6007. return RecordExprEvaluator(Info, This, Result).Visit(E);
  6008. }
  6009. //===----------------------------------------------------------------------===//
  6010. // Temporary Evaluation
  6011. //
  6012. // Temporaries are represented in the AST as rvalues, but generally behave like
  6013. // lvalues. The full-object of which the temporary is a subobject is implicitly
  6014. // materialized so that a reference can bind to it.
  6015. //===----------------------------------------------------------------------===//
  6016. namespace {
  6017. class TemporaryExprEvaluator
  6018. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  6019. public:
  6020. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  6021. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  6022. /// Visit an expression which constructs the value of this temporary.
  6023. bool VisitConstructExpr(const Expr *E) {
  6024. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  6025. return EvaluateInPlace(Value, Info, Result, E);
  6026. }
  6027. bool VisitCastExpr(const CastExpr *E) {
  6028. switch (E->getCastKind()) {
  6029. default:
  6030. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6031. case CK_ConstructorConversion:
  6032. return VisitConstructExpr(E->getSubExpr());
  6033. }
  6034. }
  6035. bool VisitInitListExpr(const InitListExpr *E) {
  6036. return VisitConstructExpr(E);
  6037. }
  6038. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6039. return VisitConstructExpr(E);
  6040. }
  6041. bool VisitCallExpr(const CallExpr *E) {
  6042. return VisitConstructExpr(E);
  6043. }
  6044. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  6045. return VisitConstructExpr(E);
  6046. }
  6047. bool VisitLambdaExpr(const LambdaExpr *E) {
  6048. return VisitConstructExpr(E);
  6049. }
  6050. };
  6051. } // end anonymous namespace
  6052. /// Evaluate an expression of record type as a temporary.
  6053. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  6054. assert(E->isRValue() && E->getType()->isRecordType());
  6055. return TemporaryExprEvaluator(Info, Result).Visit(E);
  6056. }
  6057. //===----------------------------------------------------------------------===//
  6058. // Vector Evaluation
  6059. //===----------------------------------------------------------------------===//
  6060. namespace {
  6061. class VectorExprEvaluator
  6062. : public ExprEvaluatorBase<VectorExprEvaluator> {
  6063. APValue &Result;
  6064. public:
  6065. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  6066. : ExprEvaluatorBaseTy(info), Result(Result) {}
  6067. bool Success(ArrayRef<APValue> V, const Expr *E) {
  6068. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  6069. // FIXME: remove this APValue copy.
  6070. Result = APValue(V.data(), V.size());
  6071. return true;
  6072. }
  6073. bool Success(const APValue &V, const Expr *E) {
  6074. assert(V.isVector());
  6075. Result = V;
  6076. return true;
  6077. }
  6078. bool ZeroInitialization(const Expr *E);
  6079. bool VisitUnaryReal(const UnaryOperator *E)
  6080. { return Visit(E->getSubExpr()); }
  6081. bool VisitCastExpr(const CastExpr* E);
  6082. bool VisitInitListExpr(const InitListExpr *E);
  6083. bool VisitUnaryImag(const UnaryOperator *E);
  6084. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  6085. // binary comparisons, binary and/or/xor,
  6086. // shufflevector, ExtVectorElementExpr
  6087. };
  6088. } // end anonymous namespace
  6089. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  6090. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  6091. return VectorExprEvaluator(Info, Result).Visit(E);
  6092. }
  6093. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6094. const VectorType *VTy = E->getType()->castAs<VectorType>();
  6095. unsigned NElts = VTy->getNumElements();
  6096. const Expr *SE = E->getSubExpr();
  6097. QualType SETy = SE->getType();
  6098. switch (E->getCastKind()) {
  6099. case CK_VectorSplat: {
  6100. APValue Val = APValue();
  6101. if (SETy->isIntegerType()) {
  6102. APSInt IntResult;
  6103. if (!EvaluateInteger(SE, IntResult, Info))
  6104. return false;
  6105. Val = APValue(std::move(IntResult));
  6106. } else if (SETy->isRealFloatingType()) {
  6107. APFloat FloatResult(0.0);
  6108. if (!EvaluateFloat(SE, FloatResult, Info))
  6109. return false;
  6110. Val = APValue(std::move(FloatResult));
  6111. } else {
  6112. return Error(E);
  6113. }
  6114. // Splat and create vector APValue.
  6115. SmallVector<APValue, 4> Elts(NElts, Val);
  6116. return Success(Elts, E);
  6117. }
  6118. case CK_BitCast: {
  6119. // Evaluate the operand into an APInt we can extract from.
  6120. llvm::APInt SValInt;
  6121. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  6122. return false;
  6123. // Extract the elements
  6124. QualType EltTy = VTy->getElementType();
  6125. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  6126. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  6127. SmallVector<APValue, 4> Elts;
  6128. if (EltTy->isRealFloatingType()) {
  6129. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  6130. unsigned FloatEltSize = EltSize;
  6131. if (&Sem == &APFloat::x87DoubleExtended())
  6132. FloatEltSize = 80;
  6133. for (unsigned i = 0; i < NElts; i++) {
  6134. llvm::APInt Elt;
  6135. if (BigEndian)
  6136. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  6137. else
  6138. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  6139. Elts.push_back(APValue(APFloat(Sem, Elt)));
  6140. }
  6141. } else if (EltTy->isIntegerType()) {
  6142. for (unsigned i = 0; i < NElts; i++) {
  6143. llvm::APInt Elt;
  6144. if (BigEndian)
  6145. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  6146. else
  6147. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  6148. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  6149. }
  6150. } else {
  6151. return Error(E);
  6152. }
  6153. return Success(Elts, E);
  6154. }
  6155. default:
  6156. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6157. }
  6158. }
  6159. bool
  6160. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6161. const VectorType *VT = E->getType()->castAs<VectorType>();
  6162. unsigned NumInits = E->getNumInits();
  6163. unsigned NumElements = VT->getNumElements();
  6164. QualType EltTy = VT->getElementType();
  6165. SmallVector<APValue, 4> Elements;
  6166. // The number of initializers can be less than the number of
  6167. // vector elements. For OpenCL, this can be due to nested vector
  6168. // initialization. For GCC compatibility, missing trailing elements
  6169. // should be initialized with zeroes.
  6170. unsigned CountInits = 0, CountElts = 0;
  6171. while (CountElts < NumElements) {
  6172. // Handle nested vector initialization.
  6173. if (CountInits < NumInits
  6174. && E->getInit(CountInits)->getType()->isVectorType()) {
  6175. APValue v;
  6176. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  6177. return Error(E);
  6178. unsigned vlen = v.getVectorLength();
  6179. for (unsigned j = 0; j < vlen; j++)
  6180. Elements.push_back(v.getVectorElt(j));
  6181. CountElts += vlen;
  6182. } else if (EltTy->isIntegerType()) {
  6183. llvm::APSInt sInt(32);
  6184. if (CountInits < NumInits) {
  6185. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6186. return false;
  6187. } else // trailing integer zero.
  6188. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6189. Elements.push_back(APValue(sInt));
  6190. CountElts++;
  6191. } else {
  6192. llvm::APFloat f(0.0);
  6193. if (CountInits < NumInits) {
  6194. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6195. return false;
  6196. } else // trailing float zero.
  6197. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6198. Elements.push_back(APValue(f));
  6199. CountElts++;
  6200. }
  6201. CountInits++;
  6202. }
  6203. return Success(Elements, E);
  6204. }
  6205. bool
  6206. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6207. const VectorType *VT = E->getType()->getAs<VectorType>();
  6208. QualType EltTy = VT->getElementType();
  6209. APValue ZeroElement;
  6210. if (EltTy->isIntegerType())
  6211. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6212. else
  6213. ZeroElement =
  6214. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6215. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6216. return Success(Elements, E);
  6217. }
  6218. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6219. VisitIgnoredValue(E->getSubExpr());
  6220. return ZeroInitialization(E);
  6221. }
  6222. //===----------------------------------------------------------------------===//
  6223. // Array Evaluation
  6224. //===----------------------------------------------------------------------===//
  6225. namespace {
  6226. class ArrayExprEvaluator
  6227. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6228. const LValue &This;
  6229. APValue &Result;
  6230. public:
  6231. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6232. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6233. bool Success(const APValue &V, const Expr *E) {
  6234. assert((V.isArray() || V.isLValue()) &&
  6235. "expected array or string literal");
  6236. Result = V;
  6237. return true;
  6238. }
  6239. bool ZeroInitialization(const Expr *E) {
  6240. const ConstantArrayType *CAT =
  6241. Info.Ctx.getAsConstantArrayType(E->getType());
  6242. if (!CAT)
  6243. return Error(E);
  6244. Result = APValue(APValue::UninitArray(), 0,
  6245. CAT->getSize().getZExtValue());
  6246. if (!Result.hasArrayFiller()) return true;
  6247. // Zero-initialize all elements.
  6248. LValue Subobject = This;
  6249. Subobject.addArray(Info, E, CAT);
  6250. ImplicitValueInitExpr VIE(CAT->getElementType());
  6251. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6252. }
  6253. bool VisitCallExpr(const CallExpr *E) {
  6254. return handleCallExpr(E, Result, &This);
  6255. }
  6256. bool VisitInitListExpr(const InitListExpr *E);
  6257. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6258. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6259. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6260. const LValue &Subobject,
  6261. APValue *Value, QualType Type);
  6262. };
  6263. } // end anonymous namespace
  6264. static bool EvaluateArray(const Expr *E, const LValue &This,
  6265. APValue &Result, EvalInfo &Info) {
  6266. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  6267. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  6268. }
  6269. // Return true iff the given array filler may depend on the element index.
  6270. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  6271. // For now, just whitelist non-class value-initialization and initialization
  6272. // lists comprised of them.
  6273. if (isa<ImplicitValueInitExpr>(FillerExpr))
  6274. return false;
  6275. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  6276. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  6277. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  6278. return true;
  6279. }
  6280. return false;
  6281. }
  6282. return true;
  6283. }
  6284. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6285. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  6286. if (!CAT)
  6287. return Error(E);
  6288. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  6289. // an appropriately-typed string literal enclosed in braces.
  6290. if (E->isStringLiteralInit()) {
  6291. LValue LV;
  6292. if (!EvaluateLValue(E->getInit(0), LV, Info))
  6293. return false;
  6294. APValue Val;
  6295. LV.moveInto(Val);
  6296. return Success(Val, E);
  6297. }
  6298. bool Success = true;
  6299. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  6300. "zero-initialized array shouldn't have any initialized elts");
  6301. APValue Filler;
  6302. if (Result.isArray() && Result.hasArrayFiller())
  6303. Filler = Result.getArrayFiller();
  6304. unsigned NumEltsToInit = E->getNumInits();
  6305. unsigned NumElts = CAT->getSize().getZExtValue();
  6306. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  6307. // If the initializer might depend on the array index, run it for each
  6308. // array element.
  6309. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  6310. NumEltsToInit = NumElts;
  6311. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  6312. << NumEltsToInit << ".\n");
  6313. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  6314. // If the array was previously zero-initialized, preserve the
  6315. // zero-initialized values.
  6316. if (!Filler.isUninit()) {
  6317. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  6318. Result.getArrayInitializedElt(I) = Filler;
  6319. if (Result.hasArrayFiller())
  6320. Result.getArrayFiller() = Filler;
  6321. }
  6322. LValue Subobject = This;
  6323. Subobject.addArray(Info, E, CAT);
  6324. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  6325. const Expr *Init =
  6326. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  6327. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6328. Info, Subobject, Init) ||
  6329. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  6330. CAT->getElementType(), 1)) {
  6331. if (!Info.noteFailure())
  6332. return false;
  6333. Success = false;
  6334. }
  6335. }
  6336. if (!Result.hasArrayFiller())
  6337. return Success;
  6338. // If we get here, we have a trivial filler, which we can just evaluate
  6339. // once and splat over the rest of the array elements.
  6340. assert(FillerExpr && "no array filler for incomplete init list");
  6341. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  6342. FillerExpr) && Success;
  6343. }
  6344. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  6345. if (E->getCommonExpr() &&
  6346. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  6347. Info, E->getCommonExpr()->getSourceExpr()))
  6348. return false;
  6349. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  6350. uint64_t Elements = CAT->getSize().getZExtValue();
  6351. Result = APValue(APValue::UninitArray(), Elements, Elements);
  6352. LValue Subobject = This;
  6353. Subobject.addArray(Info, E, CAT);
  6354. bool Success = true;
  6355. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  6356. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6357. Info, Subobject, E->getSubExpr()) ||
  6358. !HandleLValueArrayAdjustment(Info, E, Subobject,
  6359. CAT->getElementType(), 1)) {
  6360. if (!Info.noteFailure())
  6361. return false;
  6362. Success = false;
  6363. }
  6364. }
  6365. return Success;
  6366. }
  6367. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6368. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  6369. }
  6370. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6371. const LValue &Subobject,
  6372. APValue *Value,
  6373. QualType Type) {
  6374. bool HadZeroInit = !Value->isUninit();
  6375. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  6376. unsigned N = CAT->getSize().getZExtValue();
  6377. // Preserve the array filler if we had prior zero-initialization.
  6378. APValue Filler =
  6379. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  6380. : APValue();
  6381. *Value = APValue(APValue::UninitArray(), N, N);
  6382. if (HadZeroInit)
  6383. for (unsigned I = 0; I != N; ++I)
  6384. Value->getArrayInitializedElt(I) = Filler;
  6385. // Initialize the elements.
  6386. LValue ArrayElt = Subobject;
  6387. ArrayElt.addArray(Info, E, CAT);
  6388. for (unsigned I = 0; I != N; ++I)
  6389. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  6390. CAT->getElementType()) ||
  6391. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  6392. CAT->getElementType(), 1))
  6393. return false;
  6394. return true;
  6395. }
  6396. if (!Type->isRecordType())
  6397. return Error(E);
  6398. return RecordExprEvaluator(Info, Subobject, *Value)
  6399. .VisitCXXConstructExpr(E, Type);
  6400. }
  6401. //===----------------------------------------------------------------------===//
  6402. // Integer Evaluation
  6403. //
  6404. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  6405. // types and back in constant folding. Integer values are thus represented
  6406. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  6407. //===----------------------------------------------------------------------===//
  6408. namespace {
  6409. class IntExprEvaluator
  6410. : public ExprEvaluatorBase<IntExprEvaluator> {
  6411. APValue &Result;
  6412. public:
  6413. IntExprEvaluator(EvalInfo &info, APValue &result)
  6414. : ExprEvaluatorBaseTy(info), Result(result) {}
  6415. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6416. assert(E->getType()->isIntegralOrEnumerationType() &&
  6417. "Invalid evaluation result.");
  6418. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  6419. "Invalid evaluation result.");
  6420. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6421. "Invalid evaluation result.");
  6422. Result = APValue(SI);
  6423. return true;
  6424. }
  6425. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6426. return Success(SI, E, Result);
  6427. }
  6428. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6429. assert(E->getType()->isIntegralOrEnumerationType() &&
  6430. "Invalid evaluation result.");
  6431. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6432. "Invalid evaluation result.");
  6433. Result = APValue(APSInt(I));
  6434. Result.getInt().setIsUnsigned(
  6435. E->getType()->isUnsignedIntegerOrEnumerationType());
  6436. return true;
  6437. }
  6438. bool Success(const llvm::APInt &I, const Expr *E) {
  6439. return Success(I, E, Result);
  6440. }
  6441. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6442. assert(E->getType()->isIntegralOrEnumerationType() &&
  6443. "Invalid evaluation result.");
  6444. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6445. return true;
  6446. }
  6447. bool Success(uint64_t Value, const Expr *E) {
  6448. return Success(Value, E, Result);
  6449. }
  6450. bool Success(CharUnits Size, const Expr *E) {
  6451. return Success(Size.getQuantity(), E);
  6452. }
  6453. bool Success(const APValue &V, const Expr *E) {
  6454. if (V.isLValue() || V.isAddrLabelDiff()) {
  6455. Result = V;
  6456. return true;
  6457. }
  6458. return Success(V.getInt(), E);
  6459. }
  6460. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6461. //===--------------------------------------------------------------------===//
  6462. // Visitor Methods
  6463. //===--------------------------------------------------------------------===//
  6464. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  6465. return Success(E->getValue(), E);
  6466. }
  6467. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  6468. return Success(E->getValue(), E);
  6469. }
  6470. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  6471. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  6472. if (CheckReferencedDecl(E, E->getDecl()))
  6473. return true;
  6474. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  6475. }
  6476. bool VisitMemberExpr(const MemberExpr *E) {
  6477. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  6478. VisitIgnoredBaseExpression(E->getBase());
  6479. return true;
  6480. }
  6481. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  6482. }
  6483. bool VisitCallExpr(const CallExpr *E);
  6484. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6485. bool VisitBinaryOperator(const BinaryOperator *E);
  6486. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  6487. bool VisitUnaryOperator(const UnaryOperator *E);
  6488. bool VisitCastExpr(const CastExpr* E);
  6489. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  6490. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  6491. return Success(E->getValue(), E);
  6492. }
  6493. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  6494. return Success(E->getValue(), E);
  6495. }
  6496. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  6497. if (Info.ArrayInitIndex == uint64_t(-1)) {
  6498. // We were asked to evaluate this subexpression independent of the
  6499. // enclosing ArrayInitLoopExpr. We can't do that.
  6500. Info.FFDiag(E);
  6501. return false;
  6502. }
  6503. return Success(Info.ArrayInitIndex, E);
  6504. }
  6505. // Note, GNU defines __null as an integer, not a pointer.
  6506. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  6507. return ZeroInitialization(E);
  6508. }
  6509. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  6510. return Success(E->getValue(), E);
  6511. }
  6512. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  6513. return Success(E->getValue(), E);
  6514. }
  6515. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  6516. return Success(E->getValue(), E);
  6517. }
  6518. bool VisitUnaryReal(const UnaryOperator *E);
  6519. bool VisitUnaryImag(const UnaryOperator *E);
  6520. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  6521. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  6522. // FIXME: Missing: array subscript of vector, member of vector
  6523. };
  6524. class FixedPointExprEvaluator
  6525. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  6526. APValue &Result;
  6527. public:
  6528. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  6529. : ExprEvaluatorBaseTy(info), Result(result) {}
  6530. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6531. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6532. assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
  6533. "Invalid evaluation result.");
  6534. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6535. "Invalid evaluation result.");
  6536. Result = APValue(SI);
  6537. return true;
  6538. }
  6539. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6540. return Success(SI, E, Result);
  6541. }
  6542. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6543. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6544. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6545. "Invalid evaluation result.");
  6546. Result = APValue(APSInt(I));
  6547. Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
  6548. return true;
  6549. }
  6550. bool Success(const llvm::APInt &I, const Expr *E) {
  6551. return Success(I, E, Result);
  6552. }
  6553. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6554. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6555. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6556. return true;
  6557. }
  6558. bool Success(uint64_t Value, const Expr *E) {
  6559. return Success(Value, E, Result);
  6560. }
  6561. bool Success(CharUnits Size, const Expr *E) {
  6562. return Success(Size.getQuantity(), E);
  6563. }
  6564. bool Success(const APValue &V, const Expr *E) {
  6565. if (V.isLValue() || V.isAddrLabelDiff()) {
  6566. Result = V;
  6567. return true;
  6568. }
  6569. return Success(V.getInt(), E);
  6570. }
  6571. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6572. //===--------------------------------------------------------------------===//
  6573. // Visitor Methods
  6574. //===--------------------------------------------------------------------===//
  6575. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  6576. return Success(E->getValue(), E);
  6577. }
  6578. bool VisitUnaryOperator(const UnaryOperator *E);
  6579. };
  6580. } // end anonymous namespace
  6581. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  6582. /// produce either the integer value or a pointer.
  6583. ///
  6584. /// GCC has a heinous extension which folds casts between pointer types and
  6585. /// pointer-sized integral types. We support this by allowing the evaluation of
  6586. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  6587. /// Some simple arithmetic on such values is supported (they are treated much
  6588. /// like char*).
  6589. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  6590. EvalInfo &Info) {
  6591. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  6592. return IntExprEvaluator(Info, Result).Visit(E);
  6593. }
  6594. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  6595. APValue Val;
  6596. if (!EvaluateIntegerOrLValue(E, Val, Info))
  6597. return false;
  6598. if (!Val.isInt()) {
  6599. // FIXME: It would be better to produce the diagnostic for casting
  6600. // a pointer to an integer.
  6601. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6602. return false;
  6603. }
  6604. Result = Val.getInt();
  6605. return true;
  6606. }
  6607. /// Check whether the given declaration can be directly converted to an integral
  6608. /// rvalue. If not, no diagnostic is produced; there are other things we can
  6609. /// try.
  6610. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  6611. // Enums are integer constant exprs.
  6612. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  6613. // Check for signedness/width mismatches between E type and ECD value.
  6614. bool SameSign = (ECD->getInitVal().isSigned()
  6615. == E->getType()->isSignedIntegerOrEnumerationType());
  6616. bool SameWidth = (ECD->getInitVal().getBitWidth()
  6617. == Info.Ctx.getIntWidth(E->getType()));
  6618. if (SameSign && SameWidth)
  6619. return Success(ECD->getInitVal(), E);
  6620. else {
  6621. // Get rid of mismatch (otherwise Success assertions will fail)
  6622. // by computing a new value matching the type of E.
  6623. llvm::APSInt Val = ECD->getInitVal();
  6624. if (!SameSign)
  6625. Val.setIsSigned(!ECD->getInitVal().isSigned());
  6626. if (!SameWidth)
  6627. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  6628. return Success(Val, E);
  6629. }
  6630. }
  6631. return false;
  6632. }
  6633. /// Values returned by __builtin_classify_type, chosen to match the values
  6634. /// produced by GCC's builtin.
  6635. enum class GCCTypeClass {
  6636. None = -1,
  6637. Void = 0,
  6638. Integer = 1,
  6639. // GCC reserves 2 for character types, but instead classifies them as
  6640. // integers.
  6641. Enum = 3,
  6642. Bool = 4,
  6643. Pointer = 5,
  6644. // GCC reserves 6 for references, but appears to never use it (because
  6645. // expressions never have reference type, presumably).
  6646. PointerToDataMember = 7,
  6647. RealFloat = 8,
  6648. Complex = 9,
  6649. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  6650. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6651. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  6652. // uses 12 for that purpose, same as for a class or struct. Maybe it
  6653. // internally implements a pointer to member as a struct? Who knows.
  6654. PointerToMemberFunction = 12, // Not a bug, see above.
  6655. ClassOrStruct = 12,
  6656. Union = 13,
  6657. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  6658. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6659. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  6660. // literals.
  6661. };
  6662. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6663. /// as GCC.
  6664. static GCCTypeClass
  6665. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  6666. assert(!T->isDependentType() && "unexpected dependent type");
  6667. QualType CanTy = T.getCanonicalType();
  6668. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  6669. switch (CanTy->getTypeClass()) {
  6670. #define TYPE(ID, BASE)
  6671. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6672. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  6673. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6674. #include "clang/AST/TypeNodes.def"
  6675. case Type::Auto:
  6676. case Type::DeducedTemplateSpecialization:
  6677. llvm_unreachable("unexpected non-canonical or dependent type");
  6678. case Type::Builtin:
  6679. switch (BT->getKind()) {
  6680. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  6681. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  6682. case BuiltinType::ID: return GCCTypeClass::Integer;
  6683. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  6684. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  6685. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  6686. case BuiltinType::ID: break;
  6687. #include "clang/AST/BuiltinTypes.def"
  6688. case BuiltinType::Void:
  6689. return GCCTypeClass::Void;
  6690. case BuiltinType::Bool:
  6691. return GCCTypeClass::Bool;
  6692. case BuiltinType::Char_U:
  6693. case BuiltinType::UChar:
  6694. case BuiltinType::WChar_U:
  6695. case BuiltinType::Char8:
  6696. case BuiltinType::Char16:
  6697. case BuiltinType::Char32:
  6698. case BuiltinType::UShort:
  6699. case BuiltinType::UInt:
  6700. case BuiltinType::ULong:
  6701. case BuiltinType::ULongLong:
  6702. case BuiltinType::UInt128:
  6703. return GCCTypeClass::Integer;
  6704. case BuiltinType::UShortAccum:
  6705. case BuiltinType::UAccum:
  6706. case BuiltinType::ULongAccum:
  6707. case BuiltinType::UShortFract:
  6708. case BuiltinType::UFract:
  6709. case BuiltinType::ULongFract:
  6710. case BuiltinType::SatUShortAccum:
  6711. case BuiltinType::SatUAccum:
  6712. case BuiltinType::SatULongAccum:
  6713. case BuiltinType::SatUShortFract:
  6714. case BuiltinType::SatUFract:
  6715. case BuiltinType::SatULongFract:
  6716. return GCCTypeClass::None;
  6717. case BuiltinType::NullPtr:
  6718. case BuiltinType::ObjCId:
  6719. case BuiltinType::ObjCClass:
  6720. case BuiltinType::ObjCSel:
  6721. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6722. case BuiltinType::Id:
  6723. #include "clang/Basic/OpenCLImageTypes.def"
  6724. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  6725. case BuiltinType::Id:
  6726. #include "clang/Basic/OpenCLExtensionTypes.def"
  6727. case BuiltinType::OCLSampler:
  6728. case BuiltinType::OCLEvent:
  6729. case BuiltinType::OCLClkEvent:
  6730. case BuiltinType::OCLQueue:
  6731. case BuiltinType::OCLReserveID:
  6732. return GCCTypeClass::None;
  6733. case BuiltinType::Dependent:
  6734. llvm_unreachable("unexpected dependent type");
  6735. };
  6736. llvm_unreachable("unexpected placeholder type");
  6737. case Type::Enum:
  6738. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  6739. case Type::Pointer:
  6740. case Type::ConstantArray:
  6741. case Type::VariableArray:
  6742. case Type::IncompleteArray:
  6743. case Type::FunctionNoProto:
  6744. case Type::FunctionProto:
  6745. return GCCTypeClass::Pointer;
  6746. case Type::MemberPointer:
  6747. return CanTy->isMemberDataPointerType()
  6748. ? GCCTypeClass::PointerToDataMember
  6749. : GCCTypeClass::PointerToMemberFunction;
  6750. case Type::Complex:
  6751. return GCCTypeClass::Complex;
  6752. case Type::Record:
  6753. return CanTy->isUnionType() ? GCCTypeClass::Union
  6754. : GCCTypeClass::ClassOrStruct;
  6755. case Type::Atomic:
  6756. // GCC classifies _Atomic T the same as T.
  6757. return EvaluateBuiltinClassifyType(
  6758. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  6759. case Type::BlockPointer:
  6760. case Type::Vector:
  6761. case Type::ExtVector:
  6762. case Type::ObjCObject:
  6763. case Type::ObjCInterface:
  6764. case Type::ObjCObjectPointer:
  6765. case Type::Pipe:
  6766. // GCC classifies vectors as None. We follow its lead and classify all
  6767. // other types that don't fit into the regular classification the same way.
  6768. return GCCTypeClass::None;
  6769. case Type::LValueReference:
  6770. case Type::RValueReference:
  6771. llvm_unreachable("invalid type for expression");
  6772. }
  6773. llvm_unreachable("unexpected type class");
  6774. }
  6775. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6776. /// as GCC.
  6777. static GCCTypeClass
  6778. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  6779. // If no argument was supplied, default to None. This isn't
  6780. // ideal, however it is what gcc does.
  6781. if (E->getNumArgs() == 0)
  6782. return GCCTypeClass::None;
  6783. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  6784. // being an ICE, but still folds it to a constant using the type of the first
  6785. // argument.
  6786. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  6787. }
  6788. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  6789. /// __builtin_constant_p when applied to the given lvalue.
  6790. ///
  6791. /// An lvalue is only "constant" if it is a pointer or reference to the first
  6792. /// character of a string literal.
  6793. template<typename LValue>
  6794. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  6795. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  6796. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  6797. }
  6798. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  6799. /// GCC as we can manage.
  6800. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  6801. QualType ArgType = Arg->getType();
  6802. // __builtin_constant_p always has one operand. The rules which gcc follows
  6803. // are not precisely documented, but are as follows:
  6804. //
  6805. // - If the operand is of integral, floating, complex or enumeration type,
  6806. // and can be folded to a known value of that type, it returns 1.
  6807. // - If the operand and can be folded to a pointer to the first character
  6808. // of a string literal (or such a pointer cast to an integral type), it
  6809. // returns 1.
  6810. //
  6811. // Otherwise, it returns 0.
  6812. //
  6813. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  6814. // its support for this does not currently work.
  6815. if (ArgType->isIntegralOrEnumerationType()) {
  6816. Expr::EvalResult Result;
  6817. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  6818. return false;
  6819. APValue &V = Result.Val;
  6820. if (V.getKind() == APValue::Int)
  6821. return true;
  6822. if (V.getKind() == APValue::LValue)
  6823. return EvaluateBuiltinConstantPForLValue(V);
  6824. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  6825. return Arg->isEvaluatable(Ctx);
  6826. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  6827. LValue LV;
  6828. Expr::EvalStatus Status;
  6829. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  6830. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  6831. : EvaluatePointer(Arg, LV, Info)) &&
  6832. !Status.HasSideEffects)
  6833. return EvaluateBuiltinConstantPForLValue(LV);
  6834. }
  6835. // Anything else isn't considered to be sufficiently constant.
  6836. return false;
  6837. }
  6838. /// Retrieves the "underlying object type" of the given expression,
  6839. /// as used by __builtin_object_size.
  6840. static QualType getObjectType(APValue::LValueBase B) {
  6841. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  6842. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  6843. return VD->getType();
  6844. } else if (const Expr *E = B.get<const Expr*>()) {
  6845. if (isa<CompoundLiteralExpr>(E))
  6846. return E->getType();
  6847. }
  6848. return QualType();
  6849. }
  6850. /// A more selective version of E->IgnoreParenCasts for
  6851. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  6852. /// to change the type of E.
  6853. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  6854. ///
  6855. /// Always returns an RValue with a pointer representation.
  6856. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  6857. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6858. auto *NoParens = E->IgnoreParens();
  6859. auto *Cast = dyn_cast<CastExpr>(NoParens);
  6860. if (Cast == nullptr)
  6861. return NoParens;
  6862. // We only conservatively allow a few kinds of casts, because this code is
  6863. // inherently a simple solution that seeks to support the common case.
  6864. auto CastKind = Cast->getCastKind();
  6865. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  6866. CastKind != CK_AddressSpaceConversion)
  6867. return NoParens;
  6868. auto *SubExpr = Cast->getSubExpr();
  6869. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  6870. return NoParens;
  6871. return ignorePointerCastsAndParens(SubExpr);
  6872. }
  6873. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  6874. /// record layout. e.g.
  6875. /// struct { struct { int a, b; } fst, snd; } obj;
  6876. /// obj.fst // no
  6877. /// obj.snd // yes
  6878. /// obj.fst.a // no
  6879. /// obj.fst.b // no
  6880. /// obj.snd.a // no
  6881. /// obj.snd.b // yes
  6882. ///
  6883. /// Please note: this function is specialized for how __builtin_object_size
  6884. /// views "objects".
  6885. ///
  6886. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  6887. /// correct result, it will always return true.
  6888. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  6889. assert(!LVal.Designator.Invalid);
  6890. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  6891. const RecordDecl *Parent = FD->getParent();
  6892. Invalid = Parent->isInvalidDecl();
  6893. if (Invalid || Parent->isUnion())
  6894. return true;
  6895. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  6896. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  6897. };
  6898. auto &Base = LVal.getLValueBase();
  6899. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  6900. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  6901. bool Invalid;
  6902. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6903. return Invalid;
  6904. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  6905. for (auto *FD : IFD->chain()) {
  6906. bool Invalid;
  6907. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  6908. return Invalid;
  6909. }
  6910. }
  6911. }
  6912. unsigned I = 0;
  6913. QualType BaseType = getType(Base);
  6914. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  6915. // If we don't know the array bound, conservatively assume we're looking at
  6916. // the final array element.
  6917. ++I;
  6918. if (BaseType->isIncompleteArrayType())
  6919. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  6920. else
  6921. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  6922. }
  6923. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  6924. const auto &Entry = LVal.Designator.Entries[I];
  6925. if (BaseType->isArrayType()) {
  6926. // Because __builtin_object_size treats arrays as objects, we can ignore
  6927. // the index iff this is the last array in the Designator.
  6928. if (I + 1 == E)
  6929. return true;
  6930. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  6931. uint64_t Index = Entry.ArrayIndex;
  6932. if (Index + 1 != CAT->getSize())
  6933. return false;
  6934. BaseType = CAT->getElementType();
  6935. } else if (BaseType->isAnyComplexType()) {
  6936. const auto *CT = BaseType->castAs<ComplexType>();
  6937. uint64_t Index = Entry.ArrayIndex;
  6938. if (Index != 1)
  6939. return false;
  6940. BaseType = CT->getElementType();
  6941. } else if (auto *FD = getAsField(Entry)) {
  6942. bool Invalid;
  6943. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6944. return Invalid;
  6945. BaseType = FD->getType();
  6946. } else {
  6947. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  6948. return false;
  6949. }
  6950. }
  6951. return true;
  6952. }
  6953. /// Tests to see if the LValue has a user-specified designator (that isn't
  6954. /// necessarily valid). Note that this always returns 'true' if the LValue has
  6955. /// an unsized array as its first designator entry, because there's currently no
  6956. /// way to tell if the user typed *foo or foo[0].
  6957. static bool refersToCompleteObject(const LValue &LVal) {
  6958. if (LVal.Designator.Invalid)
  6959. return false;
  6960. if (!LVal.Designator.Entries.empty())
  6961. return LVal.Designator.isMostDerivedAnUnsizedArray();
  6962. if (!LVal.InvalidBase)
  6963. return true;
  6964. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  6965. // the LValueBase.
  6966. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  6967. return !E || !isa<MemberExpr>(E);
  6968. }
  6969. /// Attempts to detect a user writing into a piece of memory that's impossible
  6970. /// to figure out the size of by just using types.
  6971. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  6972. const SubobjectDesignator &Designator = LVal.Designator;
  6973. // Notes:
  6974. // - Users can only write off of the end when we have an invalid base. Invalid
  6975. // bases imply we don't know where the memory came from.
  6976. // - We used to be a bit more aggressive here; we'd only be conservative if
  6977. // the array at the end was flexible, or if it had 0 or 1 elements. This
  6978. // broke some common standard library extensions (PR30346), but was
  6979. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  6980. // with some sort of whitelist. OTOH, it seems that GCC is always
  6981. // conservative with the last element in structs (if it's an array), so our
  6982. // current behavior is more compatible than a whitelisting approach would
  6983. // be.
  6984. return LVal.InvalidBase &&
  6985. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  6986. Designator.MostDerivedIsArrayElement &&
  6987. isDesignatorAtObjectEnd(Ctx, LVal);
  6988. }
  6989. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  6990. /// Fails if the conversion would cause loss of precision.
  6991. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  6992. CharUnits &Result) {
  6993. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  6994. if (Int.ugt(CharUnitsMax))
  6995. return false;
  6996. Result = CharUnits::fromQuantity(Int.getZExtValue());
  6997. return true;
  6998. }
  6999. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  7000. /// determine how many bytes exist from the beginning of the object to either
  7001. /// the end of the current subobject, or the end of the object itself, depending
  7002. /// on what the LValue looks like + the value of Type.
  7003. ///
  7004. /// If this returns false, the value of Result is undefined.
  7005. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  7006. unsigned Type, const LValue &LVal,
  7007. CharUnits &EndOffset) {
  7008. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  7009. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  7010. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  7011. return false;
  7012. return HandleSizeof(Info, ExprLoc, Ty, Result);
  7013. };
  7014. // We want to evaluate the size of the entire object. This is a valid fallback
  7015. // for when Type=1 and the designator is invalid, because we're asked for an
  7016. // upper-bound.
  7017. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  7018. // Type=3 wants a lower bound, so we can't fall back to this.
  7019. if (Type == 3 && !DetermineForCompleteObject)
  7020. return false;
  7021. llvm::APInt APEndOffset;
  7022. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7023. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7024. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7025. if (LVal.InvalidBase)
  7026. return false;
  7027. QualType BaseTy = getObjectType(LVal.getLValueBase());
  7028. return CheckedHandleSizeof(BaseTy, EndOffset);
  7029. }
  7030. // We want to evaluate the size of a subobject.
  7031. const SubobjectDesignator &Designator = LVal.Designator;
  7032. // The following is a moderately common idiom in C:
  7033. //
  7034. // struct Foo { int a; char c[1]; };
  7035. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  7036. // strcpy(&F->c[0], Bar);
  7037. //
  7038. // In order to not break too much legacy code, we need to support it.
  7039. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  7040. // If we can resolve this to an alloc_size call, we can hand that back,
  7041. // because we know for certain how many bytes there are to write to.
  7042. llvm::APInt APEndOffset;
  7043. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7044. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7045. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7046. // If we cannot determine the size of the initial allocation, then we can't
  7047. // given an accurate upper-bound. However, we are still able to give
  7048. // conservative lower-bounds for Type=3.
  7049. if (Type == 1)
  7050. return false;
  7051. }
  7052. CharUnits BytesPerElem;
  7053. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  7054. return false;
  7055. // According to the GCC documentation, we want the size of the subobject
  7056. // denoted by the pointer. But that's not quite right -- what we actually
  7057. // want is the size of the immediately-enclosing array, if there is one.
  7058. int64_t ElemsRemaining;
  7059. if (Designator.MostDerivedIsArrayElement &&
  7060. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  7061. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  7062. uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
  7063. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  7064. } else {
  7065. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  7066. }
  7067. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  7068. return true;
  7069. }
  7070. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  7071. /// returns true and stores the result in @p Size.
  7072. ///
  7073. /// If @p WasError is non-null, this will report whether the failure to evaluate
  7074. /// is to be treated as an Error in IntExprEvaluator.
  7075. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  7076. EvalInfo &Info, uint64_t &Size) {
  7077. // Determine the denoted object.
  7078. LValue LVal;
  7079. {
  7080. // The operand of __builtin_object_size is never evaluated for side-effects.
  7081. // If there are any, but we can determine the pointed-to object anyway, then
  7082. // ignore the side-effects.
  7083. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7084. IgnoreSideEffectsRAII Fold(Info);
  7085. if (E->isGLValue()) {
  7086. // It's possible for us to be given GLValues if we're called via
  7087. // Expr::tryEvaluateObjectSize.
  7088. APValue RVal;
  7089. if (!EvaluateAsRValue(Info, E, RVal))
  7090. return false;
  7091. LVal.setFrom(Info.Ctx, RVal);
  7092. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  7093. /*InvalidBaseOK=*/true))
  7094. return false;
  7095. }
  7096. // If we point to before the start of the object, there are no accessible
  7097. // bytes.
  7098. if (LVal.getLValueOffset().isNegative()) {
  7099. Size = 0;
  7100. return true;
  7101. }
  7102. CharUnits EndOffset;
  7103. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  7104. return false;
  7105. // If we've fallen outside of the end offset, just pretend there's nothing to
  7106. // write to/read from.
  7107. if (EndOffset <= LVal.getLValueOffset())
  7108. Size = 0;
  7109. else
  7110. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  7111. return true;
  7112. }
  7113. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7114. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7115. return VisitBuiltinCallExpr(E, BuiltinOp);
  7116. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7117. }
  7118. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7119. unsigned BuiltinOp) {
  7120. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  7121. default:
  7122. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7123. case Builtin::BI__builtin_object_size: {
  7124. // The type was checked when we built the expression.
  7125. unsigned Type =
  7126. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7127. assert(Type <= 3 && "unexpected type");
  7128. uint64_t Size;
  7129. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  7130. return Success(Size, E);
  7131. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  7132. return Success((Type & 2) ? 0 : -1, E);
  7133. // Expression had no side effects, but we couldn't statically determine the
  7134. // size of the referenced object.
  7135. switch (Info.EvalMode) {
  7136. case EvalInfo::EM_ConstantExpression:
  7137. case EvalInfo::EM_PotentialConstantExpression:
  7138. case EvalInfo::EM_ConstantFold:
  7139. case EvalInfo::EM_EvaluateForOverflow:
  7140. case EvalInfo::EM_IgnoreSideEffects:
  7141. // Leave it to IR generation.
  7142. return Error(E);
  7143. case EvalInfo::EM_ConstantExpressionUnevaluated:
  7144. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  7145. // Reduce it to a constant now.
  7146. return Success((Type & 2) ? 0 : -1, E);
  7147. }
  7148. llvm_unreachable("unexpected EvalMode");
  7149. }
  7150. case Builtin::BI__builtin_os_log_format_buffer_size: {
  7151. analyze_os_log::OSLogBufferLayout Layout;
  7152. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  7153. return Success(Layout.size().getQuantity(), E);
  7154. }
  7155. case Builtin::BI__builtin_bswap16:
  7156. case Builtin::BI__builtin_bswap32:
  7157. case Builtin::BI__builtin_bswap64: {
  7158. APSInt Val;
  7159. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7160. return false;
  7161. return Success(Val.byteSwap(), E);
  7162. }
  7163. case Builtin::BI__builtin_classify_type:
  7164. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  7165. case Builtin::BI__builtin_clrsb:
  7166. case Builtin::BI__builtin_clrsbl:
  7167. case Builtin::BI__builtin_clrsbll: {
  7168. APSInt Val;
  7169. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7170. return false;
  7171. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  7172. }
  7173. case Builtin::BI__builtin_clz:
  7174. case Builtin::BI__builtin_clzl:
  7175. case Builtin::BI__builtin_clzll:
  7176. case Builtin::BI__builtin_clzs: {
  7177. APSInt Val;
  7178. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7179. return false;
  7180. if (!Val)
  7181. return Error(E);
  7182. return Success(Val.countLeadingZeros(), E);
  7183. }
  7184. case Builtin::BI__builtin_constant_p:
  7185. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  7186. case Builtin::BI__builtin_ctz:
  7187. case Builtin::BI__builtin_ctzl:
  7188. case Builtin::BI__builtin_ctzll:
  7189. case Builtin::BI__builtin_ctzs: {
  7190. APSInt Val;
  7191. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7192. return false;
  7193. if (!Val)
  7194. return Error(E);
  7195. return Success(Val.countTrailingZeros(), E);
  7196. }
  7197. case Builtin::BI__builtin_eh_return_data_regno: {
  7198. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7199. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7200. return Success(Operand, E);
  7201. }
  7202. case Builtin::BI__builtin_expect:
  7203. return Visit(E->getArg(0));
  7204. case Builtin::BI__builtin_ffs:
  7205. case Builtin::BI__builtin_ffsl:
  7206. case Builtin::BI__builtin_ffsll: {
  7207. APSInt Val;
  7208. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7209. return false;
  7210. unsigned N = Val.countTrailingZeros();
  7211. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7212. }
  7213. case Builtin::BI__builtin_fpclassify: {
  7214. APFloat Val(0.0);
  7215. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7216. return false;
  7217. unsigned Arg;
  7218. switch (Val.getCategory()) {
  7219. case APFloat::fcNaN: Arg = 0; break;
  7220. case APFloat::fcInfinity: Arg = 1; break;
  7221. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7222. case APFloat::fcZero: Arg = 4; break;
  7223. }
  7224. return Visit(E->getArg(Arg));
  7225. }
  7226. case Builtin::BI__builtin_isinf_sign: {
  7227. APFloat Val(0.0);
  7228. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7229. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  7230. }
  7231. case Builtin::BI__builtin_isinf: {
  7232. APFloat Val(0.0);
  7233. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7234. Success(Val.isInfinity() ? 1 : 0, E);
  7235. }
  7236. case Builtin::BI__builtin_isfinite: {
  7237. APFloat Val(0.0);
  7238. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7239. Success(Val.isFinite() ? 1 : 0, E);
  7240. }
  7241. case Builtin::BI__builtin_isnan: {
  7242. APFloat Val(0.0);
  7243. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7244. Success(Val.isNaN() ? 1 : 0, E);
  7245. }
  7246. case Builtin::BI__builtin_isnormal: {
  7247. APFloat Val(0.0);
  7248. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7249. Success(Val.isNormal() ? 1 : 0, E);
  7250. }
  7251. case Builtin::BI__builtin_parity:
  7252. case Builtin::BI__builtin_parityl:
  7253. case Builtin::BI__builtin_parityll: {
  7254. APSInt Val;
  7255. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7256. return false;
  7257. return Success(Val.countPopulation() % 2, E);
  7258. }
  7259. case Builtin::BI__builtin_popcount:
  7260. case Builtin::BI__builtin_popcountl:
  7261. case Builtin::BI__builtin_popcountll: {
  7262. APSInt Val;
  7263. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7264. return false;
  7265. return Success(Val.countPopulation(), E);
  7266. }
  7267. case Builtin::BIstrlen:
  7268. case Builtin::BIwcslen:
  7269. // A call to strlen is not a constant expression.
  7270. if (Info.getLangOpts().CPlusPlus11)
  7271. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7272. << /*isConstexpr*/0 << /*isConstructor*/0
  7273. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7274. else
  7275. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7276. LLVM_FALLTHROUGH;
  7277. case Builtin::BI__builtin_strlen:
  7278. case Builtin::BI__builtin_wcslen: {
  7279. // As an extension, we support __builtin_strlen() as a constant expression,
  7280. // and support folding strlen() to a constant.
  7281. LValue String;
  7282. if (!EvaluatePointer(E->getArg(0), String, Info))
  7283. return false;
  7284. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7285. // Fast path: if it's a string literal, search the string value.
  7286. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  7287. String.getLValueBase().dyn_cast<const Expr *>())) {
  7288. // The string literal may have embedded null characters. Find the first
  7289. // one and truncate there.
  7290. StringRef Str = S->getBytes();
  7291. int64_t Off = String.Offset.getQuantity();
  7292. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  7293. S->getCharByteWidth() == 1 &&
  7294. // FIXME: Add fast-path for wchar_t too.
  7295. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  7296. Str = Str.substr(Off);
  7297. StringRef::size_type Pos = Str.find(0);
  7298. if (Pos != StringRef::npos)
  7299. Str = Str.substr(0, Pos);
  7300. return Success(Str.size(), E);
  7301. }
  7302. // Fall through to slow path to issue appropriate diagnostic.
  7303. }
  7304. // Slow path: scan the bytes of the string looking for the terminating 0.
  7305. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  7306. APValue Char;
  7307. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  7308. !Char.isInt())
  7309. return false;
  7310. if (!Char.getInt())
  7311. return Success(Strlen, E);
  7312. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  7313. return false;
  7314. }
  7315. }
  7316. case Builtin::BIstrcmp:
  7317. case Builtin::BIwcscmp:
  7318. case Builtin::BIstrncmp:
  7319. case Builtin::BIwcsncmp:
  7320. case Builtin::BImemcmp:
  7321. case Builtin::BIwmemcmp:
  7322. // A call to strlen is not a constant expression.
  7323. if (Info.getLangOpts().CPlusPlus11)
  7324. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7325. << /*isConstexpr*/0 << /*isConstructor*/0
  7326. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7327. else
  7328. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7329. LLVM_FALLTHROUGH;
  7330. case Builtin::BI__builtin_strcmp:
  7331. case Builtin::BI__builtin_wcscmp:
  7332. case Builtin::BI__builtin_strncmp:
  7333. case Builtin::BI__builtin_wcsncmp:
  7334. case Builtin::BI__builtin_memcmp:
  7335. case Builtin::BI__builtin_wmemcmp: {
  7336. LValue String1, String2;
  7337. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  7338. !EvaluatePointer(E->getArg(1), String2, Info))
  7339. return false;
  7340. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7341. uint64_t MaxLength = uint64_t(-1);
  7342. if (BuiltinOp != Builtin::BIstrcmp &&
  7343. BuiltinOp != Builtin::BIwcscmp &&
  7344. BuiltinOp != Builtin::BI__builtin_strcmp &&
  7345. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  7346. APSInt N;
  7347. if (!EvaluateInteger(E->getArg(2), N, Info))
  7348. return false;
  7349. MaxLength = N.getExtValue();
  7350. }
  7351. bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
  7352. BuiltinOp != Builtin::BIwmemcmp &&
  7353. BuiltinOp != Builtin::BI__builtin_memcmp &&
  7354. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  7355. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  7356. BuiltinOp == Builtin::BIwcsncmp ||
  7357. BuiltinOp == Builtin::BIwmemcmp ||
  7358. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  7359. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  7360. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  7361. for (; MaxLength; --MaxLength) {
  7362. APValue Char1, Char2;
  7363. if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
  7364. !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
  7365. !Char1.isInt() || !Char2.isInt())
  7366. return false;
  7367. if (Char1.getInt() != Char2.getInt()) {
  7368. if (IsWide) // wmemcmp compares with wchar_t signedness.
  7369. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  7370. // memcmp always compares unsigned chars.
  7371. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  7372. }
  7373. if (StopAtNull && !Char1.getInt())
  7374. return Success(0, E);
  7375. assert(!(StopAtNull && !Char2.getInt()));
  7376. if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
  7377. !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
  7378. return false;
  7379. }
  7380. // We hit the strncmp / memcmp limit.
  7381. return Success(0, E);
  7382. }
  7383. case Builtin::BI__atomic_always_lock_free:
  7384. case Builtin::BI__atomic_is_lock_free:
  7385. case Builtin::BI__c11_atomic_is_lock_free: {
  7386. APSInt SizeVal;
  7387. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  7388. return false;
  7389. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  7390. // of two less than the maximum inline atomic width, we know it is
  7391. // lock-free. If the size isn't a power of two, or greater than the
  7392. // maximum alignment where we promote atomics, we know it is not lock-free
  7393. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  7394. // the answer can only be determined at runtime; for example, 16-byte
  7395. // atomics have lock-free implementations on some, but not all,
  7396. // x86-64 processors.
  7397. // Check power-of-two.
  7398. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  7399. if (Size.isPowerOfTwo()) {
  7400. // Check against inlining width.
  7401. unsigned InlineWidthBits =
  7402. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  7403. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  7404. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  7405. Size == CharUnits::One() ||
  7406. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  7407. Expr::NPC_NeverValueDependent))
  7408. // OK, we will inline appropriately-aligned operations of this size,
  7409. // and _Atomic(T) is appropriately-aligned.
  7410. return Success(1, E);
  7411. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  7412. castAs<PointerType>()->getPointeeType();
  7413. if (!PointeeType->isIncompleteType() &&
  7414. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  7415. // OK, we will inline operations on this object.
  7416. return Success(1, E);
  7417. }
  7418. }
  7419. }
  7420. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  7421. Success(0, E) : Error(E);
  7422. }
  7423. case Builtin::BIomp_is_initial_device:
  7424. // We can decide statically which value the runtime would return if called.
  7425. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  7426. case Builtin::BI__builtin_add_overflow:
  7427. case Builtin::BI__builtin_sub_overflow:
  7428. case Builtin::BI__builtin_mul_overflow:
  7429. case Builtin::BI__builtin_sadd_overflow:
  7430. case Builtin::BI__builtin_uadd_overflow:
  7431. case Builtin::BI__builtin_uaddl_overflow:
  7432. case Builtin::BI__builtin_uaddll_overflow:
  7433. case Builtin::BI__builtin_usub_overflow:
  7434. case Builtin::BI__builtin_usubl_overflow:
  7435. case Builtin::BI__builtin_usubll_overflow:
  7436. case Builtin::BI__builtin_umul_overflow:
  7437. case Builtin::BI__builtin_umull_overflow:
  7438. case Builtin::BI__builtin_umulll_overflow:
  7439. case Builtin::BI__builtin_saddl_overflow:
  7440. case Builtin::BI__builtin_saddll_overflow:
  7441. case Builtin::BI__builtin_ssub_overflow:
  7442. case Builtin::BI__builtin_ssubl_overflow:
  7443. case Builtin::BI__builtin_ssubll_overflow:
  7444. case Builtin::BI__builtin_smul_overflow:
  7445. case Builtin::BI__builtin_smull_overflow:
  7446. case Builtin::BI__builtin_smulll_overflow: {
  7447. LValue ResultLValue;
  7448. APSInt LHS, RHS;
  7449. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  7450. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  7451. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  7452. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  7453. return false;
  7454. APSInt Result;
  7455. bool DidOverflow = false;
  7456. // If the types don't have to match, enlarge all 3 to the largest of them.
  7457. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7458. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7459. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7460. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  7461. ResultType->isSignedIntegerOrEnumerationType();
  7462. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  7463. ResultType->isSignedIntegerOrEnumerationType();
  7464. uint64_t LHSSize = LHS.getBitWidth();
  7465. uint64_t RHSSize = RHS.getBitWidth();
  7466. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  7467. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  7468. // Add an additional bit if the signedness isn't uniformly agreed to. We
  7469. // could do this ONLY if there is a signed and an unsigned that both have
  7470. // MaxBits, but the code to check that is pretty nasty. The issue will be
  7471. // caught in the shrink-to-result later anyway.
  7472. if (IsSigned && !AllSigned)
  7473. ++MaxBits;
  7474. LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
  7475. !IsSigned);
  7476. RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
  7477. !IsSigned);
  7478. Result = APSInt(MaxBits, !IsSigned);
  7479. }
  7480. // Find largest int.
  7481. switch (BuiltinOp) {
  7482. default:
  7483. llvm_unreachable("Invalid value for BuiltinOp");
  7484. case Builtin::BI__builtin_add_overflow:
  7485. case Builtin::BI__builtin_sadd_overflow:
  7486. case Builtin::BI__builtin_saddl_overflow:
  7487. case Builtin::BI__builtin_saddll_overflow:
  7488. case Builtin::BI__builtin_uadd_overflow:
  7489. case Builtin::BI__builtin_uaddl_overflow:
  7490. case Builtin::BI__builtin_uaddll_overflow:
  7491. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  7492. : LHS.uadd_ov(RHS, DidOverflow);
  7493. break;
  7494. case Builtin::BI__builtin_sub_overflow:
  7495. case Builtin::BI__builtin_ssub_overflow:
  7496. case Builtin::BI__builtin_ssubl_overflow:
  7497. case Builtin::BI__builtin_ssubll_overflow:
  7498. case Builtin::BI__builtin_usub_overflow:
  7499. case Builtin::BI__builtin_usubl_overflow:
  7500. case Builtin::BI__builtin_usubll_overflow:
  7501. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  7502. : LHS.usub_ov(RHS, DidOverflow);
  7503. break;
  7504. case Builtin::BI__builtin_mul_overflow:
  7505. case Builtin::BI__builtin_smul_overflow:
  7506. case Builtin::BI__builtin_smull_overflow:
  7507. case Builtin::BI__builtin_smulll_overflow:
  7508. case Builtin::BI__builtin_umul_overflow:
  7509. case Builtin::BI__builtin_umull_overflow:
  7510. case Builtin::BI__builtin_umulll_overflow:
  7511. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  7512. : LHS.umul_ov(RHS, DidOverflow);
  7513. break;
  7514. }
  7515. // In the case where multiple sizes are allowed, truncate and see if
  7516. // the values are the same.
  7517. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7518. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7519. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7520. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  7521. // since it will give us the behavior of a TruncOrSelf in the case where
  7522. // its parameter <= its size. We previously set Result to be at least the
  7523. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  7524. // will work exactly like TruncOrSelf.
  7525. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  7526. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  7527. if (!APSInt::isSameValue(Temp, Result))
  7528. DidOverflow = true;
  7529. Result = Temp;
  7530. }
  7531. APValue APV{Result};
  7532. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  7533. return false;
  7534. return Success(DidOverflow, E);
  7535. }
  7536. }
  7537. }
  7538. /// Determine whether this is a pointer past the end of the complete
  7539. /// object referred to by the lvalue.
  7540. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  7541. const LValue &LV) {
  7542. // A null pointer can be viewed as being "past the end" but we don't
  7543. // choose to look at it that way here.
  7544. if (!LV.getLValueBase())
  7545. return false;
  7546. // If the designator is valid and refers to a subobject, we're not pointing
  7547. // past the end.
  7548. if (!LV.getLValueDesignator().Invalid &&
  7549. !LV.getLValueDesignator().isOnePastTheEnd())
  7550. return false;
  7551. // A pointer to an incomplete type might be past-the-end if the type's size is
  7552. // zero. We cannot tell because the type is incomplete.
  7553. QualType Ty = getType(LV.getLValueBase());
  7554. if (Ty->isIncompleteType())
  7555. return true;
  7556. // We're a past-the-end pointer if we point to the byte after the object,
  7557. // no matter what our type or path is.
  7558. auto Size = Ctx.getTypeSizeInChars(Ty);
  7559. return LV.getLValueOffset() == Size;
  7560. }
  7561. namespace {
  7562. /// Data recursive integer evaluator of certain binary operators.
  7563. ///
  7564. /// We use a data recursive algorithm for binary operators so that we are able
  7565. /// to handle extreme cases of chained binary operators without causing stack
  7566. /// overflow.
  7567. class DataRecursiveIntBinOpEvaluator {
  7568. struct EvalResult {
  7569. APValue Val;
  7570. bool Failed;
  7571. EvalResult() : Failed(false) { }
  7572. void swap(EvalResult &RHS) {
  7573. Val.swap(RHS.Val);
  7574. Failed = RHS.Failed;
  7575. RHS.Failed = false;
  7576. }
  7577. };
  7578. struct Job {
  7579. const Expr *E;
  7580. EvalResult LHSResult; // meaningful only for binary operator expression.
  7581. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  7582. Job() = default;
  7583. Job(Job &&) = default;
  7584. void startSpeculativeEval(EvalInfo &Info) {
  7585. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  7586. }
  7587. private:
  7588. SpeculativeEvaluationRAII SpecEvalRAII;
  7589. };
  7590. SmallVector<Job, 16> Queue;
  7591. IntExprEvaluator &IntEval;
  7592. EvalInfo &Info;
  7593. APValue &FinalResult;
  7594. public:
  7595. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  7596. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  7597. /// True if \param E is a binary operator that we are going to handle
  7598. /// data recursively.
  7599. /// We handle binary operators that are comma, logical, or that have operands
  7600. /// with integral or enumeration type.
  7601. static bool shouldEnqueue(const BinaryOperator *E) {
  7602. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  7603. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  7604. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7605. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7606. }
  7607. bool Traverse(const BinaryOperator *E) {
  7608. enqueue(E);
  7609. EvalResult PrevResult;
  7610. while (!Queue.empty())
  7611. process(PrevResult);
  7612. if (PrevResult.Failed) return false;
  7613. FinalResult.swap(PrevResult.Val);
  7614. return true;
  7615. }
  7616. private:
  7617. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7618. return IntEval.Success(Value, E, Result);
  7619. }
  7620. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  7621. return IntEval.Success(Value, E, Result);
  7622. }
  7623. bool Error(const Expr *E) {
  7624. return IntEval.Error(E);
  7625. }
  7626. bool Error(const Expr *E, diag::kind D) {
  7627. return IntEval.Error(E, D);
  7628. }
  7629. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  7630. return Info.CCEDiag(E, D);
  7631. }
  7632. // Returns true if visiting the RHS is necessary, false otherwise.
  7633. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7634. bool &SuppressRHSDiags);
  7635. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7636. const BinaryOperator *E, APValue &Result);
  7637. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  7638. Result.Failed = !Evaluate(Result.Val, Info, E);
  7639. if (Result.Failed)
  7640. Result.Val = APValue();
  7641. }
  7642. void process(EvalResult &Result);
  7643. void enqueue(const Expr *E) {
  7644. E = E->IgnoreParens();
  7645. Queue.resize(Queue.size()+1);
  7646. Queue.back().E = E;
  7647. Queue.back().Kind = Job::AnyExprKind;
  7648. }
  7649. };
  7650. }
  7651. bool DataRecursiveIntBinOpEvaluator::
  7652. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7653. bool &SuppressRHSDiags) {
  7654. if (E->getOpcode() == BO_Comma) {
  7655. // Ignore LHS but note if we could not evaluate it.
  7656. if (LHSResult.Failed)
  7657. return Info.noteSideEffect();
  7658. return true;
  7659. }
  7660. if (E->isLogicalOp()) {
  7661. bool LHSAsBool;
  7662. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  7663. // We were able to evaluate the LHS, see if we can get away with not
  7664. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  7665. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  7666. Success(LHSAsBool, E, LHSResult.Val);
  7667. return false; // Ignore RHS
  7668. }
  7669. } else {
  7670. LHSResult.Failed = true;
  7671. // Since we weren't able to evaluate the left hand side, it
  7672. // might have had side effects.
  7673. if (!Info.noteSideEffect())
  7674. return false;
  7675. // We can't evaluate the LHS; however, sometimes the result
  7676. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7677. // Don't ignore RHS and suppress diagnostics from this arm.
  7678. SuppressRHSDiags = true;
  7679. }
  7680. return true;
  7681. }
  7682. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7683. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7684. if (LHSResult.Failed && !Info.noteFailure())
  7685. return false; // Ignore RHS;
  7686. return true;
  7687. }
  7688. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  7689. bool IsSub) {
  7690. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  7691. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  7692. // offsets.
  7693. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  7694. CharUnits &Offset = LVal.getLValueOffset();
  7695. uint64_t Offset64 = Offset.getQuantity();
  7696. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  7697. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  7698. : Offset64 + Index64);
  7699. }
  7700. bool DataRecursiveIntBinOpEvaluator::
  7701. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7702. const BinaryOperator *E, APValue &Result) {
  7703. if (E->getOpcode() == BO_Comma) {
  7704. if (RHSResult.Failed)
  7705. return false;
  7706. Result = RHSResult.Val;
  7707. return true;
  7708. }
  7709. if (E->isLogicalOp()) {
  7710. bool lhsResult, rhsResult;
  7711. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  7712. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  7713. if (LHSIsOK) {
  7714. if (RHSIsOK) {
  7715. if (E->getOpcode() == BO_LOr)
  7716. return Success(lhsResult || rhsResult, E, Result);
  7717. else
  7718. return Success(lhsResult && rhsResult, E, Result);
  7719. }
  7720. } else {
  7721. if (RHSIsOK) {
  7722. // We can't evaluate the LHS; however, sometimes the result
  7723. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7724. if (rhsResult == (E->getOpcode() == BO_LOr))
  7725. return Success(rhsResult, E, Result);
  7726. }
  7727. }
  7728. return false;
  7729. }
  7730. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7731. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7732. if (LHSResult.Failed || RHSResult.Failed)
  7733. return false;
  7734. const APValue &LHSVal = LHSResult.Val;
  7735. const APValue &RHSVal = RHSResult.Val;
  7736. // Handle cases like (unsigned long)&a + 4.
  7737. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  7738. Result = LHSVal;
  7739. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  7740. return true;
  7741. }
  7742. // Handle cases like 4 + (unsigned long)&a
  7743. if (E->getOpcode() == BO_Add &&
  7744. RHSVal.isLValue() && LHSVal.isInt()) {
  7745. Result = RHSVal;
  7746. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  7747. return true;
  7748. }
  7749. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  7750. // Handle (intptr_t)&&A - (intptr_t)&&B.
  7751. if (!LHSVal.getLValueOffset().isZero() ||
  7752. !RHSVal.getLValueOffset().isZero())
  7753. return false;
  7754. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  7755. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  7756. if (!LHSExpr || !RHSExpr)
  7757. return false;
  7758. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  7759. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  7760. if (!LHSAddrExpr || !RHSAddrExpr)
  7761. return false;
  7762. // Make sure both labels come from the same function.
  7763. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  7764. RHSAddrExpr->getLabel()->getDeclContext())
  7765. return false;
  7766. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  7767. return true;
  7768. }
  7769. // All the remaining cases expect both operands to be an integer
  7770. if (!LHSVal.isInt() || !RHSVal.isInt())
  7771. return Error(E);
  7772. // Set up the width and signedness manually, in case it can't be deduced
  7773. // from the operation we're performing.
  7774. // FIXME: Don't do this in the cases where we can deduce it.
  7775. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  7776. E->getType()->isUnsignedIntegerOrEnumerationType());
  7777. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  7778. RHSVal.getInt(), Value))
  7779. return false;
  7780. return Success(Value, E, Result);
  7781. }
  7782. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  7783. Job &job = Queue.back();
  7784. switch (job.Kind) {
  7785. case Job::AnyExprKind: {
  7786. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  7787. if (shouldEnqueue(Bop)) {
  7788. job.Kind = Job::BinOpKind;
  7789. enqueue(Bop->getLHS());
  7790. return;
  7791. }
  7792. }
  7793. EvaluateExpr(job.E, Result);
  7794. Queue.pop_back();
  7795. return;
  7796. }
  7797. case Job::BinOpKind: {
  7798. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7799. bool SuppressRHSDiags = false;
  7800. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  7801. Queue.pop_back();
  7802. return;
  7803. }
  7804. if (SuppressRHSDiags)
  7805. job.startSpeculativeEval(Info);
  7806. job.LHSResult.swap(Result);
  7807. job.Kind = Job::BinOpVisitedLHSKind;
  7808. enqueue(Bop->getRHS());
  7809. return;
  7810. }
  7811. case Job::BinOpVisitedLHSKind: {
  7812. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7813. EvalResult RHS;
  7814. RHS.swap(Result);
  7815. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  7816. Queue.pop_back();
  7817. return;
  7818. }
  7819. }
  7820. llvm_unreachable("Invalid Job::Kind!");
  7821. }
  7822. namespace {
  7823. /// Used when we determine that we should fail, but can keep evaluating prior to
  7824. /// noting that we had a failure.
  7825. class DelayedNoteFailureRAII {
  7826. EvalInfo &Info;
  7827. bool NoteFailure;
  7828. public:
  7829. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  7830. : Info(Info), NoteFailure(NoteFailure) {}
  7831. ~DelayedNoteFailureRAII() {
  7832. if (NoteFailure) {
  7833. bool ContinueAfterFailure = Info.noteFailure();
  7834. (void)ContinueAfterFailure;
  7835. assert(ContinueAfterFailure &&
  7836. "Shouldn't have kept evaluating on failure.");
  7837. }
  7838. }
  7839. };
  7840. }
  7841. template <class SuccessCB, class AfterCB>
  7842. static bool
  7843. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  7844. SuccessCB &&Success, AfterCB &&DoAfter) {
  7845. assert(E->isComparisonOp() && "expected comparison operator");
  7846. assert((E->getOpcode() == BO_Cmp ||
  7847. E->getType()->isIntegralOrEnumerationType()) &&
  7848. "unsupported binary expression evaluation");
  7849. auto Error = [&](const Expr *E) {
  7850. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7851. return false;
  7852. };
  7853. using CCR = ComparisonCategoryResult;
  7854. bool IsRelational = E->isRelationalOp();
  7855. bool IsEquality = E->isEqualityOp();
  7856. if (E->getOpcode() == BO_Cmp) {
  7857. const ComparisonCategoryInfo &CmpInfo =
  7858. Info.Ctx.CompCategories.getInfoForType(E->getType());
  7859. IsRelational = CmpInfo.isOrdered();
  7860. IsEquality = CmpInfo.isEquality();
  7861. }
  7862. QualType LHSTy = E->getLHS()->getType();
  7863. QualType RHSTy = E->getRHS()->getType();
  7864. if (LHSTy->isIntegralOrEnumerationType() &&
  7865. RHSTy->isIntegralOrEnumerationType()) {
  7866. APSInt LHS, RHS;
  7867. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  7868. if (!LHSOK && !Info.noteFailure())
  7869. return false;
  7870. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  7871. return false;
  7872. if (LHS < RHS)
  7873. return Success(CCR::Less, E);
  7874. if (LHS > RHS)
  7875. return Success(CCR::Greater, E);
  7876. return Success(CCR::Equal, E);
  7877. }
  7878. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  7879. ComplexValue LHS, RHS;
  7880. bool LHSOK;
  7881. if (E->isAssignmentOp()) {
  7882. LValue LV;
  7883. EvaluateLValue(E->getLHS(), LV, Info);
  7884. LHSOK = false;
  7885. } else if (LHSTy->isRealFloatingType()) {
  7886. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  7887. if (LHSOK) {
  7888. LHS.makeComplexFloat();
  7889. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  7890. }
  7891. } else {
  7892. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  7893. }
  7894. if (!LHSOK && !Info.noteFailure())
  7895. return false;
  7896. if (E->getRHS()->getType()->isRealFloatingType()) {
  7897. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  7898. return false;
  7899. RHS.makeComplexFloat();
  7900. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  7901. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7902. return false;
  7903. if (LHS.isComplexFloat()) {
  7904. APFloat::cmpResult CR_r =
  7905. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  7906. APFloat::cmpResult CR_i =
  7907. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  7908. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  7909. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7910. } else {
  7911. assert(IsEquality && "invalid complex comparison");
  7912. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  7913. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  7914. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7915. }
  7916. }
  7917. if (LHSTy->isRealFloatingType() &&
  7918. RHSTy->isRealFloatingType()) {
  7919. APFloat RHS(0.0), LHS(0.0);
  7920. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  7921. if (!LHSOK && !Info.noteFailure())
  7922. return false;
  7923. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  7924. return false;
  7925. assert(E->isComparisonOp() && "Invalid binary operator!");
  7926. auto GetCmpRes = [&]() {
  7927. switch (LHS.compare(RHS)) {
  7928. case APFloat::cmpEqual:
  7929. return CCR::Equal;
  7930. case APFloat::cmpLessThan:
  7931. return CCR::Less;
  7932. case APFloat::cmpGreaterThan:
  7933. return CCR::Greater;
  7934. case APFloat::cmpUnordered:
  7935. return CCR::Unordered;
  7936. }
  7937. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  7938. };
  7939. return Success(GetCmpRes(), E);
  7940. }
  7941. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  7942. LValue LHSValue, RHSValue;
  7943. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  7944. if (!LHSOK && !Info.noteFailure())
  7945. return false;
  7946. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7947. return false;
  7948. // Reject differing bases from the normal codepath; we special-case
  7949. // comparisons to null.
  7950. if (!HasSameBase(LHSValue, RHSValue)) {
  7951. // Inequalities and subtractions between unrelated pointers have
  7952. // unspecified or undefined behavior.
  7953. if (!IsEquality)
  7954. return Error(E);
  7955. // A constant address may compare equal to the address of a symbol.
  7956. // The one exception is that address of an object cannot compare equal
  7957. // to a null pointer constant.
  7958. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  7959. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  7960. return Error(E);
  7961. // It's implementation-defined whether distinct literals will have
  7962. // distinct addresses. In clang, the result of such a comparison is
  7963. // unspecified, so it is not a constant expression. However, we do know
  7964. // that the address of a literal will be non-null.
  7965. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  7966. LHSValue.Base && RHSValue.Base)
  7967. return Error(E);
  7968. // We can't tell whether weak symbols will end up pointing to the same
  7969. // object.
  7970. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  7971. return Error(E);
  7972. // We can't compare the address of the start of one object with the
  7973. // past-the-end address of another object, per C++ DR1652.
  7974. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  7975. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  7976. (RHSValue.Base && RHSValue.Offset.isZero() &&
  7977. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  7978. return Error(E);
  7979. // We can't tell whether an object is at the same address as another
  7980. // zero sized object.
  7981. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  7982. (LHSValue.Base && isZeroSized(RHSValue)))
  7983. return Error(E);
  7984. return Success(CCR::Nonequal, E);
  7985. }
  7986. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  7987. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  7988. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  7989. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  7990. // C++11 [expr.rel]p3:
  7991. // Pointers to void (after pointer conversions) can be compared, with a
  7992. // result defined as follows: If both pointers represent the same
  7993. // address or are both the null pointer value, the result is true if the
  7994. // operator is <= or >= and false otherwise; otherwise the result is
  7995. // unspecified.
  7996. // We interpret this as applying to pointers to *cv* void.
  7997. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  7998. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  7999. // C++11 [expr.rel]p2:
  8000. // - If two pointers point to non-static data members of the same object,
  8001. // or to subobjects or array elements fo such members, recursively, the
  8002. // pointer to the later declared member compares greater provided the
  8003. // two members have the same access control and provided their class is
  8004. // not a union.
  8005. // [...]
  8006. // - Otherwise pointer comparisons are unspecified.
  8007. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  8008. bool WasArrayIndex;
  8009. unsigned Mismatch = FindDesignatorMismatch(
  8010. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  8011. // At the point where the designators diverge, the comparison has a
  8012. // specified value if:
  8013. // - we are comparing array indices
  8014. // - we are comparing fields of a union, or fields with the same access
  8015. // Otherwise, the result is unspecified and thus the comparison is not a
  8016. // constant expression.
  8017. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  8018. Mismatch < RHSDesignator.Entries.size()) {
  8019. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  8020. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  8021. if (!LF && !RF)
  8022. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  8023. else if (!LF)
  8024. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8025. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  8026. << RF->getParent() << RF;
  8027. else if (!RF)
  8028. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8029. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  8030. << LF->getParent() << LF;
  8031. else if (!LF->getParent()->isUnion() &&
  8032. LF->getAccess() != RF->getAccess())
  8033. Info.CCEDiag(E,
  8034. diag::note_constexpr_pointer_comparison_differing_access)
  8035. << LF << LF->getAccess() << RF << RF->getAccess()
  8036. << LF->getParent();
  8037. }
  8038. }
  8039. // The comparison here must be unsigned, and performed with the same
  8040. // width as the pointer.
  8041. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  8042. uint64_t CompareLHS = LHSOffset.getQuantity();
  8043. uint64_t CompareRHS = RHSOffset.getQuantity();
  8044. assert(PtrSize <= 64 && "Unexpected pointer width");
  8045. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  8046. CompareLHS &= Mask;
  8047. CompareRHS &= Mask;
  8048. // If there is a base and this is a relational operator, we can only
  8049. // compare pointers within the object in question; otherwise, the result
  8050. // depends on where the object is located in memory.
  8051. if (!LHSValue.Base.isNull() && IsRelational) {
  8052. QualType BaseTy = getType(LHSValue.Base);
  8053. if (BaseTy->isIncompleteType())
  8054. return Error(E);
  8055. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  8056. uint64_t OffsetLimit = Size.getQuantity();
  8057. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  8058. return Error(E);
  8059. }
  8060. if (CompareLHS < CompareRHS)
  8061. return Success(CCR::Less, E);
  8062. if (CompareLHS > CompareRHS)
  8063. return Success(CCR::Greater, E);
  8064. return Success(CCR::Equal, E);
  8065. }
  8066. if (LHSTy->isMemberPointerType()) {
  8067. assert(IsEquality && "unexpected member pointer operation");
  8068. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  8069. MemberPtr LHSValue, RHSValue;
  8070. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  8071. if (!LHSOK && !Info.noteFailure())
  8072. return false;
  8073. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8074. return false;
  8075. // C++11 [expr.eq]p2:
  8076. // If both operands are null, they compare equal. Otherwise if only one is
  8077. // null, they compare unequal.
  8078. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  8079. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  8080. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8081. }
  8082. // Otherwise if either is a pointer to a virtual member function, the
  8083. // result is unspecified.
  8084. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  8085. if (MD->isVirtual())
  8086. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8087. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  8088. if (MD->isVirtual())
  8089. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8090. // Otherwise they compare equal if and only if they would refer to the
  8091. // same member of the same most derived object or the same subobject if
  8092. // they were dereferenced with a hypothetical object of the associated
  8093. // class type.
  8094. bool Equal = LHSValue == RHSValue;
  8095. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8096. }
  8097. if (LHSTy->isNullPtrType()) {
  8098. assert(E->isComparisonOp() && "unexpected nullptr operation");
  8099. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  8100. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  8101. // are compared, the result is true of the operator is <=, >= or ==, and
  8102. // false otherwise.
  8103. return Success(CCR::Equal, E);
  8104. }
  8105. return DoAfter();
  8106. }
  8107. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  8108. if (!CheckLiteralType(Info, E))
  8109. return false;
  8110. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8111. const BinaryOperator *E) {
  8112. // Evaluation succeeded. Lookup the information for the comparison category
  8113. // type and fetch the VarDecl for the result.
  8114. const ComparisonCategoryInfo &CmpInfo =
  8115. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8116. const VarDecl *VD =
  8117. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  8118. // Check and evaluate the result as a constant expression.
  8119. LValue LV;
  8120. LV.set(VD);
  8121. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8122. return false;
  8123. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8124. };
  8125. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8126. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  8127. });
  8128. }
  8129. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8130. // We don't call noteFailure immediately because the assignment happens after
  8131. // we evaluate LHS and RHS.
  8132. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  8133. return Error(E);
  8134. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  8135. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  8136. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  8137. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  8138. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  8139. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  8140. if (E->isComparisonOp()) {
  8141. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  8142. // comparisons and then translating the result.
  8143. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8144. const BinaryOperator *E) {
  8145. using CCR = ComparisonCategoryResult;
  8146. bool IsEqual = ResKind == CCR::Equal,
  8147. IsLess = ResKind == CCR::Less,
  8148. IsGreater = ResKind == CCR::Greater;
  8149. auto Op = E->getOpcode();
  8150. switch (Op) {
  8151. default:
  8152. llvm_unreachable("unsupported binary operator");
  8153. case BO_EQ:
  8154. case BO_NE:
  8155. return Success(IsEqual == (Op == BO_EQ), E);
  8156. case BO_LT: return Success(IsLess, E);
  8157. case BO_GT: return Success(IsGreater, E);
  8158. case BO_LE: return Success(IsEqual || IsLess, E);
  8159. case BO_GE: return Success(IsEqual || IsGreater, E);
  8160. }
  8161. };
  8162. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8163. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8164. });
  8165. }
  8166. QualType LHSTy = E->getLHS()->getType();
  8167. QualType RHSTy = E->getRHS()->getType();
  8168. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  8169. E->getOpcode() == BO_Sub) {
  8170. LValue LHSValue, RHSValue;
  8171. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8172. if (!LHSOK && !Info.noteFailure())
  8173. return false;
  8174. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8175. return false;
  8176. // Reject differing bases from the normal codepath; we special-case
  8177. // comparisons to null.
  8178. if (!HasSameBase(LHSValue, RHSValue)) {
  8179. // Handle &&A - &&B.
  8180. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  8181. return Error(E);
  8182. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  8183. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  8184. if (!LHSExpr || !RHSExpr)
  8185. return Error(E);
  8186. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8187. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8188. if (!LHSAddrExpr || !RHSAddrExpr)
  8189. return Error(E);
  8190. // Make sure both labels come from the same function.
  8191. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8192. RHSAddrExpr->getLabel()->getDeclContext())
  8193. return Error(E);
  8194. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  8195. }
  8196. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8197. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8198. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8199. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8200. // C++11 [expr.add]p6:
  8201. // Unless both pointers point to elements of the same array object, or
  8202. // one past the last element of the array object, the behavior is
  8203. // undefined.
  8204. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  8205. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  8206. RHSDesignator))
  8207. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  8208. QualType Type = E->getLHS()->getType();
  8209. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  8210. CharUnits ElementSize;
  8211. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  8212. return false;
  8213. // As an extension, a type may have zero size (empty struct or union in
  8214. // C, array of zero length). Pointer subtraction in such cases has
  8215. // undefined behavior, so is not constant.
  8216. if (ElementSize.isZero()) {
  8217. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  8218. << ElementType;
  8219. return false;
  8220. }
  8221. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  8222. // and produce incorrect results when it overflows. Such behavior
  8223. // appears to be non-conforming, but is common, so perhaps we should
  8224. // assume the standard intended for such cases to be undefined behavior
  8225. // and check for them.
  8226. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  8227. // overflow in the final conversion to ptrdiff_t.
  8228. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  8229. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  8230. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  8231. false);
  8232. APSInt TrueResult = (LHS - RHS) / ElemSize;
  8233. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  8234. if (Result.extend(65) != TrueResult &&
  8235. !HandleOverflow(Info, E, TrueResult, E->getType()))
  8236. return false;
  8237. return Success(Result, E);
  8238. }
  8239. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8240. }
  8241. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  8242. /// a result as the expression's type.
  8243. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  8244. const UnaryExprOrTypeTraitExpr *E) {
  8245. switch(E->getKind()) {
  8246. case UETT_PreferredAlignOf:
  8247. case UETT_AlignOf: {
  8248. if (E->isArgumentType())
  8249. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  8250. E);
  8251. else
  8252. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  8253. E);
  8254. }
  8255. case UETT_VecStep: {
  8256. QualType Ty = E->getTypeOfArgument();
  8257. if (Ty->isVectorType()) {
  8258. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  8259. // The vec_step built-in functions that take a 3-component
  8260. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  8261. if (n == 3)
  8262. n = 4;
  8263. return Success(n, E);
  8264. } else
  8265. return Success(1, E);
  8266. }
  8267. case UETT_SizeOf: {
  8268. QualType SrcTy = E->getTypeOfArgument();
  8269. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  8270. // the result is the size of the referenced type."
  8271. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  8272. SrcTy = Ref->getPointeeType();
  8273. CharUnits Sizeof;
  8274. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  8275. return false;
  8276. return Success(Sizeof, E);
  8277. }
  8278. case UETT_OpenMPRequiredSimdAlign:
  8279. assert(E->isArgumentType());
  8280. return Success(
  8281. Info.Ctx.toCharUnitsFromBits(
  8282. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  8283. .getQuantity(),
  8284. E);
  8285. }
  8286. llvm_unreachable("unknown expr/type trait");
  8287. }
  8288. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  8289. CharUnits Result;
  8290. unsigned n = OOE->getNumComponents();
  8291. if (n == 0)
  8292. return Error(OOE);
  8293. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  8294. for (unsigned i = 0; i != n; ++i) {
  8295. OffsetOfNode ON = OOE->getComponent(i);
  8296. switch (ON.getKind()) {
  8297. case OffsetOfNode::Array: {
  8298. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  8299. APSInt IdxResult;
  8300. if (!EvaluateInteger(Idx, IdxResult, Info))
  8301. return false;
  8302. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  8303. if (!AT)
  8304. return Error(OOE);
  8305. CurrentType = AT->getElementType();
  8306. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  8307. Result += IdxResult.getSExtValue() * ElementSize;
  8308. break;
  8309. }
  8310. case OffsetOfNode::Field: {
  8311. FieldDecl *MemberDecl = ON.getField();
  8312. const RecordType *RT = CurrentType->getAs<RecordType>();
  8313. if (!RT)
  8314. return Error(OOE);
  8315. RecordDecl *RD = RT->getDecl();
  8316. if (RD->isInvalidDecl()) return false;
  8317. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8318. unsigned i = MemberDecl->getFieldIndex();
  8319. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  8320. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  8321. CurrentType = MemberDecl->getType().getNonReferenceType();
  8322. break;
  8323. }
  8324. case OffsetOfNode::Identifier:
  8325. llvm_unreachable("dependent __builtin_offsetof");
  8326. case OffsetOfNode::Base: {
  8327. CXXBaseSpecifier *BaseSpec = ON.getBase();
  8328. if (BaseSpec->isVirtual())
  8329. return Error(OOE);
  8330. // Find the layout of the class whose base we are looking into.
  8331. const RecordType *RT = CurrentType->getAs<RecordType>();
  8332. if (!RT)
  8333. return Error(OOE);
  8334. RecordDecl *RD = RT->getDecl();
  8335. if (RD->isInvalidDecl()) return false;
  8336. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8337. // Find the base class itself.
  8338. CurrentType = BaseSpec->getType();
  8339. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  8340. if (!BaseRT)
  8341. return Error(OOE);
  8342. // Add the offset to the base.
  8343. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  8344. break;
  8345. }
  8346. }
  8347. }
  8348. return Success(Result, OOE);
  8349. }
  8350. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8351. switch (E->getOpcode()) {
  8352. default:
  8353. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  8354. // See C99 6.6p3.
  8355. return Error(E);
  8356. case UO_Extension:
  8357. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  8358. // If so, we could clear the diagnostic ID.
  8359. return Visit(E->getSubExpr());
  8360. case UO_Plus:
  8361. // The result is just the value.
  8362. return Visit(E->getSubExpr());
  8363. case UO_Minus: {
  8364. if (!Visit(E->getSubExpr()))
  8365. return false;
  8366. if (!Result.isInt()) return Error(E);
  8367. const APSInt &Value = Result.getInt();
  8368. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  8369. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  8370. E->getType()))
  8371. return false;
  8372. return Success(-Value, E);
  8373. }
  8374. case UO_Not: {
  8375. if (!Visit(E->getSubExpr()))
  8376. return false;
  8377. if (!Result.isInt()) return Error(E);
  8378. return Success(~Result.getInt(), E);
  8379. }
  8380. case UO_LNot: {
  8381. bool bres;
  8382. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8383. return false;
  8384. return Success(!bres, E);
  8385. }
  8386. }
  8387. }
  8388. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  8389. /// result type is integer.
  8390. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8391. const Expr *SubExpr = E->getSubExpr();
  8392. QualType DestType = E->getType();
  8393. QualType SrcType = SubExpr->getType();
  8394. switch (E->getCastKind()) {
  8395. case CK_BaseToDerived:
  8396. case CK_DerivedToBase:
  8397. case CK_UncheckedDerivedToBase:
  8398. case CK_Dynamic:
  8399. case CK_ToUnion:
  8400. case CK_ArrayToPointerDecay:
  8401. case CK_FunctionToPointerDecay:
  8402. case CK_NullToPointer:
  8403. case CK_NullToMemberPointer:
  8404. case CK_BaseToDerivedMemberPointer:
  8405. case CK_DerivedToBaseMemberPointer:
  8406. case CK_ReinterpretMemberPointer:
  8407. case CK_ConstructorConversion:
  8408. case CK_IntegralToPointer:
  8409. case CK_ToVoid:
  8410. case CK_VectorSplat:
  8411. case CK_IntegralToFloating:
  8412. case CK_FloatingCast:
  8413. case CK_CPointerToObjCPointerCast:
  8414. case CK_BlockPointerToObjCPointerCast:
  8415. case CK_AnyPointerToBlockPointerCast:
  8416. case CK_ObjCObjectLValueCast:
  8417. case CK_FloatingRealToComplex:
  8418. case CK_FloatingComplexToReal:
  8419. case CK_FloatingComplexCast:
  8420. case CK_FloatingComplexToIntegralComplex:
  8421. case CK_IntegralRealToComplex:
  8422. case CK_IntegralComplexCast:
  8423. case CK_IntegralComplexToFloatingComplex:
  8424. case CK_BuiltinFnToFnPtr:
  8425. case CK_ZeroToOCLOpaqueType:
  8426. case CK_NonAtomicToAtomic:
  8427. case CK_AddressSpaceConversion:
  8428. case CK_IntToOCLSampler:
  8429. case CK_FixedPointCast:
  8430. llvm_unreachable("invalid cast kind for integral value");
  8431. case CK_BitCast:
  8432. case CK_Dependent:
  8433. case CK_LValueBitCast:
  8434. case CK_ARCProduceObject:
  8435. case CK_ARCConsumeObject:
  8436. case CK_ARCReclaimReturnedObject:
  8437. case CK_ARCExtendBlockObject:
  8438. case CK_CopyAndAutoreleaseBlockObject:
  8439. return Error(E);
  8440. case CK_UserDefinedConversion:
  8441. case CK_LValueToRValue:
  8442. case CK_AtomicToNonAtomic:
  8443. case CK_NoOp:
  8444. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8445. case CK_MemberPointerToBoolean:
  8446. case CK_PointerToBoolean:
  8447. case CK_IntegralToBoolean:
  8448. case CK_FloatingToBoolean:
  8449. case CK_BooleanToSignedIntegral:
  8450. case CK_FloatingComplexToBoolean:
  8451. case CK_IntegralComplexToBoolean: {
  8452. bool BoolResult;
  8453. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  8454. return false;
  8455. uint64_t IntResult = BoolResult;
  8456. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  8457. IntResult = (uint64_t)-1;
  8458. return Success(IntResult, E);
  8459. }
  8460. case CK_FixedPointToBoolean: {
  8461. // Unsigned padding does not affect this.
  8462. APValue Val;
  8463. if (!Evaluate(Val, Info, SubExpr))
  8464. return false;
  8465. return Success(Val.getInt().getBoolValue(), E);
  8466. }
  8467. case CK_IntegralCast: {
  8468. if (!Visit(SubExpr))
  8469. return false;
  8470. if (!Result.isInt()) {
  8471. // Allow casts of address-of-label differences if they are no-ops
  8472. // or narrowing. (The narrowing case isn't actually guaranteed to
  8473. // be constant-evaluatable except in some narrow cases which are hard
  8474. // to detect here. We let it through on the assumption the user knows
  8475. // what they are doing.)
  8476. if (Result.isAddrLabelDiff())
  8477. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  8478. // Only allow casts of lvalues if they are lossless.
  8479. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  8480. }
  8481. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  8482. Result.getInt()), E);
  8483. }
  8484. case CK_PointerToIntegral: {
  8485. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  8486. LValue LV;
  8487. if (!EvaluatePointer(SubExpr, LV, Info))
  8488. return false;
  8489. if (LV.getLValueBase()) {
  8490. // Only allow based lvalue casts if they are lossless.
  8491. // FIXME: Allow a larger integer size than the pointer size, and allow
  8492. // narrowing back down to pointer width in subsequent integral casts.
  8493. // FIXME: Check integer type's active bits, not its type size.
  8494. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  8495. return Error(E);
  8496. LV.Designator.setInvalid();
  8497. LV.moveInto(Result);
  8498. return true;
  8499. }
  8500. uint64_t V;
  8501. if (LV.isNullPointer())
  8502. V = Info.Ctx.getTargetNullPointerValue(SrcType);
  8503. else
  8504. V = LV.getLValueOffset().getQuantity();
  8505. APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
  8506. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  8507. }
  8508. case CK_IntegralComplexToReal: {
  8509. ComplexValue C;
  8510. if (!EvaluateComplex(SubExpr, C, Info))
  8511. return false;
  8512. return Success(C.getComplexIntReal(), E);
  8513. }
  8514. case CK_FloatingToIntegral: {
  8515. APFloat F(0.0);
  8516. if (!EvaluateFloat(SubExpr, F, Info))
  8517. return false;
  8518. APSInt Value;
  8519. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  8520. return false;
  8521. return Success(Value, E);
  8522. }
  8523. }
  8524. llvm_unreachable("unknown cast resulting in integral value");
  8525. }
  8526. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8527. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8528. ComplexValue LV;
  8529. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8530. return false;
  8531. if (!LV.isComplexInt())
  8532. return Error(E);
  8533. return Success(LV.getComplexIntReal(), E);
  8534. }
  8535. return Visit(E->getSubExpr());
  8536. }
  8537. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8538. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  8539. ComplexValue LV;
  8540. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8541. return false;
  8542. if (!LV.isComplexInt())
  8543. return Error(E);
  8544. return Success(LV.getComplexIntImag(), E);
  8545. }
  8546. VisitIgnoredValue(E->getSubExpr());
  8547. return Success(0, E);
  8548. }
  8549. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  8550. return Success(E->getPackLength(), E);
  8551. }
  8552. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  8553. return Success(E->getValue(), E);
  8554. }
  8555. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8556. switch (E->getOpcode()) {
  8557. default:
  8558. // Invalid unary operators
  8559. return Error(E);
  8560. case UO_Plus:
  8561. // The result is just the value.
  8562. return Visit(E->getSubExpr());
  8563. case UO_Minus: {
  8564. if (!Visit(E->getSubExpr())) return false;
  8565. if (!Result.isInt()) return Error(E);
  8566. const APSInt &Value = Result.getInt();
  8567. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
  8568. SmallString<64> S;
  8569. FixedPointValueToString(S, Value,
  8570. Info.Ctx.getTypeInfo(E->getType()).Width);
  8571. Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
  8572. if (Info.noteUndefinedBehavior()) return false;
  8573. }
  8574. return Success(-Value, E);
  8575. }
  8576. case UO_LNot: {
  8577. bool bres;
  8578. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8579. return false;
  8580. return Success(!bres, E);
  8581. }
  8582. }
  8583. }
  8584. //===----------------------------------------------------------------------===//
  8585. // Float Evaluation
  8586. //===----------------------------------------------------------------------===//
  8587. namespace {
  8588. class FloatExprEvaluator
  8589. : public ExprEvaluatorBase<FloatExprEvaluator> {
  8590. APFloat &Result;
  8591. public:
  8592. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  8593. : ExprEvaluatorBaseTy(info), Result(result) {}
  8594. bool Success(const APValue &V, const Expr *e) {
  8595. Result = V.getFloat();
  8596. return true;
  8597. }
  8598. bool ZeroInitialization(const Expr *E) {
  8599. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  8600. return true;
  8601. }
  8602. bool VisitCallExpr(const CallExpr *E);
  8603. bool VisitUnaryOperator(const UnaryOperator *E);
  8604. bool VisitBinaryOperator(const BinaryOperator *E);
  8605. bool VisitFloatingLiteral(const FloatingLiteral *E);
  8606. bool VisitCastExpr(const CastExpr *E);
  8607. bool VisitUnaryReal(const UnaryOperator *E);
  8608. bool VisitUnaryImag(const UnaryOperator *E);
  8609. // FIXME: Missing: array subscript of vector, member of vector
  8610. };
  8611. } // end anonymous namespace
  8612. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  8613. assert(E->isRValue() && E->getType()->isRealFloatingType());
  8614. return FloatExprEvaluator(Info, Result).Visit(E);
  8615. }
  8616. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  8617. QualType ResultTy,
  8618. const Expr *Arg,
  8619. bool SNaN,
  8620. llvm::APFloat &Result) {
  8621. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  8622. if (!S) return false;
  8623. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  8624. llvm::APInt fill;
  8625. // Treat empty strings as if they were zero.
  8626. if (S->getString().empty())
  8627. fill = llvm::APInt(32, 0);
  8628. else if (S->getString().getAsInteger(0, fill))
  8629. return false;
  8630. if (Context.getTargetInfo().isNan2008()) {
  8631. if (SNaN)
  8632. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8633. else
  8634. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8635. } else {
  8636. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  8637. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  8638. // a different encoding to what became a standard in 2008, and for pre-
  8639. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  8640. // sNaN. This is now known as "legacy NaN" encoding.
  8641. if (SNaN)
  8642. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8643. else
  8644. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8645. }
  8646. return true;
  8647. }
  8648. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8649. switch (E->getBuiltinCallee()) {
  8650. default:
  8651. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8652. case Builtin::BI__builtin_huge_val:
  8653. case Builtin::BI__builtin_huge_valf:
  8654. case Builtin::BI__builtin_huge_vall:
  8655. case Builtin::BI__builtin_huge_valf128:
  8656. case Builtin::BI__builtin_inf:
  8657. case Builtin::BI__builtin_inff:
  8658. case Builtin::BI__builtin_infl:
  8659. case Builtin::BI__builtin_inff128: {
  8660. const llvm::fltSemantics &Sem =
  8661. Info.Ctx.getFloatTypeSemantics(E->getType());
  8662. Result = llvm::APFloat::getInf(Sem);
  8663. return true;
  8664. }
  8665. case Builtin::BI__builtin_nans:
  8666. case Builtin::BI__builtin_nansf:
  8667. case Builtin::BI__builtin_nansl:
  8668. case Builtin::BI__builtin_nansf128:
  8669. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8670. true, Result))
  8671. return Error(E);
  8672. return true;
  8673. case Builtin::BI__builtin_nan:
  8674. case Builtin::BI__builtin_nanf:
  8675. case Builtin::BI__builtin_nanl:
  8676. case Builtin::BI__builtin_nanf128:
  8677. // If this is __builtin_nan() turn this into a nan, otherwise we
  8678. // can't constant fold it.
  8679. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8680. false, Result))
  8681. return Error(E);
  8682. return true;
  8683. case Builtin::BI__builtin_fabs:
  8684. case Builtin::BI__builtin_fabsf:
  8685. case Builtin::BI__builtin_fabsl:
  8686. case Builtin::BI__builtin_fabsf128:
  8687. if (!EvaluateFloat(E->getArg(0), Result, Info))
  8688. return false;
  8689. if (Result.isNegative())
  8690. Result.changeSign();
  8691. return true;
  8692. // FIXME: Builtin::BI__builtin_powi
  8693. // FIXME: Builtin::BI__builtin_powif
  8694. // FIXME: Builtin::BI__builtin_powil
  8695. case Builtin::BI__builtin_copysign:
  8696. case Builtin::BI__builtin_copysignf:
  8697. case Builtin::BI__builtin_copysignl:
  8698. case Builtin::BI__builtin_copysignf128: {
  8699. APFloat RHS(0.);
  8700. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  8701. !EvaluateFloat(E->getArg(1), RHS, Info))
  8702. return false;
  8703. Result.copySign(RHS);
  8704. return true;
  8705. }
  8706. }
  8707. }
  8708. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8709. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8710. ComplexValue CV;
  8711. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8712. return false;
  8713. Result = CV.FloatReal;
  8714. return true;
  8715. }
  8716. return Visit(E->getSubExpr());
  8717. }
  8718. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8719. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8720. ComplexValue CV;
  8721. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8722. return false;
  8723. Result = CV.FloatImag;
  8724. return true;
  8725. }
  8726. VisitIgnoredValue(E->getSubExpr());
  8727. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  8728. Result = llvm::APFloat::getZero(Sem);
  8729. return true;
  8730. }
  8731. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8732. switch (E->getOpcode()) {
  8733. default: return Error(E);
  8734. case UO_Plus:
  8735. return EvaluateFloat(E->getSubExpr(), Result, Info);
  8736. case UO_Minus:
  8737. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  8738. return false;
  8739. Result.changeSign();
  8740. return true;
  8741. }
  8742. }
  8743. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8744. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8745. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8746. APFloat RHS(0.0);
  8747. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  8748. if (!LHSOK && !Info.noteFailure())
  8749. return false;
  8750. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  8751. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  8752. }
  8753. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  8754. Result = E->getValue();
  8755. return true;
  8756. }
  8757. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8758. const Expr* SubExpr = E->getSubExpr();
  8759. switch (E->getCastKind()) {
  8760. default:
  8761. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8762. case CK_IntegralToFloating: {
  8763. APSInt IntResult;
  8764. return EvaluateInteger(SubExpr, IntResult, Info) &&
  8765. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  8766. E->getType(), Result);
  8767. }
  8768. case CK_FloatingCast: {
  8769. if (!Visit(SubExpr))
  8770. return false;
  8771. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  8772. Result);
  8773. }
  8774. case CK_FloatingComplexToReal: {
  8775. ComplexValue V;
  8776. if (!EvaluateComplex(SubExpr, V, Info))
  8777. return false;
  8778. Result = V.getComplexFloatReal();
  8779. return true;
  8780. }
  8781. }
  8782. }
  8783. //===----------------------------------------------------------------------===//
  8784. // Complex Evaluation (for float and integer)
  8785. //===----------------------------------------------------------------------===//
  8786. namespace {
  8787. class ComplexExprEvaluator
  8788. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  8789. ComplexValue &Result;
  8790. public:
  8791. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  8792. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8793. bool Success(const APValue &V, const Expr *e) {
  8794. Result.setFrom(V);
  8795. return true;
  8796. }
  8797. bool ZeroInitialization(const Expr *E);
  8798. //===--------------------------------------------------------------------===//
  8799. // Visitor Methods
  8800. //===--------------------------------------------------------------------===//
  8801. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  8802. bool VisitCastExpr(const CastExpr *E);
  8803. bool VisitBinaryOperator(const BinaryOperator *E);
  8804. bool VisitUnaryOperator(const UnaryOperator *E);
  8805. bool VisitInitListExpr(const InitListExpr *E);
  8806. };
  8807. } // end anonymous namespace
  8808. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  8809. EvalInfo &Info) {
  8810. assert(E->isRValue() && E->getType()->isAnyComplexType());
  8811. return ComplexExprEvaluator(Info, Result).Visit(E);
  8812. }
  8813. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  8814. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  8815. if (ElemTy->isRealFloatingType()) {
  8816. Result.makeComplexFloat();
  8817. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  8818. Result.FloatReal = Zero;
  8819. Result.FloatImag = Zero;
  8820. } else {
  8821. Result.makeComplexInt();
  8822. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  8823. Result.IntReal = Zero;
  8824. Result.IntImag = Zero;
  8825. }
  8826. return true;
  8827. }
  8828. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  8829. const Expr* SubExpr = E->getSubExpr();
  8830. if (SubExpr->getType()->isRealFloatingType()) {
  8831. Result.makeComplexFloat();
  8832. APFloat &Imag = Result.FloatImag;
  8833. if (!EvaluateFloat(SubExpr, Imag, Info))
  8834. return false;
  8835. Result.FloatReal = APFloat(Imag.getSemantics());
  8836. return true;
  8837. } else {
  8838. assert(SubExpr->getType()->isIntegerType() &&
  8839. "Unexpected imaginary literal.");
  8840. Result.makeComplexInt();
  8841. APSInt &Imag = Result.IntImag;
  8842. if (!EvaluateInteger(SubExpr, Imag, Info))
  8843. return false;
  8844. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  8845. return true;
  8846. }
  8847. }
  8848. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8849. switch (E->getCastKind()) {
  8850. case CK_BitCast:
  8851. case CK_BaseToDerived:
  8852. case CK_DerivedToBase:
  8853. case CK_UncheckedDerivedToBase:
  8854. case CK_Dynamic:
  8855. case CK_ToUnion:
  8856. case CK_ArrayToPointerDecay:
  8857. case CK_FunctionToPointerDecay:
  8858. case CK_NullToPointer:
  8859. case CK_NullToMemberPointer:
  8860. case CK_BaseToDerivedMemberPointer:
  8861. case CK_DerivedToBaseMemberPointer:
  8862. case CK_MemberPointerToBoolean:
  8863. case CK_ReinterpretMemberPointer:
  8864. case CK_ConstructorConversion:
  8865. case CK_IntegralToPointer:
  8866. case CK_PointerToIntegral:
  8867. case CK_PointerToBoolean:
  8868. case CK_ToVoid:
  8869. case CK_VectorSplat:
  8870. case CK_IntegralCast:
  8871. case CK_BooleanToSignedIntegral:
  8872. case CK_IntegralToBoolean:
  8873. case CK_IntegralToFloating:
  8874. case CK_FloatingToIntegral:
  8875. case CK_FloatingToBoolean:
  8876. case CK_FloatingCast:
  8877. case CK_CPointerToObjCPointerCast:
  8878. case CK_BlockPointerToObjCPointerCast:
  8879. case CK_AnyPointerToBlockPointerCast:
  8880. case CK_ObjCObjectLValueCast:
  8881. case CK_FloatingComplexToReal:
  8882. case CK_FloatingComplexToBoolean:
  8883. case CK_IntegralComplexToReal:
  8884. case CK_IntegralComplexToBoolean:
  8885. case CK_ARCProduceObject:
  8886. case CK_ARCConsumeObject:
  8887. case CK_ARCReclaimReturnedObject:
  8888. case CK_ARCExtendBlockObject:
  8889. case CK_CopyAndAutoreleaseBlockObject:
  8890. case CK_BuiltinFnToFnPtr:
  8891. case CK_ZeroToOCLOpaqueType:
  8892. case CK_NonAtomicToAtomic:
  8893. case CK_AddressSpaceConversion:
  8894. case CK_IntToOCLSampler:
  8895. case CK_FixedPointCast:
  8896. case CK_FixedPointToBoolean:
  8897. llvm_unreachable("invalid cast kind for complex value");
  8898. case CK_LValueToRValue:
  8899. case CK_AtomicToNonAtomic:
  8900. case CK_NoOp:
  8901. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8902. case CK_Dependent:
  8903. case CK_LValueBitCast:
  8904. case CK_UserDefinedConversion:
  8905. return Error(E);
  8906. case CK_FloatingRealToComplex: {
  8907. APFloat &Real = Result.FloatReal;
  8908. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  8909. return false;
  8910. Result.makeComplexFloat();
  8911. Result.FloatImag = APFloat(Real.getSemantics());
  8912. return true;
  8913. }
  8914. case CK_FloatingComplexCast: {
  8915. if (!Visit(E->getSubExpr()))
  8916. return false;
  8917. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8918. QualType From
  8919. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8920. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  8921. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  8922. }
  8923. case CK_FloatingComplexToIntegralComplex: {
  8924. if (!Visit(E->getSubExpr()))
  8925. return false;
  8926. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8927. QualType From
  8928. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8929. Result.makeComplexInt();
  8930. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  8931. To, Result.IntReal) &&
  8932. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  8933. To, Result.IntImag);
  8934. }
  8935. case CK_IntegralRealToComplex: {
  8936. APSInt &Real = Result.IntReal;
  8937. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  8938. return false;
  8939. Result.makeComplexInt();
  8940. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  8941. return true;
  8942. }
  8943. case CK_IntegralComplexCast: {
  8944. if (!Visit(E->getSubExpr()))
  8945. return false;
  8946. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8947. QualType From
  8948. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8949. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  8950. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  8951. return true;
  8952. }
  8953. case CK_IntegralComplexToFloatingComplex: {
  8954. if (!Visit(E->getSubExpr()))
  8955. return false;
  8956. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  8957. QualType From
  8958. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  8959. Result.makeComplexFloat();
  8960. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  8961. To, Result.FloatReal) &&
  8962. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  8963. To, Result.FloatImag);
  8964. }
  8965. }
  8966. llvm_unreachable("unknown cast resulting in complex value");
  8967. }
  8968. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8969. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8970. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8971. // Track whether the LHS or RHS is real at the type system level. When this is
  8972. // the case we can simplify our evaluation strategy.
  8973. bool LHSReal = false, RHSReal = false;
  8974. bool LHSOK;
  8975. if (E->getLHS()->getType()->isRealFloatingType()) {
  8976. LHSReal = true;
  8977. APFloat &Real = Result.FloatReal;
  8978. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  8979. if (LHSOK) {
  8980. Result.makeComplexFloat();
  8981. Result.FloatImag = APFloat(Real.getSemantics());
  8982. }
  8983. } else {
  8984. LHSOK = Visit(E->getLHS());
  8985. }
  8986. if (!LHSOK && !Info.noteFailure())
  8987. return false;
  8988. ComplexValue RHS;
  8989. if (E->getRHS()->getType()->isRealFloatingType()) {
  8990. RHSReal = true;
  8991. APFloat &Real = RHS.FloatReal;
  8992. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  8993. return false;
  8994. RHS.makeComplexFloat();
  8995. RHS.FloatImag = APFloat(Real.getSemantics());
  8996. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  8997. return false;
  8998. assert(!(LHSReal && RHSReal) &&
  8999. "Cannot have both operands of a complex operation be real.");
  9000. switch (E->getOpcode()) {
  9001. default: return Error(E);
  9002. case BO_Add:
  9003. if (Result.isComplexFloat()) {
  9004. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  9005. APFloat::rmNearestTiesToEven);
  9006. if (LHSReal)
  9007. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9008. else if (!RHSReal)
  9009. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  9010. APFloat::rmNearestTiesToEven);
  9011. } else {
  9012. Result.getComplexIntReal() += RHS.getComplexIntReal();
  9013. Result.getComplexIntImag() += RHS.getComplexIntImag();
  9014. }
  9015. break;
  9016. case BO_Sub:
  9017. if (Result.isComplexFloat()) {
  9018. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  9019. APFloat::rmNearestTiesToEven);
  9020. if (LHSReal) {
  9021. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9022. Result.getComplexFloatImag().changeSign();
  9023. } else if (!RHSReal) {
  9024. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  9025. APFloat::rmNearestTiesToEven);
  9026. }
  9027. } else {
  9028. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  9029. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  9030. }
  9031. break;
  9032. case BO_Mul:
  9033. if (Result.isComplexFloat()) {
  9034. // This is an implementation of complex multiplication according to the
  9035. // constraints laid out in C11 Annex G. The implemention uses the
  9036. // following naming scheme:
  9037. // (a + ib) * (c + id)
  9038. ComplexValue LHS = Result;
  9039. APFloat &A = LHS.getComplexFloatReal();
  9040. APFloat &B = LHS.getComplexFloatImag();
  9041. APFloat &C = RHS.getComplexFloatReal();
  9042. APFloat &D = RHS.getComplexFloatImag();
  9043. APFloat &ResR = Result.getComplexFloatReal();
  9044. APFloat &ResI = Result.getComplexFloatImag();
  9045. if (LHSReal) {
  9046. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  9047. ResR = A * C;
  9048. ResI = A * D;
  9049. } else if (RHSReal) {
  9050. ResR = C * A;
  9051. ResI = C * B;
  9052. } else {
  9053. // In the fully general case, we need to handle NaNs and infinities
  9054. // robustly.
  9055. APFloat AC = A * C;
  9056. APFloat BD = B * D;
  9057. APFloat AD = A * D;
  9058. APFloat BC = B * C;
  9059. ResR = AC - BD;
  9060. ResI = AD + BC;
  9061. if (ResR.isNaN() && ResI.isNaN()) {
  9062. bool Recalc = false;
  9063. if (A.isInfinity() || B.isInfinity()) {
  9064. A = APFloat::copySign(
  9065. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9066. B = APFloat::copySign(
  9067. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9068. if (C.isNaN())
  9069. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9070. if (D.isNaN())
  9071. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9072. Recalc = true;
  9073. }
  9074. if (C.isInfinity() || D.isInfinity()) {
  9075. C = APFloat::copySign(
  9076. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9077. D = APFloat::copySign(
  9078. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9079. if (A.isNaN())
  9080. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9081. if (B.isNaN())
  9082. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9083. Recalc = true;
  9084. }
  9085. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  9086. AD.isInfinity() || BC.isInfinity())) {
  9087. if (A.isNaN())
  9088. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9089. if (B.isNaN())
  9090. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9091. if (C.isNaN())
  9092. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9093. if (D.isNaN())
  9094. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9095. Recalc = true;
  9096. }
  9097. if (Recalc) {
  9098. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  9099. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  9100. }
  9101. }
  9102. }
  9103. } else {
  9104. ComplexValue LHS = Result;
  9105. Result.getComplexIntReal() =
  9106. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  9107. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  9108. Result.getComplexIntImag() =
  9109. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  9110. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  9111. }
  9112. break;
  9113. case BO_Div:
  9114. if (Result.isComplexFloat()) {
  9115. // This is an implementation of complex division according to the
  9116. // constraints laid out in C11 Annex G. The implemention uses the
  9117. // following naming scheme:
  9118. // (a + ib) / (c + id)
  9119. ComplexValue LHS = Result;
  9120. APFloat &A = LHS.getComplexFloatReal();
  9121. APFloat &B = LHS.getComplexFloatImag();
  9122. APFloat &C = RHS.getComplexFloatReal();
  9123. APFloat &D = RHS.getComplexFloatImag();
  9124. APFloat &ResR = Result.getComplexFloatReal();
  9125. APFloat &ResI = Result.getComplexFloatImag();
  9126. if (RHSReal) {
  9127. ResR = A / C;
  9128. ResI = B / C;
  9129. } else {
  9130. if (LHSReal) {
  9131. // No real optimizations we can do here, stub out with zero.
  9132. B = APFloat::getZero(A.getSemantics());
  9133. }
  9134. int DenomLogB = 0;
  9135. APFloat MaxCD = maxnum(abs(C), abs(D));
  9136. if (MaxCD.isFinite()) {
  9137. DenomLogB = ilogb(MaxCD);
  9138. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  9139. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  9140. }
  9141. APFloat Denom = C * C + D * D;
  9142. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  9143. APFloat::rmNearestTiesToEven);
  9144. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  9145. APFloat::rmNearestTiesToEven);
  9146. if (ResR.isNaN() && ResI.isNaN()) {
  9147. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  9148. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  9149. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  9150. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  9151. D.isFinite()) {
  9152. A = APFloat::copySign(
  9153. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9154. B = APFloat::copySign(
  9155. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9156. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  9157. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  9158. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  9159. C = APFloat::copySign(
  9160. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9161. D = APFloat::copySign(
  9162. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9163. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  9164. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  9165. }
  9166. }
  9167. }
  9168. } else {
  9169. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  9170. return Error(E, diag::note_expr_divide_by_zero);
  9171. ComplexValue LHS = Result;
  9172. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9173. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  9174. Result.getComplexIntReal() =
  9175. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9176. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  9177. Result.getComplexIntImag() =
  9178. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  9179. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  9180. }
  9181. break;
  9182. }
  9183. return true;
  9184. }
  9185. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9186. // Get the operand value into 'Result'.
  9187. if (!Visit(E->getSubExpr()))
  9188. return false;
  9189. switch (E->getOpcode()) {
  9190. default:
  9191. return Error(E);
  9192. case UO_Extension:
  9193. return true;
  9194. case UO_Plus:
  9195. // The result is always just the subexpr.
  9196. return true;
  9197. case UO_Minus:
  9198. if (Result.isComplexFloat()) {
  9199. Result.getComplexFloatReal().changeSign();
  9200. Result.getComplexFloatImag().changeSign();
  9201. }
  9202. else {
  9203. Result.getComplexIntReal() = -Result.getComplexIntReal();
  9204. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9205. }
  9206. return true;
  9207. case UO_Not:
  9208. if (Result.isComplexFloat())
  9209. Result.getComplexFloatImag().changeSign();
  9210. else
  9211. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9212. return true;
  9213. }
  9214. }
  9215. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9216. if (E->getNumInits() == 2) {
  9217. if (E->getType()->isComplexType()) {
  9218. Result.makeComplexFloat();
  9219. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  9220. return false;
  9221. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  9222. return false;
  9223. } else {
  9224. Result.makeComplexInt();
  9225. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  9226. return false;
  9227. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  9228. return false;
  9229. }
  9230. return true;
  9231. }
  9232. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  9233. }
  9234. //===----------------------------------------------------------------------===//
  9235. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  9236. // implicit conversion.
  9237. //===----------------------------------------------------------------------===//
  9238. namespace {
  9239. class AtomicExprEvaluator :
  9240. public ExprEvaluatorBase<AtomicExprEvaluator> {
  9241. const LValue *This;
  9242. APValue &Result;
  9243. public:
  9244. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  9245. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9246. bool Success(const APValue &V, const Expr *E) {
  9247. Result = V;
  9248. return true;
  9249. }
  9250. bool ZeroInitialization(const Expr *E) {
  9251. ImplicitValueInitExpr VIE(
  9252. E->getType()->castAs<AtomicType>()->getValueType());
  9253. // For atomic-qualified class (and array) types in C++, initialize the
  9254. // _Atomic-wrapped subobject directly, in-place.
  9255. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  9256. : Evaluate(Result, Info, &VIE);
  9257. }
  9258. bool VisitCastExpr(const CastExpr *E) {
  9259. switch (E->getCastKind()) {
  9260. default:
  9261. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9262. case CK_NonAtomicToAtomic:
  9263. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  9264. : Evaluate(Result, Info, E->getSubExpr());
  9265. }
  9266. }
  9267. };
  9268. } // end anonymous namespace
  9269. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  9270. EvalInfo &Info) {
  9271. assert(E->isRValue() && E->getType()->isAtomicType());
  9272. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  9273. }
  9274. //===----------------------------------------------------------------------===//
  9275. // Void expression evaluation, primarily for a cast to void on the LHS of a
  9276. // comma operator
  9277. //===----------------------------------------------------------------------===//
  9278. namespace {
  9279. class VoidExprEvaluator
  9280. : public ExprEvaluatorBase<VoidExprEvaluator> {
  9281. public:
  9282. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  9283. bool Success(const APValue &V, const Expr *e) { return true; }
  9284. bool ZeroInitialization(const Expr *E) { return true; }
  9285. bool VisitCastExpr(const CastExpr *E) {
  9286. switch (E->getCastKind()) {
  9287. default:
  9288. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9289. case CK_ToVoid:
  9290. VisitIgnoredValue(E->getSubExpr());
  9291. return true;
  9292. }
  9293. }
  9294. bool VisitCallExpr(const CallExpr *E) {
  9295. switch (E->getBuiltinCallee()) {
  9296. default:
  9297. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9298. case Builtin::BI__assume:
  9299. case Builtin::BI__builtin_assume:
  9300. // The argument is not evaluated!
  9301. return true;
  9302. }
  9303. }
  9304. };
  9305. } // end anonymous namespace
  9306. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  9307. assert(E->isRValue() && E->getType()->isVoidType());
  9308. return VoidExprEvaluator(Info).Visit(E);
  9309. }
  9310. //===----------------------------------------------------------------------===//
  9311. // Top level Expr::EvaluateAsRValue method.
  9312. //===----------------------------------------------------------------------===//
  9313. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  9314. // In C, function designators are not lvalues, but we evaluate them as if they
  9315. // are.
  9316. QualType T = E->getType();
  9317. if (E->isGLValue() || T->isFunctionType()) {
  9318. LValue LV;
  9319. if (!EvaluateLValue(E, LV, Info))
  9320. return false;
  9321. LV.moveInto(Result);
  9322. } else if (T->isVectorType()) {
  9323. if (!EvaluateVector(E, Result, Info))
  9324. return false;
  9325. } else if (T->isIntegralOrEnumerationType()) {
  9326. if (!IntExprEvaluator(Info, Result).Visit(E))
  9327. return false;
  9328. } else if (T->hasPointerRepresentation()) {
  9329. LValue LV;
  9330. if (!EvaluatePointer(E, LV, Info))
  9331. return false;
  9332. LV.moveInto(Result);
  9333. } else if (T->isRealFloatingType()) {
  9334. llvm::APFloat F(0.0);
  9335. if (!EvaluateFloat(E, F, Info))
  9336. return false;
  9337. Result = APValue(F);
  9338. } else if (T->isAnyComplexType()) {
  9339. ComplexValue C;
  9340. if (!EvaluateComplex(E, C, Info))
  9341. return false;
  9342. C.moveInto(Result);
  9343. } else if (T->isFixedPointType()) {
  9344. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  9345. } else if (T->isMemberPointerType()) {
  9346. MemberPtr P;
  9347. if (!EvaluateMemberPointer(E, P, Info))
  9348. return false;
  9349. P.moveInto(Result);
  9350. return true;
  9351. } else if (T->isArrayType()) {
  9352. LValue LV;
  9353. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9354. if (!EvaluateArray(E, LV, Value, Info))
  9355. return false;
  9356. Result = Value;
  9357. } else if (T->isRecordType()) {
  9358. LValue LV;
  9359. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9360. if (!EvaluateRecord(E, LV, Value, Info))
  9361. return false;
  9362. Result = Value;
  9363. } else if (T->isVoidType()) {
  9364. if (!Info.getLangOpts().CPlusPlus11)
  9365. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  9366. << E->getType();
  9367. if (!EvaluateVoid(E, Info))
  9368. return false;
  9369. } else if (T->isAtomicType()) {
  9370. QualType Unqual = T.getAtomicUnqualifiedType();
  9371. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  9372. LValue LV;
  9373. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9374. if (!EvaluateAtomic(E, &LV, Value, Info))
  9375. return false;
  9376. } else {
  9377. if (!EvaluateAtomic(E, nullptr, Result, Info))
  9378. return false;
  9379. }
  9380. } else if (Info.getLangOpts().CPlusPlus11) {
  9381. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  9382. return false;
  9383. } else {
  9384. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9385. return false;
  9386. }
  9387. return true;
  9388. }
  9389. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  9390. /// cases, the in-place evaluation is essential, since later initializers for
  9391. /// an object can indirectly refer to subobjects which were initialized earlier.
  9392. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  9393. const Expr *E, bool AllowNonLiteralTypes) {
  9394. assert(!E->isValueDependent());
  9395. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  9396. return false;
  9397. if (E->isRValue()) {
  9398. // Evaluate arrays and record types in-place, so that later initializers can
  9399. // refer to earlier-initialized members of the object.
  9400. QualType T = E->getType();
  9401. if (T->isArrayType())
  9402. return EvaluateArray(E, This, Result, Info);
  9403. else if (T->isRecordType())
  9404. return EvaluateRecord(E, This, Result, Info);
  9405. else if (T->isAtomicType()) {
  9406. QualType Unqual = T.getAtomicUnqualifiedType();
  9407. if (Unqual->isArrayType() || Unqual->isRecordType())
  9408. return EvaluateAtomic(E, &This, Result, Info);
  9409. }
  9410. }
  9411. // For any other type, in-place evaluation is unimportant.
  9412. return Evaluate(Result, Info, E);
  9413. }
  9414. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  9415. /// lvalue-to-rvalue cast if it is an lvalue.
  9416. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  9417. if (E->getType().isNull())
  9418. return false;
  9419. if (!CheckLiteralType(Info, E))
  9420. return false;
  9421. if (!::Evaluate(Result, Info, E))
  9422. return false;
  9423. if (E->isGLValue()) {
  9424. LValue LV;
  9425. LV.setFrom(Info.Ctx, Result);
  9426. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9427. return false;
  9428. }
  9429. // Check this core constant expression is a constant expression.
  9430. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9431. }
  9432. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  9433. const ASTContext &Ctx, bool &IsConst) {
  9434. // Fast-path evaluations of integer literals, since we sometimes see files
  9435. // containing vast quantities of these.
  9436. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  9437. Result.Val = APValue(APSInt(L->getValue(),
  9438. L->getType()->isUnsignedIntegerType()));
  9439. IsConst = true;
  9440. return true;
  9441. }
  9442. // This case should be rare, but we need to check it before we check on
  9443. // the type below.
  9444. if (Exp->getType().isNull()) {
  9445. IsConst = false;
  9446. return true;
  9447. }
  9448. // FIXME: Evaluating values of large array and record types can cause
  9449. // performance problems. Only do so in C++11 for now.
  9450. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  9451. Exp->getType()->isRecordType()) &&
  9452. !Ctx.getLangOpts().CPlusPlus11) {
  9453. IsConst = false;
  9454. return true;
  9455. }
  9456. return false;
  9457. }
  9458. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  9459. /// any crazy technique (that has nothing to do with language standards) that
  9460. /// we want to. If this function returns true, it returns the folded constant
  9461. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  9462. /// will be applied to the result.
  9463. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  9464. bool IsConst;
  9465. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  9466. return IsConst;
  9467. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  9468. return ::EvaluateAsRValue(Info, this, Result.Val);
  9469. }
  9470. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  9471. const ASTContext &Ctx) const {
  9472. EvalResult Scratch;
  9473. return EvaluateAsRValue(Scratch, Ctx) &&
  9474. HandleConversionToBool(Scratch.Val, Result);
  9475. }
  9476. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  9477. Expr::SideEffectsKind SEK) {
  9478. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  9479. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  9480. }
  9481. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  9482. SideEffectsKind AllowSideEffects) const {
  9483. if (!getType()->isIntegralOrEnumerationType())
  9484. return false;
  9485. EvalResult ExprResult;
  9486. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  9487. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9488. return false;
  9489. Result = ExprResult.Val.getInt();
  9490. return true;
  9491. }
  9492. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  9493. SideEffectsKind AllowSideEffects) const {
  9494. if (!getType()->isRealFloatingType())
  9495. return false;
  9496. EvalResult ExprResult;
  9497. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  9498. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9499. return false;
  9500. Result = ExprResult.Val.getFloat();
  9501. return true;
  9502. }
  9503. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  9504. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  9505. LValue LV;
  9506. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  9507. !CheckLValueConstantExpression(Info, getExprLoc(),
  9508. Ctx.getLValueReferenceType(getType()), LV,
  9509. Expr::EvaluateForCodeGen))
  9510. return false;
  9511. LV.moveInto(Result.Val);
  9512. return true;
  9513. }
  9514. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  9515. const ASTContext &Ctx) const {
  9516. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  9517. EvalInfo Info(Ctx, Result, EM);
  9518. if (!::Evaluate(Result.Val, Info, this))
  9519. return false;
  9520. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  9521. Usage);
  9522. }
  9523. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  9524. const VarDecl *VD,
  9525. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  9526. // FIXME: Evaluating initializers for large array and record types can cause
  9527. // performance problems. Only do so in C++11 for now.
  9528. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  9529. !Ctx.getLangOpts().CPlusPlus11)
  9530. return false;
  9531. Expr::EvalStatus EStatus;
  9532. EStatus.Diag = &Notes;
  9533. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  9534. ? EvalInfo::EM_ConstantExpression
  9535. : EvalInfo::EM_ConstantFold);
  9536. InitInfo.setEvaluatingDecl(VD, Value);
  9537. LValue LVal;
  9538. LVal.set(VD);
  9539. // C++11 [basic.start.init]p2:
  9540. // Variables with static storage duration or thread storage duration shall be
  9541. // zero-initialized before any other initialization takes place.
  9542. // This behavior is not present in C.
  9543. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  9544. !VD->getType()->isReferenceType()) {
  9545. ImplicitValueInitExpr VIE(VD->getType());
  9546. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  9547. /*AllowNonLiteralTypes=*/true))
  9548. return false;
  9549. }
  9550. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  9551. /*AllowNonLiteralTypes=*/true) ||
  9552. EStatus.HasSideEffects)
  9553. return false;
  9554. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  9555. Value);
  9556. }
  9557. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  9558. /// constant folded, but discard the result.
  9559. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  9560. EvalResult Result;
  9561. return EvaluateAsRValue(Result, Ctx) &&
  9562. !hasUnacceptableSideEffect(Result, SEK);
  9563. }
  9564. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  9565. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9566. EvalResult EvalResult;
  9567. EvalResult.Diag = Diag;
  9568. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  9569. (void)Result;
  9570. assert(Result && "Could not evaluate expression");
  9571. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9572. return EvalResult.Val.getInt();
  9573. }
  9574. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  9575. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9576. EvalResult EvalResult;
  9577. EvalResult.Diag = Diag;
  9578. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9579. bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
  9580. (void)Result;
  9581. assert(Result && "Could not evaluate expression");
  9582. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9583. return EvalResult.Val.getInt();
  9584. }
  9585. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  9586. bool IsConst;
  9587. EvalResult EvalResult;
  9588. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  9589. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9590. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  9591. }
  9592. }
  9593. bool Expr::EvalResult::isGlobalLValue() const {
  9594. assert(Val.isLValue());
  9595. return IsGlobalLValue(Val.getLValueBase());
  9596. }
  9597. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  9598. /// an integer constant expression.
  9599. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  9600. /// comma, etc
  9601. // CheckICE - This function does the fundamental ICE checking: the returned
  9602. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  9603. // and a (possibly null) SourceLocation indicating the location of the problem.
  9604. //
  9605. // Note that to reduce code duplication, this helper does no evaluation
  9606. // itself; the caller checks whether the expression is evaluatable, and
  9607. // in the rare cases where CheckICE actually cares about the evaluated
  9608. // value, it calls into Evaluate.
  9609. namespace {
  9610. enum ICEKind {
  9611. /// This expression is an ICE.
  9612. IK_ICE,
  9613. /// This expression is not an ICE, but if it isn't evaluated, it's
  9614. /// a legal subexpression for an ICE. This return value is used to handle
  9615. /// the comma operator in C99 mode, and non-constant subexpressions.
  9616. IK_ICEIfUnevaluated,
  9617. /// This expression is not an ICE, and is not a legal subexpression for one.
  9618. IK_NotICE
  9619. };
  9620. struct ICEDiag {
  9621. ICEKind Kind;
  9622. SourceLocation Loc;
  9623. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  9624. };
  9625. }
  9626. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  9627. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  9628. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  9629. Expr::EvalResult EVResult;
  9630. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  9631. !EVResult.Val.isInt())
  9632. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9633. return NoDiag();
  9634. }
  9635. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  9636. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  9637. if (!E->getType()->isIntegralOrEnumerationType())
  9638. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9639. switch (E->getStmtClass()) {
  9640. #define ABSTRACT_STMT(Node)
  9641. #define STMT(Node, Base) case Expr::Node##Class:
  9642. #define EXPR(Node, Base)
  9643. #include "clang/AST/StmtNodes.inc"
  9644. case Expr::PredefinedExprClass:
  9645. case Expr::FloatingLiteralClass:
  9646. case Expr::ImaginaryLiteralClass:
  9647. case Expr::StringLiteralClass:
  9648. case Expr::ArraySubscriptExprClass:
  9649. case Expr::OMPArraySectionExprClass:
  9650. case Expr::MemberExprClass:
  9651. case Expr::CompoundAssignOperatorClass:
  9652. case Expr::CompoundLiteralExprClass:
  9653. case Expr::ExtVectorElementExprClass:
  9654. case Expr::DesignatedInitExprClass:
  9655. case Expr::ArrayInitLoopExprClass:
  9656. case Expr::ArrayInitIndexExprClass:
  9657. case Expr::NoInitExprClass:
  9658. case Expr::DesignatedInitUpdateExprClass:
  9659. case Expr::ImplicitValueInitExprClass:
  9660. case Expr::ParenListExprClass:
  9661. case Expr::VAArgExprClass:
  9662. case Expr::AddrLabelExprClass:
  9663. case Expr::StmtExprClass:
  9664. case Expr::CXXMemberCallExprClass:
  9665. case Expr::CUDAKernelCallExprClass:
  9666. case Expr::CXXDynamicCastExprClass:
  9667. case Expr::CXXTypeidExprClass:
  9668. case Expr::CXXUuidofExprClass:
  9669. case Expr::MSPropertyRefExprClass:
  9670. case Expr::MSPropertySubscriptExprClass:
  9671. case Expr::CXXNullPtrLiteralExprClass:
  9672. case Expr::UserDefinedLiteralClass:
  9673. case Expr::CXXThisExprClass:
  9674. case Expr::CXXThrowExprClass:
  9675. case Expr::CXXNewExprClass:
  9676. case Expr::CXXDeleteExprClass:
  9677. case Expr::CXXPseudoDestructorExprClass:
  9678. case Expr::UnresolvedLookupExprClass:
  9679. case Expr::TypoExprClass:
  9680. case Expr::DependentScopeDeclRefExprClass:
  9681. case Expr::CXXConstructExprClass:
  9682. case Expr::CXXInheritedCtorInitExprClass:
  9683. case Expr::CXXStdInitializerListExprClass:
  9684. case Expr::CXXBindTemporaryExprClass:
  9685. case Expr::ExprWithCleanupsClass:
  9686. case Expr::CXXTemporaryObjectExprClass:
  9687. case Expr::CXXUnresolvedConstructExprClass:
  9688. case Expr::CXXDependentScopeMemberExprClass:
  9689. case Expr::UnresolvedMemberExprClass:
  9690. case Expr::ObjCStringLiteralClass:
  9691. case Expr::ObjCBoxedExprClass:
  9692. case Expr::ObjCArrayLiteralClass:
  9693. case Expr::ObjCDictionaryLiteralClass:
  9694. case Expr::ObjCEncodeExprClass:
  9695. case Expr::ObjCMessageExprClass:
  9696. case Expr::ObjCSelectorExprClass:
  9697. case Expr::ObjCProtocolExprClass:
  9698. case Expr::ObjCIvarRefExprClass:
  9699. case Expr::ObjCPropertyRefExprClass:
  9700. case Expr::ObjCSubscriptRefExprClass:
  9701. case Expr::ObjCIsaExprClass:
  9702. case Expr::ObjCAvailabilityCheckExprClass:
  9703. case Expr::ShuffleVectorExprClass:
  9704. case Expr::ConvertVectorExprClass:
  9705. case Expr::BlockExprClass:
  9706. case Expr::NoStmtClass:
  9707. case Expr::OpaqueValueExprClass:
  9708. case Expr::PackExpansionExprClass:
  9709. case Expr::SubstNonTypeTemplateParmPackExprClass:
  9710. case Expr::FunctionParmPackExprClass:
  9711. case Expr::AsTypeExprClass:
  9712. case Expr::ObjCIndirectCopyRestoreExprClass:
  9713. case Expr::MaterializeTemporaryExprClass:
  9714. case Expr::PseudoObjectExprClass:
  9715. case Expr::AtomicExprClass:
  9716. case Expr::LambdaExprClass:
  9717. case Expr::CXXFoldExprClass:
  9718. case Expr::CoawaitExprClass:
  9719. case Expr::DependentCoawaitExprClass:
  9720. case Expr::CoyieldExprClass:
  9721. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9722. case Expr::InitListExprClass: {
  9723. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  9724. // form "T x = { a };" is equivalent to "T x = a;".
  9725. // Unless we're initializing a reference, T is a scalar as it is known to be
  9726. // of integral or enumeration type.
  9727. if (E->isRValue())
  9728. if (cast<InitListExpr>(E)->getNumInits() == 1)
  9729. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  9730. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9731. }
  9732. case Expr::SizeOfPackExprClass:
  9733. case Expr::GNUNullExprClass:
  9734. // GCC considers the GNU __null value to be an integral constant expression.
  9735. return NoDiag();
  9736. case Expr::SubstNonTypeTemplateParmExprClass:
  9737. return
  9738. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  9739. case Expr::ConstantExprClass:
  9740. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  9741. case Expr::ParenExprClass:
  9742. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  9743. case Expr::GenericSelectionExprClass:
  9744. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  9745. case Expr::IntegerLiteralClass:
  9746. case Expr::FixedPointLiteralClass:
  9747. case Expr::CharacterLiteralClass:
  9748. case Expr::ObjCBoolLiteralExprClass:
  9749. case Expr::CXXBoolLiteralExprClass:
  9750. case Expr::CXXScalarValueInitExprClass:
  9751. case Expr::TypeTraitExprClass:
  9752. case Expr::ArrayTypeTraitExprClass:
  9753. case Expr::ExpressionTraitExprClass:
  9754. case Expr::CXXNoexceptExprClass:
  9755. return NoDiag();
  9756. case Expr::CallExprClass:
  9757. case Expr::CXXOperatorCallExprClass: {
  9758. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  9759. // constant expressions, but they can never be ICEs because an ICE cannot
  9760. // contain an operand of (pointer to) function type.
  9761. const CallExpr *CE = cast<CallExpr>(E);
  9762. if (CE->getBuiltinCallee())
  9763. return CheckEvalInICE(E, Ctx);
  9764. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9765. }
  9766. case Expr::DeclRefExprClass: {
  9767. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  9768. return NoDiag();
  9769. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  9770. if (Ctx.getLangOpts().CPlusPlus &&
  9771. D && IsConstNonVolatile(D->getType())) {
  9772. // Parameter variables are never constants. Without this check,
  9773. // getAnyInitializer() can find a default argument, which leads
  9774. // to chaos.
  9775. if (isa<ParmVarDecl>(D))
  9776. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9777. // C++ 7.1.5.1p2
  9778. // A variable of non-volatile const-qualified integral or enumeration
  9779. // type initialized by an ICE can be used in ICEs.
  9780. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  9781. if (!Dcl->getType()->isIntegralOrEnumerationType())
  9782. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9783. const VarDecl *VD;
  9784. // Look for a declaration of this variable that has an initializer, and
  9785. // check whether it is an ICE.
  9786. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  9787. return NoDiag();
  9788. else
  9789. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9790. }
  9791. }
  9792. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9793. }
  9794. case Expr::UnaryOperatorClass: {
  9795. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  9796. switch (Exp->getOpcode()) {
  9797. case UO_PostInc:
  9798. case UO_PostDec:
  9799. case UO_PreInc:
  9800. case UO_PreDec:
  9801. case UO_AddrOf:
  9802. case UO_Deref:
  9803. case UO_Coawait:
  9804. // C99 6.6/3 allows increment and decrement within unevaluated
  9805. // subexpressions of constant expressions, but they can never be ICEs
  9806. // because an ICE cannot contain an lvalue operand.
  9807. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9808. case UO_Extension:
  9809. case UO_LNot:
  9810. case UO_Plus:
  9811. case UO_Minus:
  9812. case UO_Not:
  9813. case UO_Real:
  9814. case UO_Imag:
  9815. return CheckICE(Exp->getSubExpr(), Ctx);
  9816. }
  9817. llvm_unreachable("invalid unary operator class");
  9818. }
  9819. case Expr::OffsetOfExprClass: {
  9820. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  9821. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  9822. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  9823. // compliance: we should warn earlier for offsetof expressions with
  9824. // array subscripts that aren't ICEs, and if the array subscripts
  9825. // are ICEs, the value of the offsetof must be an integer constant.
  9826. return CheckEvalInICE(E, Ctx);
  9827. }
  9828. case Expr::UnaryExprOrTypeTraitExprClass: {
  9829. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  9830. if ((Exp->getKind() == UETT_SizeOf) &&
  9831. Exp->getTypeOfArgument()->isVariableArrayType())
  9832. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9833. return NoDiag();
  9834. }
  9835. case Expr::BinaryOperatorClass: {
  9836. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  9837. switch (Exp->getOpcode()) {
  9838. case BO_PtrMemD:
  9839. case BO_PtrMemI:
  9840. case BO_Assign:
  9841. case BO_MulAssign:
  9842. case BO_DivAssign:
  9843. case BO_RemAssign:
  9844. case BO_AddAssign:
  9845. case BO_SubAssign:
  9846. case BO_ShlAssign:
  9847. case BO_ShrAssign:
  9848. case BO_AndAssign:
  9849. case BO_XorAssign:
  9850. case BO_OrAssign:
  9851. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  9852. // constant expressions, but they can never be ICEs because an ICE cannot
  9853. // contain an lvalue operand.
  9854. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9855. case BO_Mul:
  9856. case BO_Div:
  9857. case BO_Rem:
  9858. case BO_Add:
  9859. case BO_Sub:
  9860. case BO_Shl:
  9861. case BO_Shr:
  9862. case BO_LT:
  9863. case BO_GT:
  9864. case BO_LE:
  9865. case BO_GE:
  9866. case BO_EQ:
  9867. case BO_NE:
  9868. case BO_And:
  9869. case BO_Xor:
  9870. case BO_Or:
  9871. case BO_Comma:
  9872. case BO_Cmp: {
  9873. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9874. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9875. if (Exp->getOpcode() == BO_Div ||
  9876. Exp->getOpcode() == BO_Rem) {
  9877. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  9878. // we don't evaluate one.
  9879. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  9880. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  9881. if (REval == 0)
  9882. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9883. if (REval.isSigned() && REval.isAllOnesValue()) {
  9884. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  9885. if (LEval.isMinSignedValue())
  9886. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9887. }
  9888. }
  9889. }
  9890. if (Exp->getOpcode() == BO_Comma) {
  9891. if (Ctx.getLangOpts().C99) {
  9892. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  9893. // if it isn't evaluated.
  9894. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  9895. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  9896. } else {
  9897. // In both C89 and C++, commas in ICEs are illegal.
  9898. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9899. }
  9900. }
  9901. return Worst(LHSResult, RHSResult);
  9902. }
  9903. case BO_LAnd:
  9904. case BO_LOr: {
  9905. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9906. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9907. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  9908. // Rare case where the RHS has a comma "side-effect"; we need
  9909. // to actually check the condition to see whether the side
  9910. // with the comma is evaluated.
  9911. if ((Exp->getOpcode() == BO_LAnd) !=
  9912. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  9913. return RHSResult;
  9914. return NoDiag();
  9915. }
  9916. return Worst(LHSResult, RHSResult);
  9917. }
  9918. }
  9919. llvm_unreachable("invalid binary operator kind");
  9920. }
  9921. case Expr::ImplicitCastExprClass:
  9922. case Expr::CStyleCastExprClass:
  9923. case Expr::CXXFunctionalCastExprClass:
  9924. case Expr::CXXStaticCastExprClass:
  9925. case Expr::CXXReinterpretCastExprClass:
  9926. case Expr::CXXConstCastExprClass:
  9927. case Expr::ObjCBridgedCastExprClass: {
  9928. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  9929. if (isa<ExplicitCastExpr>(E)) {
  9930. if (const FloatingLiteral *FL
  9931. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  9932. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  9933. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  9934. APSInt IgnoredVal(DestWidth, !DestSigned);
  9935. bool Ignored;
  9936. // If the value does not fit in the destination type, the behavior is
  9937. // undefined, so we are not required to treat it as a constant
  9938. // expression.
  9939. if (FL->getValue().convertToInteger(IgnoredVal,
  9940. llvm::APFloat::rmTowardZero,
  9941. &Ignored) & APFloat::opInvalidOp)
  9942. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9943. return NoDiag();
  9944. }
  9945. }
  9946. switch (cast<CastExpr>(E)->getCastKind()) {
  9947. case CK_LValueToRValue:
  9948. case CK_AtomicToNonAtomic:
  9949. case CK_NonAtomicToAtomic:
  9950. case CK_NoOp:
  9951. case CK_IntegralToBoolean:
  9952. case CK_IntegralCast:
  9953. return CheckICE(SubExpr, Ctx);
  9954. default:
  9955. return ICEDiag(IK_NotICE, E->getBeginLoc());
  9956. }
  9957. }
  9958. case Expr::BinaryConditionalOperatorClass: {
  9959. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  9960. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  9961. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  9962. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9963. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  9964. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  9965. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  9966. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  9967. return FalseResult;
  9968. }
  9969. case Expr::ConditionalOperatorClass: {
  9970. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  9971. // If the condition (ignoring parens) is a __builtin_constant_p call,
  9972. // then only the true side is actually considered in an integer constant
  9973. // expression, and it is fully evaluated. This is an important GNU
  9974. // extension. See GCC PR38377 for discussion.
  9975. if (const CallExpr *CallCE
  9976. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  9977. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  9978. return CheckEvalInICE(E, Ctx);
  9979. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  9980. if (CondResult.Kind == IK_NotICE)
  9981. return CondResult;
  9982. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  9983. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9984. if (TrueResult.Kind == IK_NotICE)
  9985. return TrueResult;
  9986. if (FalseResult.Kind == IK_NotICE)
  9987. return FalseResult;
  9988. if (CondResult.Kind == IK_ICEIfUnevaluated)
  9989. return CondResult;
  9990. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  9991. return NoDiag();
  9992. // Rare case where the diagnostics depend on which side is evaluated
  9993. // Note that if we get here, CondResult is 0, and at least one of
  9994. // TrueResult and FalseResult is non-zero.
  9995. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  9996. return FalseResult;
  9997. return TrueResult;
  9998. }
  9999. case Expr::CXXDefaultArgExprClass:
  10000. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  10001. case Expr::CXXDefaultInitExprClass:
  10002. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  10003. case Expr::ChooseExprClass: {
  10004. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  10005. }
  10006. }
  10007. llvm_unreachable("Invalid StmtClass!");
  10008. }
  10009. /// Evaluate an expression as a C++11 integral constant expression.
  10010. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  10011. const Expr *E,
  10012. llvm::APSInt *Value,
  10013. SourceLocation *Loc) {
  10014. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10015. if (Loc) *Loc = E->getExprLoc();
  10016. return false;
  10017. }
  10018. APValue Result;
  10019. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  10020. return false;
  10021. if (!Result.isInt()) {
  10022. if (Loc) *Loc = E->getExprLoc();
  10023. return false;
  10024. }
  10025. if (Value) *Value = Result.getInt();
  10026. return true;
  10027. }
  10028. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  10029. SourceLocation *Loc) const {
  10030. if (Ctx.getLangOpts().CPlusPlus11)
  10031. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  10032. ICEDiag D = CheckICE(this, Ctx);
  10033. if (D.Kind != IK_ICE) {
  10034. if (Loc) *Loc = D.Loc;
  10035. return false;
  10036. }
  10037. return true;
  10038. }
  10039. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  10040. SourceLocation *Loc, bool isEvaluated) const {
  10041. if (Ctx.getLangOpts().CPlusPlus11)
  10042. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  10043. if (!isIntegerConstantExpr(Ctx, Loc))
  10044. return false;
  10045. // The only possible side-effects here are due to UB discovered in the
  10046. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  10047. // required to treat the expression as an ICE, so we produce the folded
  10048. // value.
  10049. if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
  10050. llvm_unreachable("ICE cannot be evaluated!");
  10051. return true;
  10052. }
  10053. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  10054. return CheckICE(this, Ctx).Kind == IK_ICE;
  10055. }
  10056. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  10057. SourceLocation *Loc) const {
  10058. // We support this checking in C++98 mode in order to diagnose compatibility
  10059. // issues.
  10060. assert(Ctx.getLangOpts().CPlusPlus);
  10061. // Build evaluation settings.
  10062. Expr::EvalStatus Status;
  10063. SmallVector<PartialDiagnosticAt, 8> Diags;
  10064. Status.Diag = &Diags;
  10065. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10066. APValue Scratch;
  10067. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  10068. if (!Diags.empty()) {
  10069. IsConstExpr = false;
  10070. if (Loc) *Loc = Diags[0].first;
  10071. } else if (!IsConstExpr) {
  10072. // FIXME: This shouldn't happen.
  10073. if (Loc) *Loc = getExprLoc();
  10074. }
  10075. return IsConstExpr;
  10076. }
  10077. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  10078. const FunctionDecl *Callee,
  10079. ArrayRef<const Expr*> Args,
  10080. const Expr *This) const {
  10081. Expr::EvalStatus Status;
  10082. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  10083. LValue ThisVal;
  10084. const LValue *ThisPtr = nullptr;
  10085. if (This) {
  10086. #ifndef NDEBUG
  10087. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  10088. assert(MD && "Don't provide `this` for non-methods.");
  10089. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  10090. #endif
  10091. if (EvaluateObjectArgument(Info, This, ThisVal))
  10092. ThisPtr = &ThisVal;
  10093. if (Info.EvalStatus.HasSideEffects)
  10094. return false;
  10095. }
  10096. ArgVector ArgValues(Args.size());
  10097. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  10098. I != E; ++I) {
  10099. if ((*I)->isValueDependent() ||
  10100. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  10101. // If evaluation fails, throw away the argument entirely.
  10102. ArgValues[I - Args.begin()] = APValue();
  10103. if (Info.EvalStatus.HasSideEffects)
  10104. return false;
  10105. }
  10106. // Build fake call to Callee.
  10107. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  10108. ArgValues.data());
  10109. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  10110. }
  10111. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  10112. SmallVectorImpl<
  10113. PartialDiagnosticAt> &Diags) {
  10114. // FIXME: It would be useful to check constexpr function templates, but at the
  10115. // moment the constant expression evaluator cannot cope with the non-rigorous
  10116. // ASTs which we build for dependent expressions.
  10117. if (FD->isDependentContext())
  10118. return true;
  10119. Expr::EvalStatus Status;
  10120. Status.Diag = &Diags;
  10121. EvalInfo Info(FD->getASTContext(), Status,
  10122. EvalInfo::EM_PotentialConstantExpression);
  10123. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  10124. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  10125. // Fabricate an arbitrary expression on the stack and pretend that it
  10126. // is a temporary being used as the 'this' pointer.
  10127. LValue This;
  10128. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  10129. This.set({&VIE, Info.CurrentCall->Index});
  10130. ArrayRef<const Expr*> Args;
  10131. APValue Scratch;
  10132. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  10133. // Evaluate the call as a constant initializer, to allow the construction
  10134. // of objects of non-literal types.
  10135. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  10136. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  10137. } else {
  10138. SourceLocation Loc = FD->getLocation();
  10139. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  10140. Args, FD->getBody(), Info, Scratch, nullptr);
  10141. }
  10142. return Diags.empty();
  10143. }
  10144. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  10145. const FunctionDecl *FD,
  10146. SmallVectorImpl<
  10147. PartialDiagnosticAt> &Diags) {
  10148. Expr::EvalStatus Status;
  10149. Status.Diag = &Diags;
  10150. EvalInfo Info(FD->getASTContext(), Status,
  10151. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  10152. // Fabricate a call stack frame to give the arguments a plausible cover story.
  10153. ArrayRef<const Expr*> Args;
  10154. ArgVector ArgValues(0);
  10155. bool Success = EvaluateArgs(Args, ArgValues, Info);
  10156. (void)Success;
  10157. assert(Success &&
  10158. "Failed to set up arguments for potential constant evaluation");
  10159. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  10160. APValue ResultScratch;
  10161. Evaluate(ResultScratch, Info, E);
  10162. return Diags.empty();
  10163. }
  10164. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  10165. unsigned Type) const {
  10166. if (!getType()->isPointerType())
  10167. return false;
  10168. Expr::EvalStatus Status;
  10169. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  10170. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  10171. }