ExprConstant.cpp 355 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193
  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/RecordLayout.h"
  42. #include "clang/AST/StmtVisitor.h"
  43. #include "clang/AST/TypeLoc.h"
  44. #include "clang/Basic/Builtins.h"
  45. #include "clang/Basic/TargetInfo.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using llvm::APSInt;
  51. using llvm::APFloat;
  52. static bool IsGlobalLValue(APValue::LValueBase B);
  53. namespace {
  54. struct LValue;
  55. struct CallStackFrame;
  56. struct EvalInfo;
  57. static QualType getType(APValue::LValueBase B) {
  58. if (!B) return QualType();
  59. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
  60. return D->getType();
  61. const Expr *Base = B.get<const Expr*>();
  62. // For a materialized temporary, the type of the temporary we materialized
  63. // may not be the type of the expression.
  64. if (const MaterializeTemporaryExpr *MTE =
  65. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  66. SmallVector<const Expr *, 2> CommaLHSs;
  67. SmallVector<SubobjectAdjustment, 2> Adjustments;
  68. const Expr *Temp = MTE->GetTemporaryExpr();
  69. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  70. Adjustments);
  71. // Keep any cv-qualifiers from the reference if we generated a temporary
  72. // for it directly. Otherwise use the type after adjustment.
  73. if (!Adjustments.empty())
  74. return Inner->getType();
  75. }
  76. return Base->getType();
  77. }
  78. /// Get an LValue path entry, which is known to not be an array index, as a
  79. /// field or base class.
  80. static
  81. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  82. APValue::BaseOrMemberType Value;
  83. Value.setFromOpaqueValue(E.BaseOrMember);
  84. return Value;
  85. }
  86. /// Get an LValue path entry, which is known to not be an array index, as a
  87. /// field declaration.
  88. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  89. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  90. }
  91. /// Get an LValue path entry, which is known to not be an array index, as a
  92. /// base class declaration.
  93. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  94. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  95. }
  96. /// Determine whether this LValue path entry for a base class names a virtual
  97. /// base class.
  98. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  99. return getAsBaseOrMember(E).getInt();
  100. }
  101. /// Find the path length and type of the most-derived subobject in the given
  102. /// path, and find the size of the containing array, if any.
  103. static
  104. unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
  105. ArrayRef<APValue::LValuePathEntry> Path,
  106. uint64_t &ArraySize, QualType &Type,
  107. bool &IsArray) {
  108. unsigned MostDerivedLength = 0;
  109. Type = Base;
  110. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  111. if (Type->isArrayType()) {
  112. const ConstantArrayType *CAT =
  113. cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
  114. Type = CAT->getElementType();
  115. ArraySize = CAT->getSize().getZExtValue();
  116. MostDerivedLength = I + 1;
  117. IsArray = true;
  118. } else if (Type->isAnyComplexType()) {
  119. const ComplexType *CT = Type->castAs<ComplexType>();
  120. Type = CT->getElementType();
  121. ArraySize = 2;
  122. MostDerivedLength = I + 1;
  123. IsArray = true;
  124. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  125. Type = FD->getType();
  126. ArraySize = 0;
  127. MostDerivedLength = I + 1;
  128. IsArray = false;
  129. } else {
  130. // Path[I] describes a base class.
  131. ArraySize = 0;
  132. IsArray = false;
  133. }
  134. }
  135. return MostDerivedLength;
  136. }
  137. // The order of this enum is important for diagnostics.
  138. enum CheckSubobjectKind {
  139. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  140. CSK_This, CSK_Real, CSK_Imag
  141. };
  142. /// A path from a glvalue to a subobject of that glvalue.
  143. struct SubobjectDesignator {
  144. /// True if the subobject was named in a manner not supported by C++11. Such
  145. /// lvalues can still be folded, but they are not core constant expressions
  146. /// and we cannot perform lvalue-to-rvalue conversions on them.
  147. unsigned Invalid : 1;
  148. /// Is this a pointer one past the end of an object?
  149. unsigned IsOnePastTheEnd : 1;
  150. /// Indicator of whether the most-derived object is an array element.
  151. unsigned MostDerivedIsArrayElement : 1;
  152. /// The length of the path to the most-derived object of which this is a
  153. /// subobject.
  154. unsigned MostDerivedPathLength : 29;
  155. /// The size of the array of which the most-derived object is an element.
  156. /// This will always be 0 if the most-derived object is not an array
  157. /// element. 0 is not an indicator of whether or not the most-derived object
  158. /// is an array, however, because 0-length arrays are allowed.
  159. uint64_t MostDerivedArraySize;
  160. /// The type of the most derived object referred to by this address.
  161. QualType MostDerivedType;
  162. typedef APValue::LValuePathEntry PathEntry;
  163. /// The entries on the path from the glvalue to the designated subobject.
  164. SmallVector<PathEntry, 8> Entries;
  165. SubobjectDesignator() : Invalid(true) {}
  166. explicit SubobjectDesignator(QualType T)
  167. : Invalid(false), IsOnePastTheEnd(false),
  168. MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
  169. MostDerivedArraySize(0), MostDerivedType(T) {}
  170. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  171. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  172. MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
  173. MostDerivedArraySize(0) {
  174. if (!Invalid) {
  175. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  176. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  177. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  178. if (V.getLValueBase()) {
  179. bool IsArray = false;
  180. MostDerivedPathLength =
  181. findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
  182. V.getLValuePath(), MostDerivedArraySize,
  183. MostDerivedType, IsArray);
  184. MostDerivedIsArrayElement = IsArray;
  185. }
  186. }
  187. }
  188. void setInvalid() {
  189. Invalid = true;
  190. Entries.clear();
  191. }
  192. /// Determine whether this is a one-past-the-end pointer.
  193. bool isOnePastTheEnd() const {
  194. assert(!Invalid);
  195. if (IsOnePastTheEnd)
  196. return true;
  197. if (MostDerivedIsArrayElement &&
  198. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  199. return true;
  200. return false;
  201. }
  202. /// Check that this refers to a valid subobject.
  203. bool isValidSubobject() const {
  204. if (Invalid)
  205. return false;
  206. return !isOnePastTheEnd();
  207. }
  208. /// Check that this refers to a valid subobject, and if not, produce a
  209. /// relevant diagnostic and set the designator as invalid.
  210. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  211. /// Update this designator to refer to the first element within this array.
  212. void addArrayUnchecked(const ConstantArrayType *CAT) {
  213. PathEntry Entry;
  214. Entry.ArrayIndex = 0;
  215. Entries.push_back(Entry);
  216. // This is a most-derived object.
  217. MostDerivedType = CAT->getElementType();
  218. MostDerivedIsArrayElement = true;
  219. MostDerivedArraySize = CAT->getSize().getZExtValue();
  220. MostDerivedPathLength = Entries.size();
  221. }
  222. /// Update this designator to refer to the given base or member of this
  223. /// object.
  224. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  225. PathEntry Entry;
  226. APValue::BaseOrMemberType Value(D, Virtual);
  227. Entry.BaseOrMember = Value.getOpaqueValue();
  228. Entries.push_back(Entry);
  229. // If this isn't a base class, it's a new most-derived object.
  230. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  231. MostDerivedType = FD->getType();
  232. MostDerivedIsArrayElement = false;
  233. MostDerivedArraySize = 0;
  234. MostDerivedPathLength = Entries.size();
  235. }
  236. }
  237. /// Update this designator to refer to the given complex component.
  238. void addComplexUnchecked(QualType EltTy, bool Imag) {
  239. PathEntry Entry;
  240. Entry.ArrayIndex = Imag;
  241. Entries.push_back(Entry);
  242. // This is technically a most-derived object, though in practice this
  243. // is unlikely to matter.
  244. MostDerivedType = EltTy;
  245. MostDerivedIsArrayElement = true;
  246. MostDerivedArraySize = 2;
  247. MostDerivedPathLength = Entries.size();
  248. }
  249. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
  250. /// Add N to the address of this subobject.
  251. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  252. if (Invalid) return;
  253. if (MostDerivedPathLength == Entries.size() &&
  254. MostDerivedIsArrayElement) {
  255. Entries.back().ArrayIndex += N;
  256. if (Entries.back().ArrayIndex > MostDerivedArraySize) {
  257. diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
  258. setInvalid();
  259. }
  260. return;
  261. }
  262. // [expr.add]p4: For the purposes of these operators, a pointer to a
  263. // nonarray object behaves the same as a pointer to the first element of
  264. // an array of length one with the type of the object as its element type.
  265. if (IsOnePastTheEnd && N == (uint64_t)-1)
  266. IsOnePastTheEnd = false;
  267. else if (!IsOnePastTheEnd && N == 1)
  268. IsOnePastTheEnd = true;
  269. else if (N != 0) {
  270. diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
  271. setInvalid();
  272. }
  273. }
  274. };
  275. /// A stack frame in the constexpr call stack.
  276. struct CallStackFrame {
  277. EvalInfo &Info;
  278. /// Parent - The caller of this stack frame.
  279. CallStackFrame *Caller;
  280. /// Callee - The function which was called.
  281. const FunctionDecl *Callee;
  282. /// This - The binding for the this pointer in this call, if any.
  283. const LValue *This;
  284. /// Arguments - Parameter bindings for this function call, indexed by
  285. /// parameters' function scope indices.
  286. APValue *Arguments;
  287. // Note that we intentionally use std::map here so that references to
  288. // values are stable.
  289. typedef std::map<const void*, APValue> MapTy;
  290. typedef MapTy::const_iterator temp_iterator;
  291. /// Temporaries - Temporary lvalues materialized within this stack frame.
  292. MapTy Temporaries;
  293. /// CallLoc - The location of the call expression for this call.
  294. SourceLocation CallLoc;
  295. /// Index - The call index of this call.
  296. unsigned Index;
  297. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  298. const FunctionDecl *Callee, const LValue *This,
  299. APValue *Arguments);
  300. ~CallStackFrame();
  301. APValue *getTemporary(const void *Key) {
  302. MapTy::iterator I = Temporaries.find(Key);
  303. return I == Temporaries.end() ? nullptr : &I->second;
  304. }
  305. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  306. };
  307. /// Temporarily override 'this'.
  308. class ThisOverrideRAII {
  309. public:
  310. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  311. : Frame(Frame), OldThis(Frame.This) {
  312. if (Enable)
  313. Frame.This = NewThis;
  314. }
  315. ~ThisOverrideRAII() {
  316. Frame.This = OldThis;
  317. }
  318. private:
  319. CallStackFrame &Frame;
  320. const LValue *OldThis;
  321. };
  322. /// A partial diagnostic which we might know in advance that we are not going
  323. /// to emit.
  324. class OptionalDiagnostic {
  325. PartialDiagnostic *Diag;
  326. public:
  327. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  328. : Diag(Diag) {}
  329. template<typename T>
  330. OptionalDiagnostic &operator<<(const T &v) {
  331. if (Diag)
  332. *Diag << v;
  333. return *this;
  334. }
  335. OptionalDiagnostic &operator<<(const APSInt &I) {
  336. if (Diag) {
  337. SmallVector<char, 32> Buffer;
  338. I.toString(Buffer);
  339. *Diag << StringRef(Buffer.data(), Buffer.size());
  340. }
  341. return *this;
  342. }
  343. OptionalDiagnostic &operator<<(const APFloat &F) {
  344. if (Diag) {
  345. // FIXME: Force the precision of the source value down so we don't
  346. // print digits which are usually useless (we don't really care here if
  347. // we truncate a digit by accident in edge cases). Ideally,
  348. // APFloat::toString would automatically print the shortest
  349. // representation which rounds to the correct value, but it's a bit
  350. // tricky to implement.
  351. unsigned precision =
  352. llvm::APFloat::semanticsPrecision(F.getSemantics());
  353. precision = (precision * 59 + 195) / 196;
  354. SmallVector<char, 32> Buffer;
  355. F.toString(Buffer, precision);
  356. *Diag << StringRef(Buffer.data(), Buffer.size());
  357. }
  358. return *this;
  359. }
  360. };
  361. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  362. class Cleanup {
  363. llvm::PointerIntPair<APValue*, 1, bool> Value;
  364. public:
  365. Cleanup(APValue *Val, bool IsLifetimeExtended)
  366. : Value(Val, IsLifetimeExtended) {}
  367. bool isLifetimeExtended() const { return Value.getInt(); }
  368. void endLifetime() {
  369. *Value.getPointer() = APValue();
  370. }
  371. };
  372. /// EvalInfo - This is a private struct used by the evaluator to capture
  373. /// information about a subexpression as it is folded. It retains information
  374. /// about the AST context, but also maintains information about the folded
  375. /// expression.
  376. ///
  377. /// If an expression could be evaluated, it is still possible it is not a C
  378. /// "integer constant expression" or constant expression. If not, this struct
  379. /// captures information about how and why not.
  380. ///
  381. /// One bit of information passed *into* the request for constant folding
  382. /// indicates whether the subexpression is "evaluated" or not according to C
  383. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  384. /// evaluate the expression regardless of what the RHS is, but C only allows
  385. /// certain things in certain situations.
  386. struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
  387. ASTContext &Ctx;
  388. /// EvalStatus - Contains information about the evaluation.
  389. Expr::EvalStatus &EvalStatus;
  390. /// CurrentCall - The top of the constexpr call stack.
  391. CallStackFrame *CurrentCall;
  392. /// CallStackDepth - The number of calls in the call stack right now.
  393. unsigned CallStackDepth;
  394. /// NextCallIndex - The next call index to assign.
  395. unsigned NextCallIndex;
  396. /// StepsLeft - The remaining number of evaluation steps we're permitted
  397. /// to perform. This is essentially a limit for the number of statements
  398. /// we will evaluate.
  399. unsigned StepsLeft;
  400. /// BottomFrame - The frame in which evaluation started. This must be
  401. /// initialized after CurrentCall and CallStackDepth.
  402. CallStackFrame BottomFrame;
  403. /// A stack of values whose lifetimes end at the end of some surrounding
  404. /// evaluation frame.
  405. llvm::SmallVector<Cleanup, 16> CleanupStack;
  406. /// EvaluatingDecl - This is the declaration whose initializer is being
  407. /// evaluated, if any.
  408. APValue::LValueBase EvaluatingDecl;
  409. /// EvaluatingDeclValue - This is the value being constructed for the
  410. /// declaration whose initializer is being evaluated, if any.
  411. APValue *EvaluatingDeclValue;
  412. /// The current array initialization index, if we're performing array
  413. /// initialization.
  414. uint64_t ArrayInitIndex = -1;
  415. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  416. /// notes attached to it will also be stored, otherwise they will not be.
  417. bool HasActiveDiagnostic;
  418. /// \brief Have we emitted a diagnostic explaining why we couldn't constant
  419. /// fold (not just why it's not strictly a constant expression)?
  420. bool HasFoldFailureDiagnostic;
  421. /// \brief Whether or not we're currently speculatively evaluating.
  422. bool IsSpeculativelyEvaluating;
  423. enum EvaluationMode {
  424. /// Evaluate as a constant expression. Stop if we find that the expression
  425. /// is not a constant expression.
  426. EM_ConstantExpression,
  427. /// Evaluate as a potential constant expression. Keep going if we hit a
  428. /// construct that we can't evaluate yet (because we don't yet know the
  429. /// value of something) but stop if we hit something that could never be
  430. /// a constant expression.
  431. EM_PotentialConstantExpression,
  432. /// Fold the expression to a constant. Stop if we hit a side-effect that
  433. /// we can't model.
  434. EM_ConstantFold,
  435. /// Evaluate the expression looking for integer overflow and similar
  436. /// issues. Don't worry about side-effects, and try to visit all
  437. /// subexpressions.
  438. EM_EvaluateForOverflow,
  439. /// Evaluate in any way we know how. Don't worry about side-effects that
  440. /// can't be modeled.
  441. EM_IgnoreSideEffects,
  442. /// Evaluate as a constant expression. Stop if we find that the expression
  443. /// is not a constant expression. Some expressions can be retried in the
  444. /// optimizer if we don't constant fold them here, but in an unevaluated
  445. /// context we try to fold them immediately since the optimizer never
  446. /// gets a chance to look at it.
  447. EM_ConstantExpressionUnevaluated,
  448. /// Evaluate as a potential constant expression. Keep going if we hit a
  449. /// construct that we can't evaluate yet (because we don't yet know the
  450. /// value of something) but stop if we hit something that could never be
  451. /// a constant expression. Some expressions can be retried in the
  452. /// optimizer if we don't constant fold them here, but in an unevaluated
  453. /// context we try to fold them immediately since the optimizer never
  454. /// gets a chance to look at it.
  455. EM_PotentialConstantExpressionUnevaluated,
  456. /// Evaluate as a constant expression. Continue evaluating if we find a
  457. /// MemberExpr with a base that can't be evaluated.
  458. EM_DesignatorFold,
  459. } EvalMode;
  460. /// Are we checking whether the expression is a potential constant
  461. /// expression?
  462. bool checkingPotentialConstantExpression() const {
  463. return EvalMode == EM_PotentialConstantExpression ||
  464. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  465. }
  466. /// Are we checking an expression for overflow?
  467. // FIXME: We should check for any kind of undefined or suspicious behavior
  468. // in such constructs, not just overflow.
  469. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  470. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  471. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  472. CallStackDepth(0), NextCallIndex(1),
  473. StepsLeft(getLangOpts().ConstexprStepLimit),
  474. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  475. EvaluatingDecl((const ValueDecl *)nullptr),
  476. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  477. HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
  478. EvalMode(Mode) {}
  479. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  480. EvaluatingDecl = Base;
  481. EvaluatingDeclValue = &Value;
  482. }
  483. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  484. bool CheckCallLimit(SourceLocation Loc) {
  485. // Don't perform any constexpr calls (other than the call we're checking)
  486. // when checking a potential constant expression.
  487. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  488. return false;
  489. if (NextCallIndex == 0) {
  490. // NextCallIndex has wrapped around.
  491. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  492. return false;
  493. }
  494. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  495. return true;
  496. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  497. << getLangOpts().ConstexprCallDepth;
  498. return false;
  499. }
  500. CallStackFrame *getCallFrame(unsigned CallIndex) {
  501. assert(CallIndex && "no call index in getCallFrame");
  502. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  503. // be null in this loop.
  504. CallStackFrame *Frame = CurrentCall;
  505. while (Frame->Index > CallIndex)
  506. Frame = Frame->Caller;
  507. return (Frame->Index == CallIndex) ? Frame : nullptr;
  508. }
  509. bool nextStep(const Stmt *S) {
  510. if (!StepsLeft) {
  511. FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
  512. return false;
  513. }
  514. --StepsLeft;
  515. return true;
  516. }
  517. private:
  518. /// Add a diagnostic to the diagnostics list.
  519. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  520. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  521. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  522. return EvalStatus.Diag->back().second;
  523. }
  524. /// Add notes containing a call stack to the current point of evaluation.
  525. void addCallStack(unsigned Limit);
  526. private:
  527. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  528. unsigned ExtraNotes, bool IsCCEDiag) {
  529. if (EvalStatus.Diag) {
  530. // If we have a prior diagnostic, it will be noting that the expression
  531. // isn't a constant expression. This diagnostic is more important,
  532. // unless we require this evaluation to produce a constant expression.
  533. //
  534. // FIXME: We might want to show both diagnostics to the user in
  535. // EM_ConstantFold mode.
  536. if (!EvalStatus.Diag->empty()) {
  537. switch (EvalMode) {
  538. case EM_ConstantFold:
  539. case EM_IgnoreSideEffects:
  540. case EM_EvaluateForOverflow:
  541. if (!HasFoldFailureDiagnostic)
  542. break;
  543. // We've already failed to fold something. Keep that diagnostic.
  544. case EM_ConstantExpression:
  545. case EM_PotentialConstantExpression:
  546. case EM_ConstantExpressionUnevaluated:
  547. case EM_PotentialConstantExpressionUnevaluated:
  548. case EM_DesignatorFold:
  549. HasActiveDiagnostic = false;
  550. return OptionalDiagnostic();
  551. }
  552. }
  553. unsigned CallStackNotes = CallStackDepth - 1;
  554. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  555. if (Limit)
  556. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  557. if (checkingPotentialConstantExpression())
  558. CallStackNotes = 0;
  559. HasActiveDiagnostic = true;
  560. HasFoldFailureDiagnostic = !IsCCEDiag;
  561. EvalStatus.Diag->clear();
  562. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  563. addDiag(Loc, DiagId);
  564. if (!checkingPotentialConstantExpression())
  565. addCallStack(Limit);
  566. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  567. }
  568. HasActiveDiagnostic = false;
  569. return OptionalDiagnostic();
  570. }
  571. public:
  572. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  573. OptionalDiagnostic
  574. FFDiag(SourceLocation Loc,
  575. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  576. unsigned ExtraNotes = 0) {
  577. return Diag(Loc, DiagId, ExtraNotes, false);
  578. }
  579. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  580. = diag::note_invalid_subexpr_in_const_expr,
  581. unsigned ExtraNotes = 0) {
  582. if (EvalStatus.Diag)
  583. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  584. HasActiveDiagnostic = false;
  585. return OptionalDiagnostic();
  586. }
  587. /// Diagnose that the evaluation does not produce a C++11 core constant
  588. /// expression.
  589. ///
  590. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  591. /// EM_PotentialConstantExpression mode and we produce one of these.
  592. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  593. = diag::note_invalid_subexpr_in_const_expr,
  594. unsigned ExtraNotes = 0) {
  595. // Don't override a previous diagnostic. Don't bother collecting
  596. // diagnostics if we're evaluating for overflow.
  597. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  598. HasActiveDiagnostic = false;
  599. return OptionalDiagnostic();
  600. }
  601. return Diag(Loc, DiagId, ExtraNotes, true);
  602. }
  603. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  604. = diag::note_invalid_subexpr_in_const_expr,
  605. unsigned ExtraNotes = 0) {
  606. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  607. }
  608. /// Add a note to a prior diagnostic.
  609. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  610. if (!HasActiveDiagnostic)
  611. return OptionalDiagnostic();
  612. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  613. }
  614. /// Add a stack of notes to a prior diagnostic.
  615. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  616. if (HasActiveDiagnostic) {
  617. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  618. Diags.begin(), Diags.end());
  619. }
  620. }
  621. /// Should we continue evaluation after encountering a side-effect that we
  622. /// couldn't model?
  623. bool keepEvaluatingAfterSideEffect() {
  624. switch (EvalMode) {
  625. case EM_PotentialConstantExpression:
  626. case EM_PotentialConstantExpressionUnevaluated:
  627. case EM_EvaluateForOverflow:
  628. case EM_IgnoreSideEffects:
  629. return true;
  630. case EM_ConstantExpression:
  631. case EM_ConstantExpressionUnevaluated:
  632. case EM_ConstantFold:
  633. case EM_DesignatorFold:
  634. return false;
  635. }
  636. llvm_unreachable("Missed EvalMode case");
  637. }
  638. /// Note that we have had a side-effect, and determine whether we should
  639. /// keep evaluating.
  640. bool noteSideEffect() {
  641. EvalStatus.HasSideEffects = true;
  642. return keepEvaluatingAfterSideEffect();
  643. }
  644. /// Should we continue evaluation after encountering undefined behavior?
  645. bool keepEvaluatingAfterUndefinedBehavior() {
  646. switch (EvalMode) {
  647. case EM_EvaluateForOverflow:
  648. case EM_IgnoreSideEffects:
  649. case EM_ConstantFold:
  650. case EM_DesignatorFold:
  651. return true;
  652. case EM_PotentialConstantExpression:
  653. case EM_PotentialConstantExpressionUnevaluated:
  654. case EM_ConstantExpression:
  655. case EM_ConstantExpressionUnevaluated:
  656. return false;
  657. }
  658. llvm_unreachable("Missed EvalMode case");
  659. }
  660. /// Note that we hit something that was technically undefined behavior, but
  661. /// that we can evaluate past it (such as signed overflow or floating-point
  662. /// division by zero.)
  663. bool noteUndefinedBehavior() {
  664. EvalStatus.HasUndefinedBehavior = true;
  665. return keepEvaluatingAfterUndefinedBehavior();
  666. }
  667. /// Should we continue evaluation as much as possible after encountering a
  668. /// construct which can't be reduced to a value?
  669. bool keepEvaluatingAfterFailure() {
  670. if (!StepsLeft)
  671. return false;
  672. switch (EvalMode) {
  673. case EM_PotentialConstantExpression:
  674. case EM_PotentialConstantExpressionUnevaluated:
  675. case EM_EvaluateForOverflow:
  676. return true;
  677. case EM_ConstantExpression:
  678. case EM_ConstantExpressionUnevaluated:
  679. case EM_ConstantFold:
  680. case EM_IgnoreSideEffects:
  681. case EM_DesignatorFold:
  682. return false;
  683. }
  684. llvm_unreachable("Missed EvalMode case");
  685. }
  686. /// Notes that we failed to evaluate an expression that other expressions
  687. /// directly depend on, and determine if we should keep evaluating. This
  688. /// should only be called if we actually intend to keep evaluating.
  689. ///
  690. /// Call noteSideEffect() instead if we may be able to ignore the value that
  691. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  692. ///
  693. /// (Foo(), 1) // use noteSideEffect
  694. /// (Foo() || true) // use noteSideEffect
  695. /// Foo() + 1 // use noteFailure
  696. LLVM_NODISCARD bool noteFailure() {
  697. // Failure when evaluating some expression often means there is some
  698. // subexpression whose evaluation was skipped. Therefore, (because we
  699. // don't track whether we skipped an expression when unwinding after an
  700. // evaluation failure) every evaluation failure that bubbles up from a
  701. // subexpression implies that a side-effect has potentially happened. We
  702. // skip setting the HasSideEffects flag to true until we decide to
  703. // continue evaluating after that point, which happens here.
  704. bool KeepGoing = keepEvaluatingAfterFailure();
  705. EvalStatus.HasSideEffects |= KeepGoing;
  706. return KeepGoing;
  707. }
  708. bool allowInvalidBaseExpr() const {
  709. return EvalMode == EM_DesignatorFold;
  710. }
  711. class ArrayInitLoopIndex {
  712. EvalInfo &Info;
  713. uint64_t OuterIndex;
  714. public:
  715. ArrayInitLoopIndex(EvalInfo &Info)
  716. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  717. Info.ArrayInitIndex = 0;
  718. }
  719. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  720. operator uint64_t&() { return Info.ArrayInitIndex; }
  721. };
  722. };
  723. /// Object used to treat all foldable expressions as constant expressions.
  724. struct FoldConstant {
  725. EvalInfo &Info;
  726. bool Enabled;
  727. bool HadNoPriorDiags;
  728. EvalInfo::EvaluationMode OldMode;
  729. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  730. : Info(Info),
  731. Enabled(Enabled),
  732. HadNoPriorDiags(Info.EvalStatus.Diag &&
  733. Info.EvalStatus.Diag->empty() &&
  734. !Info.EvalStatus.HasSideEffects),
  735. OldMode(Info.EvalMode) {
  736. if (Enabled &&
  737. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  738. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  739. Info.EvalMode = EvalInfo::EM_ConstantFold;
  740. }
  741. void keepDiagnostics() { Enabled = false; }
  742. ~FoldConstant() {
  743. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  744. !Info.EvalStatus.HasSideEffects)
  745. Info.EvalStatus.Diag->clear();
  746. Info.EvalMode = OldMode;
  747. }
  748. };
  749. /// RAII object used to treat the current evaluation as the correct pointer
  750. /// offset fold for the current EvalMode
  751. struct FoldOffsetRAII {
  752. EvalInfo &Info;
  753. EvalInfo::EvaluationMode OldMode;
  754. explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
  755. : Info(Info), OldMode(Info.EvalMode) {
  756. if (!Info.checkingPotentialConstantExpression())
  757. Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
  758. : EvalInfo::EM_ConstantFold;
  759. }
  760. ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
  761. };
  762. /// RAII object used to optionally suppress diagnostics and side-effects from
  763. /// a speculative evaluation.
  764. class SpeculativeEvaluationRAII {
  765. /// Pair of EvalInfo, and a bit that stores whether or not we were
  766. /// speculatively evaluating when we created this RAII.
  767. llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
  768. Expr::EvalStatus Old;
  769. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  770. InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
  771. Old = Other.Old;
  772. Other.InfoAndOldSpecEval.setPointer(nullptr);
  773. }
  774. void maybeRestoreState() {
  775. EvalInfo *Info = InfoAndOldSpecEval.getPointer();
  776. if (!Info)
  777. return;
  778. Info->EvalStatus = Old;
  779. Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
  780. }
  781. public:
  782. SpeculativeEvaluationRAII() = default;
  783. SpeculativeEvaluationRAII(
  784. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  785. : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
  786. Old(Info.EvalStatus) {
  787. Info.EvalStatus.Diag = NewDiag;
  788. Info.IsSpeculativelyEvaluating = true;
  789. }
  790. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  791. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  792. moveFromAndCancel(std::move(Other));
  793. }
  794. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  795. maybeRestoreState();
  796. moveFromAndCancel(std::move(Other));
  797. return *this;
  798. }
  799. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  800. };
  801. /// RAII object wrapping a full-expression or block scope, and handling
  802. /// the ending of the lifetime of temporaries created within it.
  803. template<bool IsFullExpression>
  804. class ScopeRAII {
  805. EvalInfo &Info;
  806. unsigned OldStackSize;
  807. public:
  808. ScopeRAII(EvalInfo &Info)
  809. : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
  810. ~ScopeRAII() {
  811. // Body moved to a static method to encourage the compiler to inline away
  812. // instances of this class.
  813. cleanup(Info, OldStackSize);
  814. }
  815. private:
  816. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  817. unsigned NewEnd = OldStackSize;
  818. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  819. I != N; ++I) {
  820. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  821. // Full-expression cleanup of a lifetime-extended temporary: nothing
  822. // to do, just move this cleanup to the right place in the stack.
  823. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  824. ++NewEnd;
  825. } else {
  826. // End the lifetime of the object.
  827. Info.CleanupStack[I].endLifetime();
  828. }
  829. }
  830. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  831. Info.CleanupStack.end());
  832. }
  833. };
  834. typedef ScopeRAII<false> BlockScopeRAII;
  835. typedef ScopeRAII<true> FullExpressionRAII;
  836. }
  837. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  838. CheckSubobjectKind CSK) {
  839. if (Invalid)
  840. return false;
  841. if (isOnePastTheEnd()) {
  842. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  843. << CSK;
  844. setInvalid();
  845. return false;
  846. }
  847. return true;
  848. }
  849. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  850. const Expr *E, uint64_t N) {
  851. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  852. Info.CCEDiag(E, diag::note_constexpr_array_index)
  853. << static_cast<int>(N) << /*array*/ 0
  854. << static_cast<unsigned>(MostDerivedArraySize);
  855. else
  856. Info.CCEDiag(E, diag::note_constexpr_array_index)
  857. << static_cast<int>(N) << /*non-array*/ 1;
  858. setInvalid();
  859. }
  860. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  861. const FunctionDecl *Callee, const LValue *This,
  862. APValue *Arguments)
  863. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  864. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  865. Info.CurrentCall = this;
  866. ++Info.CallStackDepth;
  867. }
  868. CallStackFrame::~CallStackFrame() {
  869. assert(Info.CurrentCall == this && "calls retired out of order");
  870. --Info.CallStackDepth;
  871. Info.CurrentCall = Caller;
  872. }
  873. APValue &CallStackFrame::createTemporary(const void *Key,
  874. bool IsLifetimeExtended) {
  875. APValue &Result = Temporaries[Key];
  876. assert(Result.isUninit() && "temporary created multiple times");
  877. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  878. return Result;
  879. }
  880. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  881. void EvalInfo::addCallStack(unsigned Limit) {
  882. // Determine which calls to skip, if any.
  883. unsigned ActiveCalls = CallStackDepth - 1;
  884. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  885. if (Limit && Limit < ActiveCalls) {
  886. SkipStart = Limit / 2 + Limit % 2;
  887. SkipEnd = ActiveCalls - Limit / 2;
  888. }
  889. // Walk the call stack and add the diagnostics.
  890. unsigned CallIdx = 0;
  891. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  892. Frame = Frame->Caller, ++CallIdx) {
  893. // Skip this call?
  894. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  895. if (CallIdx == SkipStart) {
  896. // Note that we're skipping calls.
  897. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  898. << unsigned(ActiveCalls - Limit);
  899. }
  900. continue;
  901. }
  902. // Use a different note for an inheriting constructor, because from the
  903. // user's perspective it's not really a function at all.
  904. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  905. if (CD->isInheritingConstructor()) {
  906. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  907. << CD->getParent();
  908. continue;
  909. }
  910. }
  911. SmallVector<char, 128> Buffer;
  912. llvm::raw_svector_ostream Out(Buffer);
  913. describeCall(Frame, Out);
  914. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  915. }
  916. }
  917. namespace {
  918. struct ComplexValue {
  919. private:
  920. bool IsInt;
  921. public:
  922. APSInt IntReal, IntImag;
  923. APFloat FloatReal, FloatImag;
  924. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  925. void makeComplexFloat() { IsInt = false; }
  926. bool isComplexFloat() const { return !IsInt; }
  927. APFloat &getComplexFloatReal() { return FloatReal; }
  928. APFloat &getComplexFloatImag() { return FloatImag; }
  929. void makeComplexInt() { IsInt = true; }
  930. bool isComplexInt() const { return IsInt; }
  931. APSInt &getComplexIntReal() { return IntReal; }
  932. APSInt &getComplexIntImag() { return IntImag; }
  933. void moveInto(APValue &v) const {
  934. if (isComplexFloat())
  935. v = APValue(FloatReal, FloatImag);
  936. else
  937. v = APValue(IntReal, IntImag);
  938. }
  939. void setFrom(const APValue &v) {
  940. assert(v.isComplexFloat() || v.isComplexInt());
  941. if (v.isComplexFloat()) {
  942. makeComplexFloat();
  943. FloatReal = v.getComplexFloatReal();
  944. FloatImag = v.getComplexFloatImag();
  945. } else {
  946. makeComplexInt();
  947. IntReal = v.getComplexIntReal();
  948. IntImag = v.getComplexIntImag();
  949. }
  950. }
  951. };
  952. struct LValue {
  953. APValue::LValueBase Base;
  954. CharUnits Offset;
  955. unsigned InvalidBase : 1;
  956. unsigned CallIndex : 31;
  957. SubobjectDesignator Designator;
  958. bool IsNullPtr;
  959. const APValue::LValueBase getLValueBase() const { return Base; }
  960. CharUnits &getLValueOffset() { return Offset; }
  961. const CharUnits &getLValueOffset() const { return Offset; }
  962. unsigned getLValueCallIndex() const { return CallIndex; }
  963. SubobjectDesignator &getLValueDesignator() { return Designator; }
  964. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  965. bool isNullPointer() const { return IsNullPtr;}
  966. void moveInto(APValue &V) const {
  967. if (Designator.Invalid)
  968. V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
  969. IsNullPtr);
  970. else
  971. V = APValue(Base, Offset, Designator.Entries,
  972. Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
  973. }
  974. void setFrom(ASTContext &Ctx, const APValue &V) {
  975. assert(V.isLValue());
  976. Base = V.getLValueBase();
  977. Offset = V.getLValueOffset();
  978. InvalidBase = false;
  979. CallIndex = V.getLValueCallIndex();
  980. Designator = SubobjectDesignator(Ctx, V);
  981. IsNullPtr = V.isNullPointer();
  982. }
  983. void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
  984. bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
  985. Base = B;
  986. Offset = CharUnits::fromQuantity(Offset_);
  987. InvalidBase = BInvalid;
  988. CallIndex = I;
  989. Designator = SubobjectDesignator(getType(B));
  990. IsNullPtr = IsNullPtr_;
  991. }
  992. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  993. set(B, I, true);
  994. }
  995. // Check that this LValue is not based on a null pointer. If it is, produce
  996. // a diagnostic and mark the designator as invalid.
  997. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  998. CheckSubobjectKind CSK) {
  999. if (Designator.Invalid)
  1000. return false;
  1001. if (IsNullPtr) {
  1002. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  1003. << CSK;
  1004. Designator.setInvalid();
  1005. return false;
  1006. }
  1007. return true;
  1008. }
  1009. // Check this LValue refers to an object. If not, set the designator to be
  1010. // invalid and emit a diagnostic.
  1011. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1012. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1013. Designator.checkSubobject(Info, E, CSK);
  1014. }
  1015. void addDecl(EvalInfo &Info, const Expr *E,
  1016. const Decl *D, bool Virtual = false) {
  1017. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1018. Designator.addDeclUnchecked(D, Virtual);
  1019. }
  1020. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1021. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1022. Designator.addArrayUnchecked(CAT);
  1023. }
  1024. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1025. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1026. Designator.addComplexUnchecked(EltTy, Imag);
  1027. }
  1028. void clearIsNullPointer() {
  1029. IsNullPtr = false;
  1030. }
  1031. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
  1032. CharUnits ElementSize) {
  1033. // Compute the new offset in the appropriate width.
  1034. Offset += Index * ElementSize;
  1035. if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
  1036. Designator.adjustIndex(Info, E, Index);
  1037. if (Index)
  1038. clearIsNullPointer();
  1039. }
  1040. void adjustOffset(CharUnits N) {
  1041. Offset += N;
  1042. if (N.getQuantity())
  1043. clearIsNullPointer();
  1044. }
  1045. };
  1046. struct MemberPtr {
  1047. MemberPtr() {}
  1048. explicit MemberPtr(const ValueDecl *Decl) :
  1049. DeclAndIsDerivedMember(Decl, false), Path() {}
  1050. /// The member or (direct or indirect) field referred to by this member
  1051. /// pointer, or 0 if this is a null member pointer.
  1052. const ValueDecl *getDecl() const {
  1053. return DeclAndIsDerivedMember.getPointer();
  1054. }
  1055. /// Is this actually a member of some type derived from the relevant class?
  1056. bool isDerivedMember() const {
  1057. return DeclAndIsDerivedMember.getInt();
  1058. }
  1059. /// Get the class which the declaration actually lives in.
  1060. const CXXRecordDecl *getContainingRecord() const {
  1061. return cast<CXXRecordDecl>(
  1062. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1063. }
  1064. void moveInto(APValue &V) const {
  1065. V = APValue(getDecl(), isDerivedMember(), Path);
  1066. }
  1067. void setFrom(const APValue &V) {
  1068. assert(V.isMemberPointer());
  1069. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1070. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1071. Path.clear();
  1072. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1073. Path.insert(Path.end(), P.begin(), P.end());
  1074. }
  1075. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1076. /// whether the member is a member of some class derived from the class type
  1077. /// of the member pointer.
  1078. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1079. /// Path - The path of base/derived classes from the member declaration's
  1080. /// class (exclusive) to the class type of the member pointer (inclusive).
  1081. SmallVector<const CXXRecordDecl*, 4> Path;
  1082. /// Perform a cast towards the class of the Decl (either up or down the
  1083. /// hierarchy).
  1084. bool castBack(const CXXRecordDecl *Class) {
  1085. assert(!Path.empty());
  1086. const CXXRecordDecl *Expected;
  1087. if (Path.size() >= 2)
  1088. Expected = Path[Path.size() - 2];
  1089. else
  1090. Expected = getContainingRecord();
  1091. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1092. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1093. // if B does not contain the original member and is not a base or
  1094. // derived class of the class containing the original member, the result
  1095. // of the cast is undefined.
  1096. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1097. // (D::*). We consider that to be a language defect.
  1098. return false;
  1099. }
  1100. Path.pop_back();
  1101. return true;
  1102. }
  1103. /// Perform a base-to-derived member pointer cast.
  1104. bool castToDerived(const CXXRecordDecl *Derived) {
  1105. if (!getDecl())
  1106. return true;
  1107. if (!isDerivedMember()) {
  1108. Path.push_back(Derived);
  1109. return true;
  1110. }
  1111. if (!castBack(Derived))
  1112. return false;
  1113. if (Path.empty())
  1114. DeclAndIsDerivedMember.setInt(false);
  1115. return true;
  1116. }
  1117. /// Perform a derived-to-base member pointer cast.
  1118. bool castToBase(const CXXRecordDecl *Base) {
  1119. if (!getDecl())
  1120. return true;
  1121. if (Path.empty())
  1122. DeclAndIsDerivedMember.setInt(true);
  1123. if (isDerivedMember()) {
  1124. Path.push_back(Base);
  1125. return true;
  1126. }
  1127. return castBack(Base);
  1128. }
  1129. };
  1130. /// Compare two member pointers, which are assumed to be of the same type.
  1131. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1132. if (!LHS.getDecl() || !RHS.getDecl())
  1133. return !LHS.getDecl() && !RHS.getDecl();
  1134. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1135. return false;
  1136. return LHS.Path == RHS.Path;
  1137. }
  1138. }
  1139. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1140. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1141. const LValue &This, const Expr *E,
  1142. bool AllowNonLiteralTypes = false);
  1143. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
  1144. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
  1145. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1146. EvalInfo &Info);
  1147. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1148. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1149. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1150. EvalInfo &Info);
  1151. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1152. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1153. static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
  1154. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1155. //===----------------------------------------------------------------------===//
  1156. // Misc utilities
  1157. //===----------------------------------------------------------------------===//
  1158. /// Produce a string describing the given constexpr call.
  1159. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1160. unsigned ArgIndex = 0;
  1161. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1162. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1163. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1164. if (!IsMemberCall)
  1165. Out << *Frame->Callee << '(';
  1166. if (Frame->This && IsMemberCall) {
  1167. APValue Val;
  1168. Frame->This->moveInto(Val);
  1169. Val.printPretty(Out, Frame->Info.Ctx,
  1170. Frame->This->Designator.MostDerivedType);
  1171. // FIXME: Add parens around Val if needed.
  1172. Out << "->" << *Frame->Callee << '(';
  1173. IsMemberCall = false;
  1174. }
  1175. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1176. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1177. if (ArgIndex > (unsigned)IsMemberCall)
  1178. Out << ", ";
  1179. const ParmVarDecl *Param = *I;
  1180. const APValue &Arg = Frame->Arguments[ArgIndex];
  1181. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1182. if (ArgIndex == 0 && IsMemberCall)
  1183. Out << "->" << *Frame->Callee << '(';
  1184. }
  1185. Out << ')';
  1186. }
  1187. /// Evaluate an expression to see if it had side-effects, and discard its
  1188. /// result.
  1189. /// \return \c true if the caller should keep evaluating.
  1190. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1191. APValue Scratch;
  1192. if (!Evaluate(Scratch, Info, E))
  1193. // We don't need the value, but we might have skipped a side effect here.
  1194. return Info.noteSideEffect();
  1195. return true;
  1196. }
  1197. /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
  1198. /// return its existing value.
  1199. static int64_t getExtValue(const APSInt &Value) {
  1200. return Value.isSigned() ? Value.getSExtValue()
  1201. : static_cast<int64_t>(Value.getZExtValue());
  1202. }
  1203. /// Should this call expression be treated as a string literal?
  1204. static bool IsStringLiteralCall(const CallExpr *E) {
  1205. unsigned Builtin = E->getBuiltinCallee();
  1206. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1207. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1208. }
  1209. static bool IsGlobalLValue(APValue::LValueBase B) {
  1210. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1211. // constant expression of pointer type that evaluates to...
  1212. // ... a null pointer value, or a prvalue core constant expression of type
  1213. // std::nullptr_t.
  1214. if (!B) return true;
  1215. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1216. // ... the address of an object with static storage duration,
  1217. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1218. return VD->hasGlobalStorage();
  1219. // ... the address of a function,
  1220. return isa<FunctionDecl>(D);
  1221. }
  1222. const Expr *E = B.get<const Expr*>();
  1223. switch (E->getStmtClass()) {
  1224. default:
  1225. return false;
  1226. case Expr::CompoundLiteralExprClass: {
  1227. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1228. return CLE->isFileScope() && CLE->isLValue();
  1229. }
  1230. case Expr::MaterializeTemporaryExprClass:
  1231. // A materialized temporary might have been lifetime-extended to static
  1232. // storage duration.
  1233. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1234. // A string literal has static storage duration.
  1235. case Expr::StringLiteralClass:
  1236. case Expr::PredefinedExprClass:
  1237. case Expr::ObjCStringLiteralClass:
  1238. case Expr::ObjCEncodeExprClass:
  1239. case Expr::CXXTypeidExprClass:
  1240. case Expr::CXXUuidofExprClass:
  1241. return true;
  1242. case Expr::CallExprClass:
  1243. return IsStringLiteralCall(cast<CallExpr>(E));
  1244. // For GCC compatibility, &&label has static storage duration.
  1245. case Expr::AddrLabelExprClass:
  1246. return true;
  1247. // A Block literal expression may be used as the initialization value for
  1248. // Block variables at global or local static scope.
  1249. case Expr::BlockExprClass:
  1250. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1251. case Expr::ImplicitValueInitExprClass:
  1252. // FIXME:
  1253. // We can never form an lvalue with an implicit value initialization as its
  1254. // base through expression evaluation, so these only appear in one case: the
  1255. // implicit variable declaration we invent when checking whether a constexpr
  1256. // constructor can produce a constant expression. We must assume that such
  1257. // an expression might be a global lvalue.
  1258. return true;
  1259. }
  1260. }
  1261. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1262. assert(Base && "no location for a null lvalue");
  1263. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1264. if (VD)
  1265. Info.Note(VD->getLocation(), diag::note_declared_at);
  1266. else
  1267. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1268. diag::note_constexpr_temporary_here);
  1269. }
  1270. /// Check that this reference or pointer core constant expression is a valid
  1271. /// value for an address or reference constant expression. Return true if we
  1272. /// can fold this expression, whether or not it's a constant expression.
  1273. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1274. QualType Type, const LValue &LVal) {
  1275. bool IsReferenceType = Type->isReferenceType();
  1276. APValue::LValueBase Base = LVal.getLValueBase();
  1277. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1278. // Check that the object is a global. Note that the fake 'this' object we
  1279. // manufacture when checking potential constant expressions is conservatively
  1280. // assumed to be global here.
  1281. if (!IsGlobalLValue(Base)) {
  1282. if (Info.getLangOpts().CPlusPlus11) {
  1283. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1284. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1285. << IsReferenceType << !Designator.Entries.empty()
  1286. << !!VD << VD;
  1287. NoteLValueLocation(Info, Base);
  1288. } else {
  1289. Info.FFDiag(Loc);
  1290. }
  1291. // Don't allow references to temporaries to escape.
  1292. return false;
  1293. }
  1294. assert((Info.checkingPotentialConstantExpression() ||
  1295. LVal.getLValueCallIndex() == 0) &&
  1296. "have call index for global lvalue");
  1297. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1298. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1299. // Check if this is a thread-local variable.
  1300. if (Var->getTLSKind())
  1301. return false;
  1302. // A dllimport variable never acts like a constant.
  1303. if (Var->hasAttr<DLLImportAttr>())
  1304. return false;
  1305. }
  1306. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1307. // __declspec(dllimport) must be handled very carefully:
  1308. // We must never initialize an expression with the thunk in C++.
  1309. // Doing otherwise would allow the same id-expression to yield
  1310. // different addresses for the same function in different translation
  1311. // units. However, this means that we must dynamically initialize the
  1312. // expression with the contents of the import address table at runtime.
  1313. //
  1314. // The C language has no notion of ODR; furthermore, it has no notion of
  1315. // dynamic initialization. This means that we are permitted to
  1316. // perform initialization with the address of the thunk.
  1317. if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
  1318. return false;
  1319. }
  1320. }
  1321. // Allow address constant expressions to be past-the-end pointers. This is
  1322. // an extension: the standard requires them to point to an object.
  1323. if (!IsReferenceType)
  1324. return true;
  1325. // A reference constant expression must refer to an object.
  1326. if (!Base) {
  1327. // FIXME: diagnostic
  1328. Info.CCEDiag(Loc);
  1329. return true;
  1330. }
  1331. // Does this refer one past the end of some object?
  1332. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1333. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1334. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1335. << !Designator.Entries.empty() << !!VD << VD;
  1336. NoteLValueLocation(Info, Base);
  1337. }
  1338. return true;
  1339. }
  1340. /// Check that this core constant expression is of literal type, and if not,
  1341. /// produce an appropriate diagnostic.
  1342. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1343. const LValue *This = nullptr) {
  1344. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1345. return true;
  1346. // C++1y: A constant initializer for an object o [...] may also invoke
  1347. // constexpr constructors for o and its subobjects even if those objects
  1348. // are of non-literal class types.
  1349. if (Info.getLangOpts().CPlusPlus14 && This &&
  1350. Info.EvaluatingDecl == This->getLValueBase())
  1351. return true;
  1352. // Prvalue constant expressions must be of literal types.
  1353. if (Info.getLangOpts().CPlusPlus11)
  1354. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1355. << E->getType();
  1356. else
  1357. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1358. return false;
  1359. }
  1360. /// Check that this core constant expression value is a valid value for a
  1361. /// constant expression. If not, report an appropriate diagnostic. Does not
  1362. /// check that the expression is of literal type.
  1363. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  1364. QualType Type, const APValue &Value) {
  1365. if (Value.isUninit()) {
  1366. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1367. << true << Type;
  1368. return false;
  1369. }
  1370. // We allow _Atomic(T) to be initialized from anything that T can be
  1371. // initialized from.
  1372. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1373. Type = AT->getValueType();
  1374. // Core issue 1454: For a literal constant expression of array or class type,
  1375. // each subobject of its value shall have been initialized by a constant
  1376. // expression.
  1377. if (Value.isArray()) {
  1378. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1379. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1380. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1381. Value.getArrayInitializedElt(I)))
  1382. return false;
  1383. }
  1384. if (!Value.hasArrayFiller())
  1385. return true;
  1386. return CheckConstantExpression(Info, DiagLoc, EltTy,
  1387. Value.getArrayFiller());
  1388. }
  1389. if (Value.isUnion() && Value.getUnionField()) {
  1390. return CheckConstantExpression(Info, DiagLoc,
  1391. Value.getUnionField()->getType(),
  1392. Value.getUnionValue());
  1393. }
  1394. if (Value.isStruct()) {
  1395. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1396. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1397. unsigned BaseIndex = 0;
  1398. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  1399. End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
  1400. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1401. Value.getStructBase(BaseIndex)))
  1402. return false;
  1403. }
  1404. }
  1405. for (const auto *I : RD->fields()) {
  1406. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1407. Value.getStructField(I->getFieldIndex())))
  1408. return false;
  1409. }
  1410. }
  1411. if (Value.isLValue()) {
  1412. LValue LVal;
  1413. LVal.setFrom(Info.Ctx, Value);
  1414. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
  1415. }
  1416. // Everything else is fine.
  1417. return true;
  1418. }
  1419. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1420. return LVal.Base.dyn_cast<const ValueDecl*>();
  1421. }
  1422. static bool IsLiteralLValue(const LValue &Value) {
  1423. if (Value.CallIndex)
  1424. return false;
  1425. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1426. return E && !isa<MaterializeTemporaryExpr>(E);
  1427. }
  1428. static bool IsWeakLValue(const LValue &Value) {
  1429. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1430. return Decl && Decl->isWeak();
  1431. }
  1432. static bool isZeroSized(const LValue &Value) {
  1433. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1434. if (Decl && isa<VarDecl>(Decl)) {
  1435. QualType Ty = Decl->getType();
  1436. if (Ty->isArrayType())
  1437. return Ty->isIncompleteType() ||
  1438. Decl->getASTContext().getTypeSize(Ty) == 0;
  1439. }
  1440. return false;
  1441. }
  1442. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1443. // A null base expression indicates a null pointer. These are always
  1444. // evaluatable, and they are false unless the offset is zero.
  1445. if (!Value.getLValueBase()) {
  1446. Result = !Value.getLValueOffset().isZero();
  1447. return true;
  1448. }
  1449. // We have a non-null base. These are generally known to be true, but if it's
  1450. // a weak declaration it can be null at runtime.
  1451. Result = true;
  1452. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1453. return !Decl || !Decl->isWeak();
  1454. }
  1455. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1456. switch (Val.getKind()) {
  1457. case APValue::Uninitialized:
  1458. return false;
  1459. case APValue::Int:
  1460. Result = Val.getInt().getBoolValue();
  1461. return true;
  1462. case APValue::Float:
  1463. Result = !Val.getFloat().isZero();
  1464. return true;
  1465. case APValue::ComplexInt:
  1466. Result = Val.getComplexIntReal().getBoolValue() ||
  1467. Val.getComplexIntImag().getBoolValue();
  1468. return true;
  1469. case APValue::ComplexFloat:
  1470. Result = !Val.getComplexFloatReal().isZero() ||
  1471. !Val.getComplexFloatImag().isZero();
  1472. return true;
  1473. case APValue::LValue:
  1474. return EvalPointerValueAsBool(Val, Result);
  1475. case APValue::MemberPointer:
  1476. Result = Val.getMemberPointerDecl();
  1477. return true;
  1478. case APValue::Vector:
  1479. case APValue::Array:
  1480. case APValue::Struct:
  1481. case APValue::Union:
  1482. case APValue::AddrLabelDiff:
  1483. return false;
  1484. }
  1485. llvm_unreachable("unknown APValue kind");
  1486. }
  1487. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1488. EvalInfo &Info) {
  1489. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1490. APValue Val;
  1491. if (!Evaluate(Val, Info, E))
  1492. return false;
  1493. return HandleConversionToBool(Val, Result);
  1494. }
  1495. template<typename T>
  1496. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1497. const T &SrcValue, QualType DestType) {
  1498. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1499. << SrcValue << DestType;
  1500. return Info.noteUndefinedBehavior();
  1501. }
  1502. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1503. QualType SrcType, const APFloat &Value,
  1504. QualType DestType, APSInt &Result) {
  1505. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1506. // Determine whether we are converting to unsigned or signed.
  1507. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1508. Result = APSInt(DestWidth, !DestSigned);
  1509. bool ignored;
  1510. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1511. & APFloat::opInvalidOp)
  1512. return HandleOverflow(Info, E, Value, DestType);
  1513. return true;
  1514. }
  1515. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1516. QualType SrcType, QualType DestType,
  1517. APFloat &Result) {
  1518. APFloat Value = Result;
  1519. bool ignored;
  1520. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1521. APFloat::rmNearestTiesToEven, &ignored)
  1522. & APFloat::opOverflow)
  1523. return HandleOverflow(Info, E, Value, DestType);
  1524. return true;
  1525. }
  1526. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1527. QualType DestType, QualType SrcType,
  1528. const APSInt &Value) {
  1529. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1530. APSInt Result = Value;
  1531. // Figure out if this is a truncate, extend or noop cast.
  1532. // If the input is signed, do a sign extend, noop, or truncate.
  1533. Result = Result.extOrTrunc(DestWidth);
  1534. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1535. return Result;
  1536. }
  1537. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1538. QualType SrcType, const APSInt &Value,
  1539. QualType DestType, APFloat &Result) {
  1540. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1541. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1542. APFloat::rmNearestTiesToEven)
  1543. & APFloat::opOverflow)
  1544. return HandleOverflow(Info, E, Value, DestType);
  1545. return true;
  1546. }
  1547. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1548. APValue &Value, const FieldDecl *FD) {
  1549. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1550. if (!Value.isInt()) {
  1551. // Trying to store a pointer-cast-to-integer into a bitfield.
  1552. // FIXME: In this case, we should provide the diagnostic for casting
  1553. // a pointer to an integer.
  1554. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1555. Info.FFDiag(E);
  1556. return false;
  1557. }
  1558. APSInt &Int = Value.getInt();
  1559. unsigned OldBitWidth = Int.getBitWidth();
  1560. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1561. if (NewBitWidth < OldBitWidth)
  1562. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1563. return true;
  1564. }
  1565. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1566. llvm::APInt &Res) {
  1567. APValue SVal;
  1568. if (!Evaluate(SVal, Info, E))
  1569. return false;
  1570. if (SVal.isInt()) {
  1571. Res = SVal.getInt();
  1572. return true;
  1573. }
  1574. if (SVal.isFloat()) {
  1575. Res = SVal.getFloat().bitcastToAPInt();
  1576. return true;
  1577. }
  1578. if (SVal.isVector()) {
  1579. QualType VecTy = E->getType();
  1580. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1581. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1582. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1583. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1584. Res = llvm::APInt::getNullValue(VecSize);
  1585. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1586. APValue &Elt = SVal.getVectorElt(i);
  1587. llvm::APInt EltAsInt;
  1588. if (Elt.isInt()) {
  1589. EltAsInt = Elt.getInt();
  1590. } else if (Elt.isFloat()) {
  1591. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1592. } else {
  1593. // Don't try to handle vectors of anything other than int or float
  1594. // (not sure if it's possible to hit this case).
  1595. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1596. return false;
  1597. }
  1598. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1599. if (BigEndian)
  1600. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1601. else
  1602. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1603. }
  1604. return true;
  1605. }
  1606. // Give up if the input isn't an int, float, or vector. For example, we
  1607. // reject "(v4i16)(intptr_t)&a".
  1608. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1609. return false;
  1610. }
  1611. /// Perform the given integer operation, which is known to need at most BitWidth
  1612. /// bits, and check for overflow in the original type (if that type was not an
  1613. /// unsigned type).
  1614. template<typename Operation>
  1615. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1616. const APSInt &LHS, const APSInt &RHS,
  1617. unsigned BitWidth, Operation Op,
  1618. APSInt &Result) {
  1619. if (LHS.isUnsigned()) {
  1620. Result = Op(LHS, RHS);
  1621. return true;
  1622. }
  1623. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1624. Result = Value.trunc(LHS.getBitWidth());
  1625. if (Result.extend(BitWidth) != Value) {
  1626. if (Info.checkingForOverflow())
  1627. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1628. diag::warn_integer_constant_overflow)
  1629. << Result.toString(10) << E->getType();
  1630. else
  1631. return HandleOverflow(Info, E, Value, E->getType());
  1632. }
  1633. return true;
  1634. }
  1635. /// Perform the given binary integer operation.
  1636. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1637. BinaryOperatorKind Opcode, APSInt RHS,
  1638. APSInt &Result) {
  1639. switch (Opcode) {
  1640. default:
  1641. Info.FFDiag(E);
  1642. return false;
  1643. case BO_Mul:
  1644. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1645. std::multiplies<APSInt>(), Result);
  1646. case BO_Add:
  1647. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1648. std::plus<APSInt>(), Result);
  1649. case BO_Sub:
  1650. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1651. std::minus<APSInt>(), Result);
  1652. case BO_And: Result = LHS & RHS; return true;
  1653. case BO_Xor: Result = LHS ^ RHS; return true;
  1654. case BO_Or: Result = LHS | RHS; return true;
  1655. case BO_Div:
  1656. case BO_Rem:
  1657. if (RHS == 0) {
  1658. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1659. return false;
  1660. }
  1661. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1662. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1663. // this operation and gives the two's complement result.
  1664. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1665. LHS.isSigned() && LHS.isMinSignedValue())
  1666. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1667. E->getType());
  1668. return true;
  1669. case BO_Shl: {
  1670. if (Info.getLangOpts().OpenCL)
  1671. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1672. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1673. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1674. RHS.isUnsigned());
  1675. else if (RHS.isSigned() && RHS.isNegative()) {
  1676. // During constant-folding, a negative shift is an opposite shift. Such
  1677. // a shift is not a constant expression.
  1678. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1679. RHS = -RHS;
  1680. goto shift_right;
  1681. }
  1682. shift_left:
  1683. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  1684. // the shifted type.
  1685. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1686. if (SA != RHS) {
  1687. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1688. << RHS << E->getType() << LHS.getBitWidth();
  1689. } else if (LHS.isSigned()) {
  1690. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  1691. // operand, and must not overflow the corresponding unsigned type.
  1692. if (LHS.isNegative())
  1693. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  1694. else if (LHS.countLeadingZeros() < SA)
  1695. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  1696. }
  1697. Result = LHS << SA;
  1698. return true;
  1699. }
  1700. case BO_Shr: {
  1701. if (Info.getLangOpts().OpenCL)
  1702. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1703. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1704. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1705. RHS.isUnsigned());
  1706. else if (RHS.isSigned() && RHS.isNegative()) {
  1707. // During constant-folding, a negative shift is an opposite shift. Such a
  1708. // shift is not a constant expression.
  1709. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  1710. RHS = -RHS;
  1711. goto shift_left;
  1712. }
  1713. shift_right:
  1714. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  1715. // shifted type.
  1716. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  1717. if (SA != RHS)
  1718. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  1719. << RHS << E->getType() << LHS.getBitWidth();
  1720. Result = LHS >> SA;
  1721. return true;
  1722. }
  1723. case BO_LT: Result = LHS < RHS; return true;
  1724. case BO_GT: Result = LHS > RHS; return true;
  1725. case BO_LE: Result = LHS <= RHS; return true;
  1726. case BO_GE: Result = LHS >= RHS; return true;
  1727. case BO_EQ: Result = LHS == RHS; return true;
  1728. case BO_NE: Result = LHS != RHS; return true;
  1729. }
  1730. }
  1731. /// Perform the given binary floating-point operation, in-place, on LHS.
  1732. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  1733. APFloat &LHS, BinaryOperatorKind Opcode,
  1734. const APFloat &RHS) {
  1735. switch (Opcode) {
  1736. default:
  1737. Info.FFDiag(E);
  1738. return false;
  1739. case BO_Mul:
  1740. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  1741. break;
  1742. case BO_Add:
  1743. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  1744. break;
  1745. case BO_Sub:
  1746. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  1747. break;
  1748. case BO_Div:
  1749. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  1750. break;
  1751. }
  1752. if (LHS.isInfinity() || LHS.isNaN()) {
  1753. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  1754. return Info.noteUndefinedBehavior();
  1755. }
  1756. return true;
  1757. }
  1758. /// Cast an lvalue referring to a base subobject to a derived class, by
  1759. /// truncating the lvalue's path to the given length.
  1760. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  1761. const RecordDecl *TruncatedType,
  1762. unsigned TruncatedElements) {
  1763. SubobjectDesignator &D = Result.Designator;
  1764. // Check we actually point to a derived class object.
  1765. if (TruncatedElements == D.Entries.size())
  1766. return true;
  1767. assert(TruncatedElements >= D.MostDerivedPathLength &&
  1768. "not casting to a derived class");
  1769. if (!Result.checkSubobject(Info, E, CSK_Derived))
  1770. return false;
  1771. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  1772. const RecordDecl *RD = TruncatedType;
  1773. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  1774. if (RD->isInvalidDecl()) return false;
  1775. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1776. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  1777. if (isVirtualBaseClass(D.Entries[I]))
  1778. Result.Offset -= Layout.getVBaseClassOffset(Base);
  1779. else
  1780. Result.Offset -= Layout.getBaseClassOffset(Base);
  1781. RD = Base;
  1782. }
  1783. D.Entries.resize(TruncatedElements);
  1784. return true;
  1785. }
  1786. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1787. const CXXRecordDecl *Derived,
  1788. const CXXRecordDecl *Base,
  1789. const ASTRecordLayout *RL = nullptr) {
  1790. if (!RL) {
  1791. if (Derived->isInvalidDecl()) return false;
  1792. RL = &Info.Ctx.getASTRecordLayout(Derived);
  1793. }
  1794. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  1795. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  1796. return true;
  1797. }
  1798. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1799. const CXXRecordDecl *DerivedDecl,
  1800. const CXXBaseSpecifier *Base) {
  1801. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  1802. if (!Base->isVirtual())
  1803. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  1804. SubobjectDesignator &D = Obj.Designator;
  1805. if (D.Invalid)
  1806. return false;
  1807. // Extract most-derived object and corresponding type.
  1808. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  1809. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  1810. return false;
  1811. // Find the virtual base class.
  1812. if (DerivedDecl->isInvalidDecl()) return false;
  1813. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  1814. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  1815. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  1816. return true;
  1817. }
  1818. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  1819. QualType Type, LValue &Result) {
  1820. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  1821. PathE = E->path_end();
  1822. PathI != PathE; ++PathI) {
  1823. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  1824. *PathI))
  1825. return false;
  1826. Type = (*PathI)->getType();
  1827. }
  1828. return true;
  1829. }
  1830. /// Update LVal to refer to the given field, which must be a member of the type
  1831. /// currently described by LVal.
  1832. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  1833. const FieldDecl *FD,
  1834. const ASTRecordLayout *RL = nullptr) {
  1835. if (!RL) {
  1836. if (FD->getParent()->isInvalidDecl()) return false;
  1837. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  1838. }
  1839. unsigned I = FD->getFieldIndex();
  1840. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  1841. LVal.addDecl(Info, E, FD);
  1842. return true;
  1843. }
  1844. /// Update LVal to refer to the given indirect field.
  1845. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  1846. LValue &LVal,
  1847. const IndirectFieldDecl *IFD) {
  1848. for (const auto *C : IFD->chain())
  1849. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  1850. return false;
  1851. return true;
  1852. }
  1853. /// Get the size of the given type in char units.
  1854. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  1855. QualType Type, CharUnits &Size) {
  1856. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  1857. // extension.
  1858. if (Type->isVoidType() || Type->isFunctionType()) {
  1859. Size = CharUnits::One();
  1860. return true;
  1861. }
  1862. if (Type->isDependentType()) {
  1863. Info.FFDiag(Loc);
  1864. return false;
  1865. }
  1866. if (!Type->isConstantSizeType()) {
  1867. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  1868. // FIXME: Better diagnostic.
  1869. Info.FFDiag(Loc);
  1870. return false;
  1871. }
  1872. Size = Info.Ctx.getTypeSizeInChars(Type);
  1873. return true;
  1874. }
  1875. /// Update a pointer value to model pointer arithmetic.
  1876. /// \param Info - Information about the ongoing evaluation.
  1877. /// \param E - The expression being evaluated, for diagnostic purposes.
  1878. /// \param LVal - The pointer value to be updated.
  1879. /// \param EltTy - The pointee type represented by LVal.
  1880. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  1881. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  1882. LValue &LVal, QualType EltTy,
  1883. int64_t Adjustment) {
  1884. CharUnits SizeOfPointee;
  1885. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  1886. return false;
  1887. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  1888. return true;
  1889. }
  1890. /// Update an lvalue to refer to a component of a complex number.
  1891. /// \param Info - Information about the ongoing evaluation.
  1892. /// \param LVal - The lvalue to be updated.
  1893. /// \param EltTy - The complex number's component type.
  1894. /// \param Imag - False for the real component, true for the imaginary.
  1895. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  1896. LValue &LVal, QualType EltTy,
  1897. bool Imag) {
  1898. if (Imag) {
  1899. CharUnits SizeOfComponent;
  1900. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  1901. return false;
  1902. LVal.Offset += SizeOfComponent;
  1903. }
  1904. LVal.addComplex(Info, E, EltTy, Imag);
  1905. return true;
  1906. }
  1907. /// Try to evaluate the initializer for a variable declaration.
  1908. ///
  1909. /// \param Info Information about the ongoing evaluation.
  1910. /// \param E An expression to be used when printing diagnostics.
  1911. /// \param VD The variable whose initializer should be obtained.
  1912. /// \param Frame The frame in which the variable was created. Must be null
  1913. /// if this variable is not local to the evaluation.
  1914. /// \param Result Filled in with a pointer to the value of the variable.
  1915. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  1916. const VarDecl *VD, CallStackFrame *Frame,
  1917. APValue *&Result) {
  1918. // If this is a parameter to an active constexpr function call, perform
  1919. // argument substitution.
  1920. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  1921. // Assume arguments of a potential constant expression are unknown
  1922. // constant expressions.
  1923. if (Info.checkingPotentialConstantExpression())
  1924. return false;
  1925. if (!Frame || !Frame->Arguments) {
  1926. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1927. return false;
  1928. }
  1929. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  1930. return true;
  1931. }
  1932. // If this is a local variable, dig out its value.
  1933. if (Frame) {
  1934. Result = Frame->getTemporary(VD);
  1935. if (!Result) {
  1936. // Assume variables referenced within a lambda's call operator that were
  1937. // not declared within the call operator are captures and during checking
  1938. // of a potential constant expression, assume they are unknown constant
  1939. // expressions.
  1940. assert(isLambdaCallOperator(Frame->Callee) &&
  1941. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  1942. "missing value for local variable");
  1943. if (Info.checkingPotentialConstantExpression())
  1944. return false;
  1945. // FIXME: implement capture evaluation during constant expr evaluation.
  1946. Info.FFDiag(E->getLocStart(),
  1947. diag::note_unimplemented_constexpr_lambda_feature_ast)
  1948. << "captures not currently allowed";
  1949. return false;
  1950. }
  1951. return true;
  1952. }
  1953. // Dig out the initializer, and use the declaration which it's attached to.
  1954. const Expr *Init = VD->getAnyInitializer(VD);
  1955. if (!Init || Init->isValueDependent()) {
  1956. // If we're checking a potential constant expression, the variable could be
  1957. // initialized later.
  1958. if (!Info.checkingPotentialConstantExpression())
  1959. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1960. return false;
  1961. }
  1962. // If we're currently evaluating the initializer of this declaration, use that
  1963. // in-flight value.
  1964. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  1965. Result = Info.EvaluatingDeclValue;
  1966. return true;
  1967. }
  1968. // Never evaluate the initializer of a weak variable. We can't be sure that
  1969. // this is the definition which will be used.
  1970. if (VD->isWeak()) {
  1971. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1972. return false;
  1973. }
  1974. // Check that we can fold the initializer. In C++, we will have already done
  1975. // this in the cases where it matters for conformance.
  1976. SmallVector<PartialDiagnosticAt, 8> Notes;
  1977. if (!VD->evaluateValue(Notes)) {
  1978. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  1979. Notes.size() + 1) << VD;
  1980. Info.Note(VD->getLocation(), diag::note_declared_at);
  1981. Info.addNotes(Notes);
  1982. return false;
  1983. } else if (!VD->checkInitIsICE()) {
  1984. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  1985. Notes.size() + 1) << VD;
  1986. Info.Note(VD->getLocation(), diag::note_declared_at);
  1987. Info.addNotes(Notes);
  1988. }
  1989. Result = VD->getEvaluatedValue();
  1990. return true;
  1991. }
  1992. static bool IsConstNonVolatile(QualType T) {
  1993. Qualifiers Quals = T.getQualifiers();
  1994. return Quals.hasConst() && !Quals.hasVolatile();
  1995. }
  1996. /// Get the base index of the given base class within an APValue representing
  1997. /// the given derived class.
  1998. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  1999. const CXXRecordDecl *Base) {
  2000. Base = Base->getCanonicalDecl();
  2001. unsigned Index = 0;
  2002. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2003. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2004. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2005. return Index;
  2006. }
  2007. llvm_unreachable("base class missing from derived class's bases list");
  2008. }
  2009. /// Extract the value of a character from a string literal.
  2010. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2011. uint64_t Index) {
  2012. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2013. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2014. Lit = PE->getFunctionName();
  2015. const StringLiteral *S = cast<StringLiteral>(Lit);
  2016. const ConstantArrayType *CAT =
  2017. Info.Ctx.getAsConstantArrayType(S->getType());
  2018. assert(CAT && "string literal isn't an array");
  2019. QualType CharType = CAT->getElementType();
  2020. assert(CharType->isIntegerType() && "unexpected character type");
  2021. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2022. CharType->isUnsignedIntegerType());
  2023. if (Index < S->getLength())
  2024. Value = S->getCodeUnit(Index);
  2025. return Value;
  2026. }
  2027. // Expand a string literal into an array of characters.
  2028. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  2029. APValue &Result) {
  2030. const StringLiteral *S = cast<StringLiteral>(Lit);
  2031. const ConstantArrayType *CAT =
  2032. Info.Ctx.getAsConstantArrayType(S->getType());
  2033. assert(CAT && "string literal isn't an array");
  2034. QualType CharType = CAT->getElementType();
  2035. assert(CharType->isIntegerType() && "unexpected character type");
  2036. unsigned Elts = CAT->getSize().getZExtValue();
  2037. Result = APValue(APValue::UninitArray(),
  2038. std::min(S->getLength(), Elts), Elts);
  2039. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2040. CharType->isUnsignedIntegerType());
  2041. if (Result.hasArrayFiller())
  2042. Result.getArrayFiller() = APValue(Value);
  2043. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2044. Value = S->getCodeUnit(I);
  2045. Result.getArrayInitializedElt(I) = APValue(Value);
  2046. }
  2047. }
  2048. // Expand an array so that it has more than Index filled elements.
  2049. static void expandArray(APValue &Array, unsigned Index) {
  2050. unsigned Size = Array.getArraySize();
  2051. assert(Index < Size);
  2052. // Always at least double the number of elements for which we store a value.
  2053. unsigned OldElts = Array.getArrayInitializedElts();
  2054. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2055. NewElts = std::min(Size, std::max(NewElts, 8u));
  2056. // Copy the data across.
  2057. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2058. for (unsigned I = 0; I != OldElts; ++I)
  2059. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2060. for (unsigned I = OldElts; I != NewElts; ++I)
  2061. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2062. if (NewValue.hasArrayFiller())
  2063. NewValue.getArrayFiller() = Array.getArrayFiller();
  2064. Array.swap(NewValue);
  2065. }
  2066. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2067. /// conversion. If it's of class type, we may assume that the copy operation
  2068. /// is trivial. Note that this is never true for a union type with fields
  2069. /// (because the copy always "reads" the active member) and always true for
  2070. /// a non-class type.
  2071. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2072. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2073. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2074. return true;
  2075. if (RD->isEmpty())
  2076. return false;
  2077. for (auto *Field : RD->fields())
  2078. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2079. return true;
  2080. for (auto &BaseSpec : RD->bases())
  2081. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2082. return true;
  2083. return false;
  2084. }
  2085. /// Diagnose an attempt to read from any unreadable field within the specified
  2086. /// type, which might be a class type.
  2087. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2088. QualType T) {
  2089. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2090. if (!RD)
  2091. return false;
  2092. if (!RD->hasMutableFields())
  2093. return false;
  2094. for (auto *Field : RD->fields()) {
  2095. // If we're actually going to read this field in some way, then it can't
  2096. // be mutable. If we're in a union, then assigning to a mutable field
  2097. // (even an empty one) can change the active member, so that's not OK.
  2098. // FIXME: Add core issue number for the union case.
  2099. if (Field->isMutable() &&
  2100. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2101. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2102. Info.Note(Field->getLocation(), diag::note_declared_at);
  2103. return true;
  2104. }
  2105. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2106. return true;
  2107. }
  2108. for (auto &BaseSpec : RD->bases())
  2109. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2110. return true;
  2111. // All mutable fields were empty, and thus not actually read.
  2112. return false;
  2113. }
  2114. /// Kinds of access we can perform on an object, for diagnostics.
  2115. enum AccessKinds {
  2116. AK_Read,
  2117. AK_Assign,
  2118. AK_Increment,
  2119. AK_Decrement
  2120. };
  2121. namespace {
  2122. /// A handle to a complete object (an object that is not a subobject of
  2123. /// another object).
  2124. struct CompleteObject {
  2125. /// The value of the complete object.
  2126. APValue *Value;
  2127. /// The type of the complete object.
  2128. QualType Type;
  2129. CompleteObject() : Value(nullptr) {}
  2130. CompleteObject(APValue *Value, QualType Type)
  2131. : Value(Value), Type(Type) {
  2132. assert(Value && "missing value for complete object");
  2133. }
  2134. explicit operator bool() const { return Value; }
  2135. };
  2136. } // end anonymous namespace
  2137. /// Find the designated sub-object of an rvalue.
  2138. template<typename SubobjectHandler>
  2139. typename SubobjectHandler::result_type
  2140. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2141. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2142. if (Sub.Invalid)
  2143. // A diagnostic will have already been produced.
  2144. return handler.failed();
  2145. if (Sub.isOnePastTheEnd()) {
  2146. if (Info.getLangOpts().CPlusPlus11)
  2147. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2148. << handler.AccessKind;
  2149. else
  2150. Info.FFDiag(E);
  2151. return handler.failed();
  2152. }
  2153. APValue *O = Obj.Value;
  2154. QualType ObjType = Obj.Type;
  2155. const FieldDecl *LastField = nullptr;
  2156. // Walk the designator's path to find the subobject.
  2157. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2158. if (O->isUninit()) {
  2159. if (!Info.checkingPotentialConstantExpression())
  2160. Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2161. return handler.failed();
  2162. }
  2163. if (I == N) {
  2164. // If we are reading an object of class type, there may still be more
  2165. // things we need to check: if there are any mutable subobjects, we
  2166. // cannot perform this read. (This only happens when performing a trivial
  2167. // copy or assignment.)
  2168. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2169. diagnoseUnreadableFields(Info, E, ObjType))
  2170. return handler.failed();
  2171. if (!handler.found(*O, ObjType))
  2172. return false;
  2173. // If we modified a bit-field, truncate it to the right width.
  2174. if (handler.AccessKind != AK_Read &&
  2175. LastField && LastField->isBitField() &&
  2176. !truncateBitfieldValue(Info, E, *O, LastField))
  2177. return false;
  2178. return true;
  2179. }
  2180. LastField = nullptr;
  2181. if (ObjType->isArrayType()) {
  2182. // Next subobject is an array element.
  2183. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2184. assert(CAT && "vla in literal type?");
  2185. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2186. if (CAT->getSize().ule(Index)) {
  2187. // Note, it should not be possible to form a pointer with a valid
  2188. // designator which points more than one past the end of the array.
  2189. if (Info.getLangOpts().CPlusPlus11)
  2190. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2191. << handler.AccessKind;
  2192. else
  2193. Info.FFDiag(E);
  2194. return handler.failed();
  2195. }
  2196. ObjType = CAT->getElementType();
  2197. // An array object is represented as either an Array APValue or as an
  2198. // LValue which refers to a string literal.
  2199. if (O->isLValue()) {
  2200. assert(I == N - 1 && "extracting subobject of character?");
  2201. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2202. if (handler.AccessKind != AK_Read)
  2203. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2204. *O);
  2205. else
  2206. return handler.foundString(*O, ObjType, Index);
  2207. }
  2208. if (O->getArrayInitializedElts() > Index)
  2209. O = &O->getArrayInitializedElt(Index);
  2210. else if (handler.AccessKind != AK_Read) {
  2211. expandArray(*O, Index);
  2212. O = &O->getArrayInitializedElt(Index);
  2213. } else
  2214. O = &O->getArrayFiller();
  2215. } else if (ObjType->isAnyComplexType()) {
  2216. // Next subobject is a complex number.
  2217. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2218. if (Index > 1) {
  2219. if (Info.getLangOpts().CPlusPlus11)
  2220. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2221. << handler.AccessKind;
  2222. else
  2223. Info.FFDiag(E);
  2224. return handler.failed();
  2225. }
  2226. bool WasConstQualified = ObjType.isConstQualified();
  2227. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2228. if (WasConstQualified)
  2229. ObjType.addConst();
  2230. assert(I == N - 1 && "extracting subobject of scalar?");
  2231. if (O->isComplexInt()) {
  2232. return handler.found(Index ? O->getComplexIntImag()
  2233. : O->getComplexIntReal(), ObjType);
  2234. } else {
  2235. assert(O->isComplexFloat());
  2236. return handler.found(Index ? O->getComplexFloatImag()
  2237. : O->getComplexFloatReal(), ObjType);
  2238. }
  2239. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2240. if (Field->isMutable() && handler.AccessKind == AK_Read) {
  2241. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2242. << Field;
  2243. Info.Note(Field->getLocation(), diag::note_declared_at);
  2244. return handler.failed();
  2245. }
  2246. // Next subobject is a class, struct or union field.
  2247. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2248. if (RD->isUnion()) {
  2249. const FieldDecl *UnionField = O->getUnionField();
  2250. if (!UnionField ||
  2251. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2252. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2253. << handler.AccessKind << Field << !UnionField << UnionField;
  2254. return handler.failed();
  2255. }
  2256. O = &O->getUnionValue();
  2257. } else
  2258. O = &O->getStructField(Field->getFieldIndex());
  2259. bool WasConstQualified = ObjType.isConstQualified();
  2260. ObjType = Field->getType();
  2261. if (WasConstQualified && !Field->isMutable())
  2262. ObjType.addConst();
  2263. if (ObjType.isVolatileQualified()) {
  2264. if (Info.getLangOpts().CPlusPlus) {
  2265. // FIXME: Include a description of the path to the volatile subobject.
  2266. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2267. << handler.AccessKind << 2 << Field;
  2268. Info.Note(Field->getLocation(), diag::note_declared_at);
  2269. } else {
  2270. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2271. }
  2272. return handler.failed();
  2273. }
  2274. LastField = Field;
  2275. } else {
  2276. // Next subobject is a base class.
  2277. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2278. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2279. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2280. bool WasConstQualified = ObjType.isConstQualified();
  2281. ObjType = Info.Ctx.getRecordType(Base);
  2282. if (WasConstQualified)
  2283. ObjType.addConst();
  2284. }
  2285. }
  2286. }
  2287. namespace {
  2288. struct ExtractSubobjectHandler {
  2289. EvalInfo &Info;
  2290. APValue &Result;
  2291. static const AccessKinds AccessKind = AK_Read;
  2292. typedef bool result_type;
  2293. bool failed() { return false; }
  2294. bool found(APValue &Subobj, QualType SubobjType) {
  2295. Result = Subobj;
  2296. return true;
  2297. }
  2298. bool found(APSInt &Value, QualType SubobjType) {
  2299. Result = APValue(Value);
  2300. return true;
  2301. }
  2302. bool found(APFloat &Value, QualType SubobjType) {
  2303. Result = APValue(Value);
  2304. return true;
  2305. }
  2306. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2307. Result = APValue(extractStringLiteralCharacter(
  2308. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2309. return true;
  2310. }
  2311. };
  2312. } // end anonymous namespace
  2313. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2314. /// Extract the designated sub-object of an rvalue.
  2315. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2316. const CompleteObject &Obj,
  2317. const SubobjectDesignator &Sub,
  2318. APValue &Result) {
  2319. ExtractSubobjectHandler Handler = { Info, Result };
  2320. return findSubobject(Info, E, Obj, Sub, Handler);
  2321. }
  2322. namespace {
  2323. struct ModifySubobjectHandler {
  2324. EvalInfo &Info;
  2325. APValue &NewVal;
  2326. const Expr *E;
  2327. typedef bool result_type;
  2328. static const AccessKinds AccessKind = AK_Assign;
  2329. bool checkConst(QualType QT) {
  2330. // Assigning to a const object has undefined behavior.
  2331. if (QT.isConstQualified()) {
  2332. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2333. return false;
  2334. }
  2335. return true;
  2336. }
  2337. bool failed() { return false; }
  2338. bool found(APValue &Subobj, QualType SubobjType) {
  2339. if (!checkConst(SubobjType))
  2340. return false;
  2341. // We've been given ownership of NewVal, so just swap it in.
  2342. Subobj.swap(NewVal);
  2343. return true;
  2344. }
  2345. bool found(APSInt &Value, QualType SubobjType) {
  2346. if (!checkConst(SubobjType))
  2347. return false;
  2348. if (!NewVal.isInt()) {
  2349. // Maybe trying to write a cast pointer value into a complex?
  2350. Info.FFDiag(E);
  2351. return false;
  2352. }
  2353. Value = NewVal.getInt();
  2354. return true;
  2355. }
  2356. bool found(APFloat &Value, QualType SubobjType) {
  2357. if (!checkConst(SubobjType))
  2358. return false;
  2359. Value = NewVal.getFloat();
  2360. return true;
  2361. }
  2362. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2363. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2364. }
  2365. };
  2366. } // end anonymous namespace
  2367. const AccessKinds ModifySubobjectHandler::AccessKind;
  2368. /// Update the designated sub-object of an rvalue to the given value.
  2369. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2370. const CompleteObject &Obj,
  2371. const SubobjectDesignator &Sub,
  2372. APValue &NewVal) {
  2373. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2374. return findSubobject(Info, E, Obj, Sub, Handler);
  2375. }
  2376. /// Find the position where two subobject designators diverge, or equivalently
  2377. /// the length of the common initial subsequence.
  2378. static unsigned FindDesignatorMismatch(QualType ObjType,
  2379. const SubobjectDesignator &A,
  2380. const SubobjectDesignator &B,
  2381. bool &WasArrayIndex) {
  2382. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2383. for (/**/; I != N; ++I) {
  2384. if (!ObjType.isNull() &&
  2385. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2386. // Next subobject is an array element.
  2387. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2388. WasArrayIndex = true;
  2389. return I;
  2390. }
  2391. if (ObjType->isAnyComplexType())
  2392. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2393. else
  2394. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2395. } else {
  2396. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2397. WasArrayIndex = false;
  2398. return I;
  2399. }
  2400. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2401. // Next subobject is a field.
  2402. ObjType = FD->getType();
  2403. else
  2404. // Next subobject is a base class.
  2405. ObjType = QualType();
  2406. }
  2407. }
  2408. WasArrayIndex = false;
  2409. return I;
  2410. }
  2411. /// Determine whether the given subobject designators refer to elements of the
  2412. /// same array object.
  2413. static bool AreElementsOfSameArray(QualType ObjType,
  2414. const SubobjectDesignator &A,
  2415. const SubobjectDesignator &B) {
  2416. if (A.Entries.size() != B.Entries.size())
  2417. return false;
  2418. bool IsArray = A.MostDerivedIsArrayElement;
  2419. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2420. // A is a subobject of the array element.
  2421. return false;
  2422. // If A (and B) designates an array element, the last entry will be the array
  2423. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2424. // of length 1' case, and the entire path must match.
  2425. bool WasArrayIndex;
  2426. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2427. return CommonLength >= A.Entries.size() - IsArray;
  2428. }
  2429. /// Find the complete object to which an LValue refers.
  2430. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2431. AccessKinds AK, const LValue &LVal,
  2432. QualType LValType) {
  2433. if (!LVal.Base) {
  2434. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2435. return CompleteObject();
  2436. }
  2437. CallStackFrame *Frame = nullptr;
  2438. if (LVal.CallIndex) {
  2439. Frame = Info.getCallFrame(LVal.CallIndex);
  2440. if (!Frame) {
  2441. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2442. << AK << LVal.Base.is<const ValueDecl*>();
  2443. NoteLValueLocation(Info, LVal.Base);
  2444. return CompleteObject();
  2445. }
  2446. }
  2447. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2448. // is not a constant expression (even if the object is non-volatile). We also
  2449. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2450. // semantics.
  2451. if (LValType.isVolatileQualified()) {
  2452. if (Info.getLangOpts().CPlusPlus)
  2453. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2454. << AK << LValType;
  2455. else
  2456. Info.FFDiag(E);
  2457. return CompleteObject();
  2458. }
  2459. // Compute value storage location and type of base object.
  2460. APValue *BaseVal = nullptr;
  2461. QualType BaseType = getType(LVal.Base);
  2462. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2463. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2464. // In C++11, constexpr, non-volatile variables initialized with constant
  2465. // expressions are constant expressions too. Inside constexpr functions,
  2466. // parameters are constant expressions even if they're non-const.
  2467. // In C++1y, objects local to a constant expression (those with a Frame) are
  2468. // both readable and writable inside constant expressions.
  2469. // In C, such things can also be folded, although they are not ICEs.
  2470. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2471. if (VD) {
  2472. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2473. VD = VDef;
  2474. }
  2475. if (!VD || VD->isInvalidDecl()) {
  2476. Info.FFDiag(E);
  2477. return CompleteObject();
  2478. }
  2479. // Accesses of volatile-qualified objects are not allowed.
  2480. if (BaseType.isVolatileQualified()) {
  2481. if (Info.getLangOpts().CPlusPlus) {
  2482. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2483. << AK << 1 << VD;
  2484. Info.Note(VD->getLocation(), diag::note_declared_at);
  2485. } else {
  2486. Info.FFDiag(E);
  2487. }
  2488. return CompleteObject();
  2489. }
  2490. // Unless we're looking at a local variable or argument in a constexpr call,
  2491. // the variable we're reading must be const.
  2492. if (!Frame) {
  2493. if (Info.getLangOpts().CPlusPlus14 &&
  2494. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2495. // OK, we can read and modify an object if we're in the process of
  2496. // evaluating its initializer, because its lifetime began in this
  2497. // evaluation.
  2498. } else if (AK != AK_Read) {
  2499. // All the remaining cases only permit reading.
  2500. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2501. return CompleteObject();
  2502. } else if (VD->isConstexpr()) {
  2503. // OK, we can read this variable.
  2504. } else if (BaseType->isIntegralOrEnumerationType()) {
  2505. // In OpenCL if a variable is in constant address space it is a const value.
  2506. if (!(BaseType.isConstQualified() ||
  2507. (Info.getLangOpts().OpenCL &&
  2508. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2509. if (Info.getLangOpts().CPlusPlus) {
  2510. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2511. Info.Note(VD->getLocation(), diag::note_declared_at);
  2512. } else {
  2513. Info.FFDiag(E);
  2514. }
  2515. return CompleteObject();
  2516. }
  2517. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2518. // We support folding of const floating-point types, in order to make
  2519. // static const data members of such types (supported as an extension)
  2520. // more useful.
  2521. if (Info.getLangOpts().CPlusPlus11) {
  2522. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2523. Info.Note(VD->getLocation(), diag::note_declared_at);
  2524. } else {
  2525. Info.CCEDiag(E);
  2526. }
  2527. } else {
  2528. // FIXME: Allow folding of values of any literal type in all languages.
  2529. if (Info.checkingPotentialConstantExpression() &&
  2530. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2531. // The definition of this variable could be constexpr. We can't
  2532. // access it right now, but may be able to in future.
  2533. } else if (Info.getLangOpts().CPlusPlus11) {
  2534. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2535. Info.Note(VD->getLocation(), diag::note_declared_at);
  2536. } else {
  2537. Info.FFDiag(E);
  2538. }
  2539. return CompleteObject();
  2540. }
  2541. }
  2542. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
  2543. return CompleteObject();
  2544. } else {
  2545. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2546. if (!Frame) {
  2547. if (const MaterializeTemporaryExpr *MTE =
  2548. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2549. assert(MTE->getStorageDuration() == SD_Static &&
  2550. "should have a frame for a non-global materialized temporary");
  2551. // Per C++1y [expr.const]p2:
  2552. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2553. // - a [...] glvalue of integral or enumeration type that refers to
  2554. // a non-volatile const object [...]
  2555. // [...]
  2556. // - a [...] glvalue of literal type that refers to a non-volatile
  2557. // object whose lifetime began within the evaluation of e.
  2558. //
  2559. // C++11 misses the 'began within the evaluation of e' check and
  2560. // instead allows all temporaries, including things like:
  2561. // int &&r = 1;
  2562. // int x = ++r;
  2563. // constexpr int k = r;
  2564. // Therefore we use the C++1y rules in C++11 too.
  2565. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2566. const ValueDecl *ED = MTE->getExtendingDecl();
  2567. if (!(BaseType.isConstQualified() &&
  2568. BaseType->isIntegralOrEnumerationType()) &&
  2569. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2570. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2571. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2572. return CompleteObject();
  2573. }
  2574. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2575. assert(BaseVal && "got reference to unevaluated temporary");
  2576. } else {
  2577. Info.FFDiag(E);
  2578. return CompleteObject();
  2579. }
  2580. } else {
  2581. BaseVal = Frame->getTemporary(Base);
  2582. assert(BaseVal && "missing value for temporary");
  2583. }
  2584. // Volatile temporary objects cannot be accessed in constant expressions.
  2585. if (BaseType.isVolatileQualified()) {
  2586. if (Info.getLangOpts().CPlusPlus) {
  2587. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2588. << AK << 0;
  2589. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2590. } else {
  2591. Info.FFDiag(E);
  2592. }
  2593. return CompleteObject();
  2594. }
  2595. }
  2596. // During the construction of an object, it is not yet 'const'.
  2597. // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
  2598. // and this doesn't do quite the right thing for const subobjects of the
  2599. // object under construction.
  2600. if (LVal.getLValueBase() == Info.EvaluatingDecl) {
  2601. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2602. BaseType.removeLocalConst();
  2603. }
  2604. // In C++1y, we can't safely access any mutable state when we might be
  2605. // evaluating after an unmodeled side effect.
  2606. //
  2607. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2608. // to be read here (but take care with 'mutable' fields).
  2609. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2610. Info.EvalStatus.HasSideEffects) ||
  2611. (AK != AK_Read && Info.IsSpeculativelyEvaluating))
  2612. return CompleteObject();
  2613. return CompleteObject(BaseVal, BaseType);
  2614. }
  2615. /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2616. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2617. /// glvalue referred to by an entity of reference type.
  2618. ///
  2619. /// \param Info - Information about the ongoing evaluation.
  2620. /// \param Conv - The expression for which we are performing the conversion.
  2621. /// Used for diagnostics.
  2622. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2623. /// case of a non-class type).
  2624. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2625. /// \param RVal - The produced value will be placed here.
  2626. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2627. QualType Type,
  2628. const LValue &LVal, APValue &RVal) {
  2629. if (LVal.Designator.Invalid)
  2630. return false;
  2631. // Check for special cases where there is no existing APValue to look at.
  2632. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2633. if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
  2634. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2635. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2636. // initializer until now for such expressions. Such an expression can't be
  2637. // an ICE in C, so this only matters for fold.
  2638. if (Type.isVolatileQualified()) {
  2639. Info.FFDiag(Conv);
  2640. return false;
  2641. }
  2642. APValue Lit;
  2643. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  2644. return false;
  2645. CompleteObject LitObj(&Lit, Base->getType());
  2646. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  2647. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  2648. // We represent a string literal array as an lvalue pointing at the
  2649. // corresponding expression, rather than building an array of chars.
  2650. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  2651. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  2652. CompleteObject StrObj(&Str, Base->getType());
  2653. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  2654. }
  2655. }
  2656. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  2657. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  2658. }
  2659. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  2660. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2661. QualType LValType, APValue &Val) {
  2662. if (LVal.Designator.Invalid)
  2663. return false;
  2664. if (!Info.getLangOpts().CPlusPlus14) {
  2665. Info.FFDiag(E);
  2666. return false;
  2667. }
  2668. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2669. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  2670. }
  2671. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  2672. return T->isSignedIntegerType() &&
  2673. Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  2674. }
  2675. namespace {
  2676. struct CompoundAssignSubobjectHandler {
  2677. EvalInfo &Info;
  2678. const Expr *E;
  2679. QualType PromotedLHSType;
  2680. BinaryOperatorKind Opcode;
  2681. const APValue &RHS;
  2682. static const AccessKinds AccessKind = AK_Assign;
  2683. typedef bool result_type;
  2684. bool checkConst(QualType QT) {
  2685. // Assigning to a const object has undefined behavior.
  2686. if (QT.isConstQualified()) {
  2687. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2688. return false;
  2689. }
  2690. return true;
  2691. }
  2692. bool failed() { return false; }
  2693. bool found(APValue &Subobj, QualType SubobjType) {
  2694. switch (Subobj.getKind()) {
  2695. case APValue::Int:
  2696. return found(Subobj.getInt(), SubobjType);
  2697. case APValue::Float:
  2698. return found(Subobj.getFloat(), SubobjType);
  2699. case APValue::ComplexInt:
  2700. case APValue::ComplexFloat:
  2701. // FIXME: Implement complex compound assignment.
  2702. Info.FFDiag(E);
  2703. return false;
  2704. case APValue::LValue:
  2705. return foundPointer(Subobj, SubobjType);
  2706. default:
  2707. // FIXME: can this happen?
  2708. Info.FFDiag(E);
  2709. return false;
  2710. }
  2711. }
  2712. bool found(APSInt &Value, QualType SubobjType) {
  2713. if (!checkConst(SubobjType))
  2714. return false;
  2715. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  2716. // We don't support compound assignment on integer-cast-to-pointer
  2717. // values.
  2718. Info.FFDiag(E);
  2719. return false;
  2720. }
  2721. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  2722. SubobjType, Value);
  2723. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  2724. return false;
  2725. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  2726. return true;
  2727. }
  2728. bool found(APFloat &Value, QualType SubobjType) {
  2729. return checkConst(SubobjType) &&
  2730. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  2731. Value) &&
  2732. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  2733. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  2734. }
  2735. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  2736. if (!checkConst(SubobjType))
  2737. return false;
  2738. QualType PointeeType;
  2739. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  2740. PointeeType = PT->getPointeeType();
  2741. if (PointeeType.isNull() || !RHS.isInt() ||
  2742. (Opcode != BO_Add && Opcode != BO_Sub)) {
  2743. Info.FFDiag(E);
  2744. return false;
  2745. }
  2746. int64_t Offset = getExtValue(RHS.getInt());
  2747. if (Opcode == BO_Sub)
  2748. Offset = -Offset;
  2749. LValue LVal;
  2750. LVal.setFrom(Info.Ctx, Subobj);
  2751. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  2752. return false;
  2753. LVal.moveInto(Subobj);
  2754. return true;
  2755. }
  2756. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2757. llvm_unreachable("shouldn't encounter string elements here");
  2758. }
  2759. };
  2760. } // end anonymous namespace
  2761. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  2762. /// Perform a compound assignment of LVal <op>= RVal.
  2763. static bool handleCompoundAssignment(
  2764. EvalInfo &Info, const Expr *E,
  2765. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  2766. BinaryOperatorKind Opcode, const APValue &RVal) {
  2767. if (LVal.Designator.Invalid)
  2768. return false;
  2769. if (!Info.getLangOpts().CPlusPlus14) {
  2770. Info.FFDiag(E);
  2771. return false;
  2772. }
  2773. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  2774. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  2775. RVal };
  2776. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  2777. }
  2778. namespace {
  2779. struct IncDecSubobjectHandler {
  2780. EvalInfo &Info;
  2781. const Expr *E;
  2782. AccessKinds AccessKind;
  2783. APValue *Old;
  2784. typedef bool result_type;
  2785. bool checkConst(QualType QT) {
  2786. // Assigning to a const object has undefined behavior.
  2787. if (QT.isConstQualified()) {
  2788. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2789. return false;
  2790. }
  2791. return true;
  2792. }
  2793. bool failed() { return false; }
  2794. bool found(APValue &Subobj, QualType SubobjType) {
  2795. // Stash the old value. Also clear Old, so we don't clobber it later
  2796. // if we're post-incrementing a complex.
  2797. if (Old) {
  2798. *Old = Subobj;
  2799. Old = nullptr;
  2800. }
  2801. switch (Subobj.getKind()) {
  2802. case APValue::Int:
  2803. return found(Subobj.getInt(), SubobjType);
  2804. case APValue::Float:
  2805. return found(Subobj.getFloat(), SubobjType);
  2806. case APValue::ComplexInt:
  2807. return found(Subobj.getComplexIntReal(),
  2808. SubobjType->castAs<ComplexType>()->getElementType()
  2809. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  2810. case APValue::ComplexFloat:
  2811. return found(Subobj.getComplexFloatReal(),
  2812. SubobjType->castAs<ComplexType>()->getElementType()
  2813. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  2814. case APValue::LValue:
  2815. return foundPointer(Subobj, SubobjType);
  2816. default:
  2817. // FIXME: can this happen?
  2818. Info.FFDiag(E);
  2819. return false;
  2820. }
  2821. }
  2822. bool found(APSInt &Value, QualType SubobjType) {
  2823. if (!checkConst(SubobjType))
  2824. return false;
  2825. if (!SubobjType->isIntegerType()) {
  2826. // We don't support increment / decrement on integer-cast-to-pointer
  2827. // values.
  2828. Info.FFDiag(E);
  2829. return false;
  2830. }
  2831. if (Old) *Old = APValue(Value);
  2832. // bool arithmetic promotes to int, and the conversion back to bool
  2833. // doesn't reduce mod 2^n, so special-case it.
  2834. if (SubobjType->isBooleanType()) {
  2835. if (AccessKind == AK_Increment)
  2836. Value = 1;
  2837. else
  2838. Value = !Value;
  2839. return true;
  2840. }
  2841. bool WasNegative = Value.isNegative();
  2842. if (AccessKind == AK_Increment) {
  2843. ++Value;
  2844. if (!WasNegative && Value.isNegative() &&
  2845. isOverflowingIntegerType(Info.Ctx, SubobjType)) {
  2846. APSInt ActualValue(Value, /*IsUnsigned*/true);
  2847. return HandleOverflow(Info, E, ActualValue, SubobjType);
  2848. }
  2849. } else {
  2850. --Value;
  2851. if (WasNegative && !Value.isNegative() &&
  2852. isOverflowingIntegerType(Info.Ctx, SubobjType)) {
  2853. unsigned BitWidth = Value.getBitWidth();
  2854. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  2855. ActualValue.setBit(BitWidth);
  2856. return HandleOverflow(Info, E, ActualValue, SubobjType);
  2857. }
  2858. }
  2859. return true;
  2860. }
  2861. bool found(APFloat &Value, QualType SubobjType) {
  2862. if (!checkConst(SubobjType))
  2863. return false;
  2864. if (Old) *Old = APValue(Value);
  2865. APFloat One(Value.getSemantics(), 1);
  2866. if (AccessKind == AK_Increment)
  2867. Value.add(One, APFloat::rmNearestTiesToEven);
  2868. else
  2869. Value.subtract(One, APFloat::rmNearestTiesToEven);
  2870. return true;
  2871. }
  2872. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  2873. if (!checkConst(SubobjType))
  2874. return false;
  2875. QualType PointeeType;
  2876. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  2877. PointeeType = PT->getPointeeType();
  2878. else {
  2879. Info.FFDiag(E);
  2880. return false;
  2881. }
  2882. LValue LVal;
  2883. LVal.setFrom(Info.Ctx, Subobj);
  2884. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  2885. AccessKind == AK_Increment ? 1 : -1))
  2886. return false;
  2887. LVal.moveInto(Subobj);
  2888. return true;
  2889. }
  2890. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2891. llvm_unreachable("shouldn't encounter string elements here");
  2892. }
  2893. };
  2894. } // end anonymous namespace
  2895. /// Perform an increment or decrement on LVal.
  2896. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  2897. QualType LValType, bool IsIncrement, APValue *Old) {
  2898. if (LVal.Designator.Invalid)
  2899. return false;
  2900. if (!Info.getLangOpts().CPlusPlus14) {
  2901. Info.FFDiag(E);
  2902. return false;
  2903. }
  2904. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  2905. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  2906. IncDecSubobjectHandler Handler = { Info, E, AK, Old };
  2907. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  2908. }
  2909. /// Build an lvalue for the object argument of a member function call.
  2910. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  2911. LValue &This) {
  2912. if (Object->getType()->isPointerType())
  2913. return EvaluatePointer(Object, This, Info);
  2914. if (Object->isGLValue())
  2915. return EvaluateLValue(Object, This, Info);
  2916. if (Object->getType()->isLiteralType(Info.Ctx))
  2917. return EvaluateTemporary(Object, This, Info);
  2918. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  2919. return false;
  2920. }
  2921. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  2922. /// lvalue referring to the result.
  2923. ///
  2924. /// \param Info - Information about the ongoing evaluation.
  2925. /// \param LV - An lvalue referring to the base of the member pointer.
  2926. /// \param RHS - The member pointer expression.
  2927. /// \param IncludeMember - Specifies whether the member itself is included in
  2928. /// the resulting LValue subobject designator. This is not possible when
  2929. /// creating a bound member function.
  2930. /// \return The field or method declaration to which the member pointer refers,
  2931. /// or 0 if evaluation fails.
  2932. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  2933. QualType LVType,
  2934. LValue &LV,
  2935. const Expr *RHS,
  2936. bool IncludeMember = true) {
  2937. MemberPtr MemPtr;
  2938. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  2939. return nullptr;
  2940. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  2941. // member value, the behavior is undefined.
  2942. if (!MemPtr.getDecl()) {
  2943. // FIXME: Specific diagnostic.
  2944. Info.FFDiag(RHS);
  2945. return nullptr;
  2946. }
  2947. if (MemPtr.isDerivedMember()) {
  2948. // This is a member of some derived class. Truncate LV appropriately.
  2949. // The end of the derived-to-base path for the base object must match the
  2950. // derived-to-base path for the member pointer.
  2951. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  2952. LV.Designator.Entries.size()) {
  2953. Info.FFDiag(RHS);
  2954. return nullptr;
  2955. }
  2956. unsigned PathLengthToMember =
  2957. LV.Designator.Entries.size() - MemPtr.Path.size();
  2958. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  2959. const CXXRecordDecl *LVDecl = getAsBaseClass(
  2960. LV.Designator.Entries[PathLengthToMember + I]);
  2961. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  2962. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  2963. Info.FFDiag(RHS);
  2964. return nullptr;
  2965. }
  2966. }
  2967. // Truncate the lvalue to the appropriate derived class.
  2968. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  2969. PathLengthToMember))
  2970. return nullptr;
  2971. } else if (!MemPtr.Path.empty()) {
  2972. // Extend the LValue path with the member pointer's path.
  2973. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  2974. MemPtr.Path.size() + IncludeMember);
  2975. // Walk down to the appropriate base class.
  2976. if (const PointerType *PT = LVType->getAs<PointerType>())
  2977. LVType = PT->getPointeeType();
  2978. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  2979. assert(RD && "member pointer access on non-class-type expression");
  2980. // The first class in the path is that of the lvalue.
  2981. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  2982. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  2983. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  2984. return nullptr;
  2985. RD = Base;
  2986. }
  2987. // Finally cast to the class containing the member.
  2988. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  2989. MemPtr.getContainingRecord()))
  2990. return nullptr;
  2991. }
  2992. // Add the member. Note that we cannot build bound member functions here.
  2993. if (IncludeMember) {
  2994. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  2995. if (!HandleLValueMember(Info, RHS, LV, FD))
  2996. return nullptr;
  2997. } else if (const IndirectFieldDecl *IFD =
  2998. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  2999. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3000. return nullptr;
  3001. } else {
  3002. llvm_unreachable("can't construct reference to bound member function");
  3003. }
  3004. }
  3005. return MemPtr.getDecl();
  3006. }
  3007. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3008. const BinaryOperator *BO,
  3009. LValue &LV,
  3010. bool IncludeMember = true) {
  3011. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3012. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3013. if (Info.noteFailure()) {
  3014. MemberPtr MemPtr;
  3015. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3016. }
  3017. return nullptr;
  3018. }
  3019. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3020. BO->getRHS(), IncludeMember);
  3021. }
  3022. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3023. /// the provided lvalue, which currently refers to the base object.
  3024. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3025. LValue &Result) {
  3026. SubobjectDesignator &D = Result.Designator;
  3027. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3028. return false;
  3029. QualType TargetQT = E->getType();
  3030. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3031. TargetQT = PT->getPointeeType();
  3032. // Check this cast lands within the final derived-to-base subobject path.
  3033. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3034. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3035. << D.MostDerivedType << TargetQT;
  3036. return false;
  3037. }
  3038. // Check the type of the final cast. We don't need to check the path,
  3039. // since a cast can only be formed if the path is unique.
  3040. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3041. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3042. const CXXRecordDecl *FinalType;
  3043. if (NewEntriesSize == D.MostDerivedPathLength)
  3044. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3045. else
  3046. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3047. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3048. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3049. << D.MostDerivedType << TargetQT;
  3050. return false;
  3051. }
  3052. // Truncate the lvalue to the appropriate derived class.
  3053. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3054. }
  3055. namespace {
  3056. enum EvalStmtResult {
  3057. /// Evaluation failed.
  3058. ESR_Failed,
  3059. /// Hit a 'return' statement.
  3060. ESR_Returned,
  3061. /// Evaluation succeeded.
  3062. ESR_Succeeded,
  3063. /// Hit a 'continue' statement.
  3064. ESR_Continue,
  3065. /// Hit a 'break' statement.
  3066. ESR_Break,
  3067. /// Still scanning for 'case' or 'default' statement.
  3068. ESR_CaseNotFound
  3069. };
  3070. }
  3071. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3072. // We don't need to evaluate the initializer for a static local.
  3073. if (!VD->hasLocalStorage())
  3074. return true;
  3075. LValue Result;
  3076. Result.set(VD, Info.CurrentCall->Index);
  3077. APValue &Val = Info.CurrentCall->createTemporary(VD, true);
  3078. const Expr *InitE = VD->getInit();
  3079. if (!InitE) {
  3080. Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
  3081. << false << VD->getType();
  3082. Val = APValue();
  3083. return false;
  3084. }
  3085. if (InitE->isValueDependent())
  3086. return false;
  3087. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3088. // Wipe out any partially-computed value, to allow tracking that this
  3089. // evaluation failed.
  3090. Val = APValue();
  3091. return false;
  3092. }
  3093. return true;
  3094. }
  3095. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3096. bool OK = true;
  3097. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3098. OK &= EvaluateVarDecl(Info, VD);
  3099. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3100. for (auto *BD : DD->bindings())
  3101. if (auto *VD = BD->getHoldingVar())
  3102. OK &= EvaluateDecl(Info, VD);
  3103. return OK;
  3104. }
  3105. /// Evaluate a condition (either a variable declaration or an expression).
  3106. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3107. const Expr *Cond, bool &Result) {
  3108. FullExpressionRAII Scope(Info);
  3109. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3110. return false;
  3111. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3112. }
  3113. namespace {
  3114. /// \brief A location where the result (returned value) of evaluating a
  3115. /// statement should be stored.
  3116. struct StmtResult {
  3117. /// The APValue that should be filled in with the returned value.
  3118. APValue &Value;
  3119. /// The location containing the result, if any (used to support RVO).
  3120. const LValue *Slot;
  3121. };
  3122. }
  3123. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3124. const Stmt *S,
  3125. const SwitchCase *SC = nullptr);
  3126. /// Evaluate the body of a loop, and translate the result as appropriate.
  3127. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3128. const Stmt *Body,
  3129. const SwitchCase *Case = nullptr) {
  3130. BlockScopeRAII Scope(Info);
  3131. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3132. case ESR_Break:
  3133. return ESR_Succeeded;
  3134. case ESR_Succeeded:
  3135. case ESR_Continue:
  3136. return ESR_Continue;
  3137. case ESR_Failed:
  3138. case ESR_Returned:
  3139. case ESR_CaseNotFound:
  3140. return ESR;
  3141. }
  3142. llvm_unreachable("Invalid EvalStmtResult!");
  3143. }
  3144. /// Evaluate a switch statement.
  3145. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3146. const SwitchStmt *SS) {
  3147. BlockScopeRAII Scope(Info);
  3148. // Evaluate the switch condition.
  3149. APSInt Value;
  3150. {
  3151. FullExpressionRAII Scope(Info);
  3152. if (const Stmt *Init = SS->getInit()) {
  3153. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3154. if (ESR != ESR_Succeeded)
  3155. return ESR;
  3156. }
  3157. if (SS->getConditionVariable() &&
  3158. !EvaluateDecl(Info, SS->getConditionVariable()))
  3159. return ESR_Failed;
  3160. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3161. return ESR_Failed;
  3162. }
  3163. // Find the switch case corresponding to the value of the condition.
  3164. // FIXME: Cache this lookup.
  3165. const SwitchCase *Found = nullptr;
  3166. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3167. SC = SC->getNextSwitchCase()) {
  3168. if (isa<DefaultStmt>(SC)) {
  3169. Found = SC;
  3170. continue;
  3171. }
  3172. const CaseStmt *CS = cast<CaseStmt>(SC);
  3173. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3174. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3175. : LHS;
  3176. if (LHS <= Value && Value <= RHS) {
  3177. Found = SC;
  3178. break;
  3179. }
  3180. }
  3181. if (!Found)
  3182. return ESR_Succeeded;
  3183. // Search the switch body for the switch case and evaluate it from there.
  3184. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3185. case ESR_Break:
  3186. return ESR_Succeeded;
  3187. case ESR_Succeeded:
  3188. case ESR_Continue:
  3189. case ESR_Failed:
  3190. case ESR_Returned:
  3191. return ESR;
  3192. case ESR_CaseNotFound:
  3193. // This can only happen if the switch case is nested within a statement
  3194. // expression. We have no intention of supporting that.
  3195. Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
  3196. return ESR_Failed;
  3197. }
  3198. llvm_unreachable("Invalid EvalStmtResult!");
  3199. }
  3200. // Evaluate a statement.
  3201. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3202. const Stmt *S, const SwitchCase *Case) {
  3203. if (!Info.nextStep(S))
  3204. return ESR_Failed;
  3205. // If we're hunting down a 'case' or 'default' label, recurse through
  3206. // substatements until we hit the label.
  3207. if (Case) {
  3208. // FIXME: We don't start the lifetime of objects whose initialization we
  3209. // jump over. However, such objects must be of class type with a trivial
  3210. // default constructor that initialize all subobjects, so must be empty,
  3211. // so this almost never matters.
  3212. switch (S->getStmtClass()) {
  3213. case Stmt::CompoundStmtClass:
  3214. // FIXME: Precompute which substatement of a compound statement we
  3215. // would jump to, and go straight there rather than performing a
  3216. // linear scan each time.
  3217. case Stmt::LabelStmtClass:
  3218. case Stmt::AttributedStmtClass:
  3219. case Stmt::DoStmtClass:
  3220. break;
  3221. case Stmt::CaseStmtClass:
  3222. case Stmt::DefaultStmtClass:
  3223. if (Case == S)
  3224. Case = nullptr;
  3225. break;
  3226. case Stmt::IfStmtClass: {
  3227. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3228. // straight there rather than scanning both sides.
  3229. const IfStmt *IS = cast<IfStmt>(S);
  3230. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3231. // preceded by our switch label.
  3232. BlockScopeRAII Scope(Info);
  3233. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3234. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3235. return ESR;
  3236. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3237. }
  3238. case Stmt::WhileStmtClass: {
  3239. EvalStmtResult ESR =
  3240. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3241. if (ESR != ESR_Continue)
  3242. return ESR;
  3243. break;
  3244. }
  3245. case Stmt::ForStmtClass: {
  3246. const ForStmt *FS = cast<ForStmt>(S);
  3247. EvalStmtResult ESR =
  3248. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3249. if (ESR != ESR_Continue)
  3250. return ESR;
  3251. if (FS->getInc()) {
  3252. FullExpressionRAII IncScope(Info);
  3253. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3254. return ESR_Failed;
  3255. }
  3256. break;
  3257. }
  3258. case Stmt::DeclStmtClass:
  3259. // FIXME: If the variable has initialization that can't be jumped over,
  3260. // bail out of any immediately-surrounding compound-statement too.
  3261. default:
  3262. return ESR_CaseNotFound;
  3263. }
  3264. }
  3265. switch (S->getStmtClass()) {
  3266. default:
  3267. if (const Expr *E = dyn_cast<Expr>(S)) {
  3268. // Don't bother evaluating beyond an expression-statement which couldn't
  3269. // be evaluated.
  3270. FullExpressionRAII Scope(Info);
  3271. if (!EvaluateIgnoredValue(Info, E))
  3272. return ESR_Failed;
  3273. return ESR_Succeeded;
  3274. }
  3275. Info.FFDiag(S->getLocStart());
  3276. return ESR_Failed;
  3277. case Stmt::NullStmtClass:
  3278. return ESR_Succeeded;
  3279. case Stmt::DeclStmtClass: {
  3280. const DeclStmt *DS = cast<DeclStmt>(S);
  3281. for (const auto *DclIt : DS->decls()) {
  3282. // Each declaration initialization is its own full-expression.
  3283. // FIXME: This isn't quite right; if we're performing aggregate
  3284. // initialization, each braced subexpression is its own full-expression.
  3285. FullExpressionRAII Scope(Info);
  3286. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3287. return ESR_Failed;
  3288. }
  3289. return ESR_Succeeded;
  3290. }
  3291. case Stmt::ReturnStmtClass: {
  3292. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3293. FullExpressionRAII Scope(Info);
  3294. if (RetExpr &&
  3295. !(Result.Slot
  3296. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3297. : Evaluate(Result.Value, Info, RetExpr)))
  3298. return ESR_Failed;
  3299. return ESR_Returned;
  3300. }
  3301. case Stmt::CompoundStmtClass: {
  3302. BlockScopeRAII Scope(Info);
  3303. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3304. for (const auto *BI : CS->body()) {
  3305. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3306. if (ESR == ESR_Succeeded)
  3307. Case = nullptr;
  3308. else if (ESR != ESR_CaseNotFound)
  3309. return ESR;
  3310. }
  3311. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3312. }
  3313. case Stmt::IfStmtClass: {
  3314. const IfStmt *IS = cast<IfStmt>(S);
  3315. // Evaluate the condition, as either a var decl or as an expression.
  3316. BlockScopeRAII Scope(Info);
  3317. if (const Stmt *Init = IS->getInit()) {
  3318. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3319. if (ESR != ESR_Succeeded)
  3320. return ESR;
  3321. }
  3322. bool Cond;
  3323. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3324. return ESR_Failed;
  3325. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3326. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3327. if (ESR != ESR_Succeeded)
  3328. return ESR;
  3329. }
  3330. return ESR_Succeeded;
  3331. }
  3332. case Stmt::WhileStmtClass: {
  3333. const WhileStmt *WS = cast<WhileStmt>(S);
  3334. while (true) {
  3335. BlockScopeRAII Scope(Info);
  3336. bool Continue;
  3337. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3338. Continue))
  3339. return ESR_Failed;
  3340. if (!Continue)
  3341. break;
  3342. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3343. if (ESR != ESR_Continue)
  3344. return ESR;
  3345. }
  3346. return ESR_Succeeded;
  3347. }
  3348. case Stmt::DoStmtClass: {
  3349. const DoStmt *DS = cast<DoStmt>(S);
  3350. bool Continue;
  3351. do {
  3352. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3353. if (ESR != ESR_Continue)
  3354. return ESR;
  3355. Case = nullptr;
  3356. FullExpressionRAII CondScope(Info);
  3357. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3358. return ESR_Failed;
  3359. } while (Continue);
  3360. return ESR_Succeeded;
  3361. }
  3362. case Stmt::ForStmtClass: {
  3363. const ForStmt *FS = cast<ForStmt>(S);
  3364. BlockScopeRAII Scope(Info);
  3365. if (FS->getInit()) {
  3366. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3367. if (ESR != ESR_Succeeded)
  3368. return ESR;
  3369. }
  3370. while (true) {
  3371. BlockScopeRAII Scope(Info);
  3372. bool Continue = true;
  3373. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3374. FS->getCond(), Continue))
  3375. return ESR_Failed;
  3376. if (!Continue)
  3377. break;
  3378. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3379. if (ESR != ESR_Continue)
  3380. return ESR;
  3381. if (FS->getInc()) {
  3382. FullExpressionRAII IncScope(Info);
  3383. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3384. return ESR_Failed;
  3385. }
  3386. }
  3387. return ESR_Succeeded;
  3388. }
  3389. case Stmt::CXXForRangeStmtClass: {
  3390. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3391. BlockScopeRAII Scope(Info);
  3392. // Initialize the __range variable.
  3393. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3394. if (ESR != ESR_Succeeded)
  3395. return ESR;
  3396. // Create the __begin and __end iterators.
  3397. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3398. if (ESR != ESR_Succeeded)
  3399. return ESR;
  3400. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3401. if (ESR != ESR_Succeeded)
  3402. return ESR;
  3403. while (true) {
  3404. // Condition: __begin != __end.
  3405. {
  3406. bool Continue = true;
  3407. FullExpressionRAII CondExpr(Info);
  3408. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3409. return ESR_Failed;
  3410. if (!Continue)
  3411. break;
  3412. }
  3413. // User's variable declaration, initialized by *__begin.
  3414. BlockScopeRAII InnerScope(Info);
  3415. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3416. if (ESR != ESR_Succeeded)
  3417. return ESR;
  3418. // Loop body.
  3419. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3420. if (ESR != ESR_Continue)
  3421. return ESR;
  3422. // Increment: ++__begin
  3423. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3424. return ESR_Failed;
  3425. }
  3426. return ESR_Succeeded;
  3427. }
  3428. case Stmt::SwitchStmtClass:
  3429. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3430. case Stmt::ContinueStmtClass:
  3431. return ESR_Continue;
  3432. case Stmt::BreakStmtClass:
  3433. return ESR_Break;
  3434. case Stmt::LabelStmtClass:
  3435. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3436. case Stmt::AttributedStmtClass:
  3437. // As a general principle, C++11 attributes can be ignored without
  3438. // any semantic impact.
  3439. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3440. Case);
  3441. case Stmt::CaseStmtClass:
  3442. case Stmt::DefaultStmtClass:
  3443. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3444. }
  3445. }
  3446. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3447. /// default constructor. If so, we'll fold it whether or not it's marked as
  3448. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3449. /// so we need special handling.
  3450. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3451. const CXXConstructorDecl *CD,
  3452. bool IsValueInitialization) {
  3453. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3454. return false;
  3455. // Value-initialization does not call a trivial default constructor, so such a
  3456. // call is a core constant expression whether or not the constructor is
  3457. // constexpr.
  3458. if (!CD->isConstexpr() && !IsValueInitialization) {
  3459. if (Info.getLangOpts().CPlusPlus11) {
  3460. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3461. // we should be much more explicit about why it's not constexpr.
  3462. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3463. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3464. Info.Note(CD->getLocation(), diag::note_declared_at);
  3465. } else {
  3466. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3467. }
  3468. }
  3469. return true;
  3470. }
  3471. /// CheckConstexprFunction - Check that a function can be called in a constant
  3472. /// expression.
  3473. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3474. const FunctionDecl *Declaration,
  3475. const FunctionDecl *Definition,
  3476. const Stmt *Body) {
  3477. // Potential constant expressions can contain calls to declared, but not yet
  3478. // defined, constexpr functions.
  3479. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3480. Declaration->isConstexpr())
  3481. return false;
  3482. // Bail out with no diagnostic if the function declaration itself is invalid.
  3483. // We will have produced a relevant diagnostic while parsing it.
  3484. if (Declaration->isInvalidDecl())
  3485. return false;
  3486. // Can we evaluate this function call?
  3487. if (Definition && Definition->isConstexpr() &&
  3488. !Definition->isInvalidDecl() && Body)
  3489. return true;
  3490. if (Info.getLangOpts().CPlusPlus11) {
  3491. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3492. // If this function is not constexpr because it is an inherited
  3493. // non-constexpr constructor, diagnose that directly.
  3494. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3495. if (CD && CD->isInheritingConstructor()) {
  3496. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3497. if (!Inherited->isConstexpr())
  3498. DiagDecl = CD = Inherited;
  3499. }
  3500. // FIXME: If DiagDecl is an implicitly-declared special member function
  3501. // or an inheriting constructor, we should be much more explicit about why
  3502. // it's not constexpr.
  3503. if (CD && CD->isInheritingConstructor())
  3504. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3505. << CD->getInheritedConstructor().getConstructor()->getParent();
  3506. else
  3507. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3508. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3509. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3510. } else {
  3511. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3512. }
  3513. return false;
  3514. }
  3515. /// Determine if a class has any fields that might need to be copied by a
  3516. /// trivial copy or move operation.
  3517. static bool hasFields(const CXXRecordDecl *RD) {
  3518. if (!RD || RD->isEmpty())
  3519. return false;
  3520. for (auto *FD : RD->fields()) {
  3521. if (FD->isUnnamedBitfield())
  3522. continue;
  3523. return true;
  3524. }
  3525. for (auto &Base : RD->bases())
  3526. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3527. return true;
  3528. return false;
  3529. }
  3530. namespace {
  3531. typedef SmallVector<APValue, 8> ArgVector;
  3532. }
  3533. /// EvaluateArgs - Evaluate the arguments to a function call.
  3534. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3535. EvalInfo &Info) {
  3536. bool Success = true;
  3537. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3538. I != E; ++I) {
  3539. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3540. // If we're checking for a potential constant expression, evaluate all
  3541. // initializers even if some of them fail.
  3542. if (!Info.noteFailure())
  3543. return false;
  3544. Success = false;
  3545. }
  3546. }
  3547. return Success;
  3548. }
  3549. /// Evaluate a function call.
  3550. static bool HandleFunctionCall(SourceLocation CallLoc,
  3551. const FunctionDecl *Callee, const LValue *This,
  3552. ArrayRef<const Expr*> Args, const Stmt *Body,
  3553. EvalInfo &Info, APValue &Result,
  3554. const LValue *ResultSlot) {
  3555. ArgVector ArgValues(Args.size());
  3556. if (!EvaluateArgs(Args, ArgValues, Info))
  3557. return false;
  3558. if (!Info.CheckCallLimit(CallLoc))
  3559. return false;
  3560. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3561. // For a trivial copy or move assignment, perform an APValue copy. This is
  3562. // essential for unions, where the operations performed by the assignment
  3563. // operator cannot be represented as statements.
  3564. //
  3565. // Skip this for non-union classes with no fields; in that case, the defaulted
  3566. // copy/move does not actually read the object.
  3567. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3568. if (MD && MD->isDefaulted() &&
  3569. (MD->getParent()->isUnion() ||
  3570. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3571. assert(This &&
  3572. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3573. LValue RHS;
  3574. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3575. APValue RHSValue;
  3576. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3577. RHS, RHSValue))
  3578. return false;
  3579. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3580. RHSValue))
  3581. return false;
  3582. This->moveInto(Result);
  3583. return true;
  3584. }
  3585. StmtResult Ret = {Result, ResultSlot};
  3586. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  3587. if (ESR == ESR_Succeeded) {
  3588. if (Callee->getReturnType()->isVoidType())
  3589. return true;
  3590. Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
  3591. }
  3592. return ESR == ESR_Returned;
  3593. }
  3594. /// Evaluate a constructor call.
  3595. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3596. APValue *ArgValues,
  3597. const CXXConstructorDecl *Definition,
  3598. EvalInfo &Info, APValue &Result) {
  3599. SourceLocation CallLoc = E->getExprLoc();
  3600. if (!Info.CheckCallLimit(CallLoc))
  3601. return false;
  3602. const CXXRecordDecl *RD = Definition->getParent();
  3603. if (RD->getNumVBases()) {
  3604. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3605. return false;
  3606. }
  3607. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  3608. // FIXME: Creating an APValue just to hold a nonexistent return value is
  3609. // wasteful.
  3610. APValue RetVal;
  3611. StmtResult Ret = {RetVal, nullptr};
  3612. // If it's a delegating constructor, delegate.
  3613. if (Definition->isDelegatingConstructor()) {
  3614. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3615. {
  3616. FullExpressionRAII InitScope(Info);
  3617. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3618. return false;
  3619. }
  3620. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3621. }
  3622. // For a trivial copy or move constructor, perform an APValue copy. This is
  3623. // essential for unions (or classes with anonymous union members), where the
  3624. // operations performed by the constructor cannot be represented by
  3625. // ctor-initializers.
  3626. //
  3627. // Skip this for empty non-union classes; we should not perform an
  3628. // lvalue-to-rvalue conversion on them because their copy constructor does not
  3629. // actually read them.
  3630. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  3631. (Definition->getParent()->isUnion() ||
  3632. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  3633. LValue RHS;
  3634. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3635. return handleLValueToRValueConversion(
  3636. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  3637. RHS, Result);
  3638. }
  3639. // Reserve space for the struct members.
  3640. if (!RD->isUnion() && Result.isUninit())
  3641. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  3642. std::distance(RD->field_begin(), RD->field_end()));
  3643. if (RD->isInvalidDecl()) return false;
  3644. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  3645. // A scope for temporaries lifetime-extended by reference members.
  3646. BlockScopeRAII LifetimeExtendedScope(Info);
  3647. bool Success = true;
  3648. unsigned BasesSeen = 0;
  3649. #ifndef NDEBUG
  3650. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  3651. #endif
  3652. for (const auto *I : Definition->inits()) {
  3653. LValue Subobject = This;
  3654. APValue *Value = &Result;
  3655. // Determine the subobject to initialize.
  3656. FieldDecl *FD = nullptr;
  3657. if (I->isBaseInitializer()) {
  3658. QualType BaseType(I->getBaseClass(), 0);
  3659. #ifndef NDEBUG
  3660. // Non-virtual base classes are initialized in the order in the class
  3661. // definition. We have already checked for virtual base classes.
  3662. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  3663. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  3664. "base class initializers not in expected order");
  3665. ++BaseIt;
  3666. #endif
  3667. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  3668. BaseType->getAsCXXRecordDecl(), &Layout))
  3669. return false;
  3670. Value = &Result.getStructBase(BasesSeen++);
  3671. } else if ((FD = I->getMember())) {
  3672. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  3673. return false;
  3674. if (RD->isUnion()) {
  3675. Result = APValue(FD);
  3676. Value = &Result.getUnionValue();
  3677. } else {
  3678. Value = &Result.getStructField(FD->getFieldIndex());
  3679. }
  3680. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  3681. // Walk the indirect field decl's chain to find the object to initialize,
  3682. // and make sure we've initialized every step along it.
  3683. for (auto *C : IFD->chain()) {
  3684. FD = cast<FieldDecl>(C);
  3685. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  3686. // Switch the union field if it differs. This happens if we had
  3687. // preceding zero-initialization, and we're now initializing a union
  3688. // subobject other than the first.
  3689. // FIXME: In this case, the values of the other subobjects are
  3690. // specified, since zero-initialization sets all padding bits to zero.
  3691. if (Value->isUninit() ||
  3692. (Value->isUnion() && Value->getUnionField() != FD)) {
  3693. if (CD->isUnion())
  3694. *Value = APValue(FD);
  3695. else
  3696. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  3697. std::distance(CD->field_begin(), CD->field_end()));
  3698. }
  3699. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  3700. return false;
  3701. if (CD->isUnion())
  3702. Value = &Value->getUnionValue();
  3703. else
  3704. Value = &Value->getStructField(FD->getFieldIndex());
  3705. }
  3706. } else {
  3707. llvm_unreachable("unknown base initializer kind");
  3708. }
  3709. FullExpressionRAII InitScope(Info);
  3710. if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
  3711. (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
  3712. *Value, FD))) {
  3713. // If we're checking for a potential constant expression, evaluate all
  3714. // initializers even if some of them fail.
  3715. if (!Info.noteFailure())
  3716. return false;
  3717. Success = false;
  3718. }
  3719. }
  3720. return Success &&
  3721. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3722. }
  3723. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3724. ArrayRef<const Expr*> Args,
  3725. const CXXConstructorDecl *Definition,
  3726. EvalInfo &Info, APValue &Result) {
  3727. ArgVector ArgValues(Args.size());
  3728. if (!EvaluateArgs(Args, ArgValues, Info))
  3729. return false;
  3730. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  3731. Info, Result);
  3732. }
  3733. //===----------------------------------------------------------------------===//
  3734. // Generic Evaluation
  3735. //===----------------------------------------------------------------------===//
  3736. namespace {
  3737. template <class Derived>
  3738. class ExprEvaluatorBase
  3739. : public ConstStmtVisitor<Derived, bool> {
  3740. private:
  3741. Derived &getDerived() { return static_cast<Derived&>(*this); }
  3742. bool DerivedSuccess(const APValue &V, const Expr *E) {
  3743. return getDerived().Success(V, E);
  3744. }
  3745. bool DerivedZeroInitialization(const Expr *E) {
  3746. return getDerived().ZeroInitialization(E);
  3747. }
  3748. // Check whether a conditional operator with a non-constant condition is a
  3749. // potential constant expression. If neither arm is a potential constant
  3750. // expression, then the conditional operator is not either.
  3751. template<typename ConditionalOperator>
  3752. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  3753. assert(Info.checkingPotentialConstantExpression());
  3754. // Speculatively evaluate both arms.
  3755. SmallVector<PartialDiagnosticAt, 8> Diag;
  3756. {
  3757. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  3758. StmtVisitorTy::Visit(E->getFalseExpr());
  3759. if (Diag.empty())
  3760. return;
  3761. }
  3762. {
  3763. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  3764. Diag.clear();
  3765. StmtVisitorTy::Visit(E->getTrueExpr());
  3766. if (Diag.empty())
  3767. return;
  3768. }
  3769. Error(E, diag::note_constexpr_conditional_never_const);
  3770. }
  3771. template<typename ConditionalOperator>
  3772. bool HandleConditionalOperator(const ConditionalOperator *E) {
  3773. bool BoolResult;
  3774. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  3775. if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
  3776. CheckPotentialConstantConditional(E);
  3777. return false;
  3778. }
  3779. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  3780. return StmtVisitorTy::Visit(EvalExpr);
  3781. }
  3782. protected:
  3783. EvalInfo &Info;
  3784. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  3785. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  3786. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  3787. return Info.CCEDiag(E, D);
  3788. }
  3789. bool ZeroInitialization(const Expr *E) { return Error(E); }
  3790. public:
  3791. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  3792. EvalInfo &getEvalInfo() { return Info; }
  3793. /// Report an evaluation error. This should only be called when an error is
  3794. /// first discovered. When propagating an error, just return false.
  3795. bool Error(const Expr *E, diag::kind D) {
  3796. Info.FFDiag(E, D);
  3797. return false;
  3798. }
  3799. bool Error(const Expr *E) {
  3800. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  3801. }
  3802. bool VisitStmt(const Stmt *) {
  3803. llvm_unreachable("Expression evaluator should not be called on stmts");
  3804. }
  3805. bool VisitExpr(const Expr *E) {
  3806. return Error(E);
  3807. }
  3808. bool VisitParenExpr(const ParenExpr *E)
  3809. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3810. bool VisitUnaryExtension(const UnaryOperator *E)
  3811. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3812. bool VisitUnaryPlus(const UnaryOperator *E)
  3813. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3814. bool VisitChooseExpr(const ChooseExpr *E)
  3815. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  3816. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  3817. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  3818. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  3819. { return StmtVisitorTy::Visit(E->getReplacement()); }
  3820. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
  3821. { return StmtVisitorTy::Visit(E->getExpr()); }
  3822. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  3823. // The initializer may not have been parsed yet, or might be erroneous.
  3824. if (!E->getExpr())
  3825. return Error(E);
  3826. return StmtVisitorTy::Visit(E->getExpr());
  3827. }
  3828. // We cannot create any objects for which cleanups are required, so there is
  3829. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  3830. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  3831. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  3832. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  3833. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  3834. return static_cast<Derived*>(this)->VisitCastExpr(E);
  3835. }
  3836. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  3837. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  3838. return static_cast<Derived*>(this)->VisitCastExpr(E);
  3839. }
  3840. bool VisitBinaryOperator(const BinaryOperator *E) {
  3841. switch (E->getOpcode()) {
  3842. default:
  3843. return Error(E);
  3844. case BO_Comma:
  3845. VisitIgnoredValue(E->getLHS());
  3846. return StmtVisitorTy::Visit(E->getRHS());
  3847. case BO_PtrMemD:
  3848. case BO_PtrMemI: {
  3849. LValue Obj;
  3850. if (!HandleMemberPointerAccess(Info, E, Obj))
  3851. return false;
  3852. APValue Result;
  3853. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  3854. return false;
  3855. return DerivedSuccess(Result, E);
  3856. }
  3857. }
  3858. }
  3859. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  3860. // Evaluate and cache the common expression. We treat it as a temporary,
  3861. // even though it's not quite the same thing.
  3862. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  3863. Info, E->getCommon()))
  3864. return false;
  3865. return HandleConditionalOperator(E);
  3866. }
  3867. bool VisitConditionalOperator(const ConditionalOperator *E) {
  3868. bool IsBcpCall = false;
  3869. // If the condition (ignoring parens) is a __builtin_constant_p call,
  3870. // the result is a constant expression if it can be folded without
  3871. // side-effects. This is an important GNU extension. See GCC PR38377
  3872. // for discussion.
  3873. if (const CallExpr *CallCE =
  3874. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  3875. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  3876. IsBcpCall = true;
  3877. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  3878. // constant expression; we can't check whether it's potentially foldable.
  3879. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  3880. return false;
  3881. FoldConstant Fold(Info, IsBcpCall);
  3882. if (!HandleConditionalOperator(E)) {
  3883. Fold.keepDiagnostics();
  3884. return false;
  3885. }
  3886. return true;
  3887. }
  3888. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  3889. if (APValue *Value = Info.CurrentCall->getTemporary(E))
  3890. return DerivedSuccess(*Value, E);
  3891. const Expr *Source = E->getSourceExpr();
  3892. if (!Source)
  3893. return Error(E);
  3894. if (Source == E) { // sanity checking.
  3895. assert(0 && "OpaqueValueExpr recursively refers to itself");
  3896. return Error(E);
  3897. }
  3898. return StmtVisitorTy::Visit(Source);
  3899. }
  3900. bool VisitCallExpr(const CallExpr *E) {
  3901. APValue Result;
  3902. if (!handleCallExpr(E, Result, nullptr))
  3903. return false;
  3904. return DerivedSuccess(Result, E);
  3905. }
  3906. bool handleCallExpr(const CallExpr *E, APValue &Result,
  3907. const LValue *ResultSlot) {
  3908. const Expr *Callee = E->getCallee()->IgnoreParens();
  3909. QualType CalleeType = Callee->getType();
  3910. const FunctionDecl *FD = nullptr;
  3911. LValue *This = nullptr, ThisVal;
  3912. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  3913. bool HasQualifier = false;
  3914. // Extract function decl and 'this' pointer from the callee.
  3915. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  3916. const ValueDecl *Member = nullptr;
  3917. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  3918. // Explicit bound member calls, such as x.f() or p->g();
  3919. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  3920. return false;
  3921. Member = ME->getMemberDecl();
  3922. This = &ThisVal;
  3923. HasQualifier = ME->hasQualifier();
  3924. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  3925. // Indirect bound member calls ('.*' or '->*').
  3926. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  3927. if (!Member) return false;
  3928. This = &ThisVal;
  3929. } else
  3930. return Error(Callee);
  3931. FD = dyn_cast<FunctionDecl>(Member);
  3932. if (!FD)
  3933. return Error(Callee);
  3934. } else if (CalleeType->isFunctionPointerType()) {
  3935. LValue Call;
  3936. if (!EvaluatePointer(Callee, Call, Info))
  3937. return false;
  3938. if (!Call.getLValueOffset().isZero())
  3939. return Error(Callee);
  3940. FD = dyn_cast_or_null<FunctionDecl>(
  3941. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  3942. if (!FD)
  3943. return Error(Callee);
  3944. // Overloaded operator calls to member functions are represented as normal
  3945. // calls with '*this' as the first argument.
  3946. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  3947. if (MD && !MD->isStatic()) {
  3948. // FIXME: When selecting an implicit conversion for an overloaded
  3949. // operator delete, we sometimes try to evaluate calls to conversion
  3950. // operators without a 'this' parameter!
  3951. if (Args.empty())
  3952. return Error(E);
  3953. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  3954. return false;
  3955. This = &ThisVal;
  3956. Args = Args.slice(1);
  3957. }
  3958. // Don't call function pointers which have been cast to some other type.
  3959. // Per DR (no number yet), the caller and callee can differ in noexcept.
  3960. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  3961. CalleeType->getPointeeType(), FD->getType())) {
  3962. return Error(E);
  3963. }
  3964. } else
  3965. return Error(E);
  3966. if (This && !This->checkSubobject(Info, E, CSK_This))
  3967. return false;
  3968. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  3969. // calls to such functions in constant expressions.
  3970. if (This && !HasQualifier &&
  3971. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  3972. return Error(E, diag::note_constexpr_virtual_call);
  3973. const FunctionDecl *Definition = nullptr;
  3974. Stmt *Body = FD->getBody(Definition);
  3975. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  3976. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  3977. Result, ResultSlot))
  3978. return false;
  3979. return true;
  3980. }
  3981. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  3982. return StmtVisitorTy::Visit(E->getInitializer());
  3983. }
  3984. bool VisitInitListExpr(const InitListExpr *E) {
  3985. if (E->getNumInits() == 0)
  3986. return DerivedZeroInitialization(E);
  3987. if (E->getNumInits() == 1)
  3988. return StmtVisitorTy::Visit(E->getInit(0));
  3989. return Error(E);
  3990. }
  3991. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  3992. return DerivedZeroInitialization(E);
  3993. }
  3994. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  3995. return DerivedZeroInitialization(E);
  3996. }
  3997. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  3998. return DerivedZeroInitialization(E);
  3999. }
  4000. /// A member expression where the object is a prvalue is itself a prvalue.
  4001. bool VisitMemberExpr(const MemberExpr *E) {
  4002. assert(!E->isArrow() && "missing call to bound member function?");
  4003. APValue Val;
  4004. if (!Evaluate(Val, Info, E->getBase()))
  4005. return false;
  4006. QualType BaseTy = E->getBase()->getType();
  4007. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4008. if (!FD) return Error(E);
  4009. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4010. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4011. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4012. CompleteObject Obj(&Val, BaseTy);
  4013. SubobjectDesignator Designator(BaseTy);
  4014. Designator.addDeclUnchecked(FD);
  4015. APValue Result;
  4016. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4017. DerivedSuccess(Result, E);
  4018. }
  4019. bool VisitCastExpr(const CastExpr *E) {
  4020. switch (E->getCastKind()) {
  4021. default:
  4022. break;
  4023. case CK_AtomicToNonAtomic: {
  4024. APValue AtomicVal;
  4025. if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
  4026. return false;
  4027. return DerivedSuccess(AtomicVal, E);
  4028. }
  4029. case CK_NoOp:
  4030. case CK_UserDefinedConversion:
  4031. return StmtVisitorTy::Visit(E->getSubExpr());
  4032. case CK_LValueToRValue: {
  4033. LValue LVal;
  4034. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4035. return false;
  4036. APValue RVal;
  4037. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4038. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4039. LVal, RVal))
  4040. return false;
  4041. return DerivedSuccess(RVal, E);
  4042. }
  4043. }
  4044. return Error(E);
  4045. }
  4046. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4047. return VisitUnaryPostIncDec(UO);
  4048. }
  4049. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4050. return VisitUnaryPostIncDec(UO);
  4051. }
  4052. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4053. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4054. return Error(UO);
  4055. LValue LVal;
  4056. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4057. return false;
  4058. APValue RVal;
  4059. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4060. UO->isIncrementOp(), &RVal))
  4061. return false;
  4062. return DerivedSuccess(RVal, UO);
  4063. }
  4064. bool VisitStmtExpr(const StmtExpr *E) {
  4065. // We will have checked the full-expressions inside the statement expression
  4066. // when they were completed, and don't need to check them again now.
  4067. if (Info.checkingForOverflow())
  4068. return Error(E);
  4069. BlockScopeRAII Scope(Info);
  4070. const CompoundStmt *CS = E->getSubStmt();
  4071. if (CS->body_empty())
  4072. return true;
  4073. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4074. BE = CS->body_end();
  4075. /**/; ++BI) {
  4076. if (BI + 1 == BE) {
  4077. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4078. if (!FinalExpr) {
  4079. Info.FFDiag((*BI)->getLocStart(),
  4080. diag::note_constexpr_stmt_expr_unsupported);
  4081. return false;
  4082. }
  4083. return this->Visit(FinalExpr);
  4084. }
  4085. APValue ReturnValue;
  4086. StmtResult Result = { ReturnValue, nullptr };
  4087. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4088. if (ESR != ESR_Succeeded) {
  4089. // FIXME: If the statement-expression terminated due to 'return',
  4090. // 'break', or 'continue', it would be nice to propagate that to
  4091. // the outer statement evaluation rather than bailing out.
  4092. if (ESR != ESR_Failed)
  4093. Info.FFDiag((*BI)->getLocStart(),
  4094. diag::note_constexpr_stmt_expr_unsupported);
  4095. return false;
  4096. }
  4097. }
  4098. llvm_unreachable("Return from function from the loop above.");
  4099. }
  4100. /// Visit a value which is evaluated, but whose value is ignored.
  4101. void VisitIgnoredValue(const Expr *E) {
  4102. EvaluateIgnoredValue(Info, E);
  4103. }
  4104. /// Potentially visit a MemberExpr's base expression.
  4105. void VisitIgnoredBaseExpression(const Expr *E) {
  4106. // While MSVC doesn't evaluate the base expression, it does diagnose the
  4107. // presence of side-effecting behavior.
  4108. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  4109. return;
  4110. VisitIgnoredValue(E);
  4111. }
  4112. };
  4113. }
  4114. //===----------------------------------------------------------------------===//
  4115. // Common base class for lvalue and temporary evaluation.
  4116. //===----------------------------------------------------------------------===//
  4117. namespace {
  4118. template<class Derived>
  4119. class LValueExprEvaluatorBase
  4120. : public ExprEvaluatorBase<Derived> {
  4121. protected:
  4122. LValue &Result;
  4123. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  4124. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  4125. bool Success(APValue::LValueBase B) {
  4126. Result.set(B);
  4127. return true;
  4128. }
  4129. public:
  4130. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
  4131. ExprEvaluatorBaseTy(Info), Result(Result) {}
  4132. bool Success(const APValue &V, const Expr *E) {
  4133. Result.setFrom(this->Info.Ctx, V);
  4134. return true;
  4135. }
  4136. bool VisitMemberExpr(const MemberExpr *E) {
  4137. // Handle non-static data members.
  4138. QualType BaseTy;
  4139. bool EvalOK;
  4140. if (E->isArrow()) {
  4141. EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
  4142. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  4143. } else if (E->getBase()->isRValue()) {
  4144. assert(E->getBase()->getType()->isRecordType());
  4145. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  4146. BaseTy = E->getBase()->getType();
  4147. } else {
  4148. EvalOK = this->Visit(E->getBase());
  4149. BaseTy = E->getBase()->getType();
  4150. }
  4151. if (!EvalOK) {
  4152. if (!this->Info.allowInvalidBaseExpr())
  4153. return false;
  4154. Result.setInvalid(E);
  4155. return true;
  4156. }
  4157. const ValueDecl *MD = E->getMemberDecl();
  4158. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  4159. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4160. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4161. (void)BaseTy;
  4162. if (!HandleLValueMember(this->Info, E, Result, FD))
  4163. return false;
  4164. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  4165. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  4166. return false;
  4167. } else
  4168. return this->Error(E);
  4169. if (MD->getType()->isReferenceType()) {
  4170. APValue RefValue;
  4171. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  4172. RefValue))
  4173. return false;
  4174. return Success(RefValue, E);
  4175. }
  4176. return true;
  4177. }
  4178. bool VisitBinaryOperator(const BinaryOperator *E) {
  4179. switch (E->getOpcode()) {
  4180. default:
  4181. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4182. case BO_PtrMemD:
  4183. case BO_PtrMemI:
  4184. return HandleMemberPointerAccess(this->Info, E, Result);
  4185. }
  4186. }
  4187. bool VisitCastExpr(const CastExpr *E) {
  4188. switch (E->getCastKind()) {
  4189. default:
  4190. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4191. case CK_DerivedToBase:
  4192. case CK_UncheckedDerivedToBase:
  4193. if (!this->Visit(E->getSubExpr()))
  4194. return false;
  4195. // Now figure out the necessary offset to add to the base LV to get from
  4196. // the derived class to the base class.
  4197. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4198. Result);
  4199. }
  4200. }
  4201. };
  4202. }
  4203. //===----------------------------------------------------------------------===//
  4204. // LValue Evaluation
  4205. //
  4206. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4207. // function designators (in C), decl references to void objects (in C), and
  4208. // temporaries (if building with -Wno-address-of-temporary).
  4209. //
  4210. // LValue evaluation produces values comprising a base expression of one of the
  4211. // following types:
  4212. // - Declarations
  4213. // * VarDecl
  4214. // * FunctionDecl
  4215. // - Literals
  4216. // * CompoundLiteralExpr in C (and in global scope in C++)
  4217. // * StringLiteral
  4218. // * CXXTypeidExpr
  4219. // * PredefinedExpr
  4220. // * ObjCStringLiteralExpr
  4221. // * ObjCEncodeExpr
  4222. // * AddrLabelExpr
  4223. // * BlockExpr
  4224. // * CallExpr for a MakeStringConstant builtin
  4225. // - Locals and temporaries
  4226. // * MaterializeTemporaryExpr
  4227. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4228. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4229. // from the AST (FIXME).
  4230. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4231. // CallIndex, for a lifetime-extended temporary.
  4232. // plus an offset in bytes.
  4233. //===----------------------------------------------------------------------===//
  4234. namespace {
  4235. class LValueExprEvaluator
  4236. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4237. public:
  4238. LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
  4239. LValueExprEvaluatorBaseTy(Info, Result) {}
  4240. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4241. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4242. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4243. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4244. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4245. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4246. bool VisitMemberExpr(const MemberExpr *E);
  4247. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4248. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4249. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4250. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4251. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4252. bool VisitUnaryDeref(const UnaryOperator *E);
  4253. bool VisitUnaryReal(const UnaryOperator *E);
  4254. bool VisitUnaryImag(const UnaryOperator *E);
  4255. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4256. return VisitUnaryPreIncDec(UO);
  4257. }
  4258. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4259. return VisitUnaryPreIncDec(UO);
  4260. }
  4261. bool VisitBinAssign(const BinaryOperator *BO);
  4262. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4263. bool VisitCastExpr(const CastExpr *E) {
  4264. switch (E->getCastKind()) {
  4265. default:
  4266. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4267. case CK_LValueBitCast:
  4268. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4269. if (!Visit(E->getSubExpr()))
  4270. return false;
  4271. Result.Designator.setInvalid();
  4272. return true;
  4273. case CK_BaseToDerived:
  4274. if (!Visit(E->getSubExpr()))
  4275. return false;
  4276. return HandleBaseToDerivedCast(Info, E, Result);
  4277. }
  4278. }
  4279. };
  4280. } // end anonymous namespace
  4281. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4282. /// expressions which are not glvalues, in three cases:
  4283. /// * function designators in C, and
  4284. /// * "extern void" objects
  4285. /// * @selector() expressions in Objective-C
  4286. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
  4287. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4288. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  4289. return LValueExprEvaluator(Info, Result).Visit(E);
  4290. }
  4291. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4292. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4293. return Success(FD);
  4294. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4295. return VisitVarDecl(E, VD);
  4296. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  4297. return Visit(BD->getBinding());
  4298. return Error(E);
  4299. }
  4300. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4301. CallStackFrame *Frame = nullptr;
  4302. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  4303. // Only if a local variable was declared in the function currently being
  4304. // evaluated, do we expect to be able to find its value in the current
  4305. // frame. (Otherwise it was likely declared in an enclosing context and
  4306. // could either have a valid evaluatable value (for e.g. a constexpr
  4307. // variable) or be ill-formed (and trigger an appropriate evaluation
  4308. // diagnostic)).
  4309. if (Info.CurrentCall->Callee &&
  4310. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  4311. Frame = Info.CurrentCall;
  4312. }
  4313. }
  4314. if (!VD->getType()->isReferenceType()) {
  4315. if (Frame) {
  4316. Result.set(VD, Frame->Index);
  4317. return true;
  4318. }
  4319. return Success(VD);
  4320. }
  4321. APValue *V;
  4322. if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
  4323. return false;
  4324. if (V->isUninit()) {
  4325. if (!Info.checkingPotentialConstantExpression())
  4326. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  4327. return false;
  4328. }
  4329. return Success(*V, E);
  4330. }
  4331. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4332. const MaterializeTemporaryExpr *E) {
  4333. // Walk through the expression to find the materialized temporary itself.
  4334. SmallVector<const Expr *, 2> CommaLHSs;
  4335. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4336. const Expr *Inner = E->GetTemporaryExpr()->
  4337. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4338. // If we passed any comma operators, evaluate their LHSs.
  4339. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4340. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4341. return false;
  4342. // A materialized temporary with static storage duration can appear within the
  4343. // result of a constant expression evaluation, so we need to preserve its
  4344. // value for use outside this evaluation.
  4345. APValue *Value;
  4346. if (E->getStorageDuration() == SD_Static) {
  4347. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4348. *Value = APValue();
  4349. Result.set(E);
  4350. } else {
  4351. Value = &Info.CurrentCall->
  4352. createTemporary(E, E->getStorageDuration() == SD_Automatic);
  4353. Result.set(E, Info.CurrentCall->Index);
  4354. }
  4355. QualType Type = Inner->getType();
  4356. // Materialize the temporary itself.
  4357. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4358. (E->getStorageDuration() == SD_Static &&
  4359. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4360. *Value = APValue();
  4361. return false;
  4362. }
  4363. // Adjust our lvalue to refer to the desired subobject.
  4364. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4365. --I;
  4366. switch (Adjustments[I].Kind) {
  4367. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4368. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4369. Type, Result))
  4370. return false;
  4371. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4372. break;
  4373. case SubobjectAdjustment::FieldAdjustment:
  4374. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4375. return false;
  4376. Type = Adjustments[I].Field->getType();
  4377. break;
  4378. case SubobjectAdjustment::MemberPointerAdjustment:
  4379. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4380. Adjustments[I].Ptr.RHS))
  4381. return false;
  4382. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4383. break;
  4384. }
  4385. }
  4386. return true;
  4387. }
  4388. bool
  4389. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4390. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  4391. "lvalue compound literal in c++?");
  4392. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4393. // only see this when folding in C, so there's no standard to follow here.
  4394. return Success(E);
  4395. }
  4396. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4397. if (!E->isPotentiallyEvaluated())
  4398. return Success(E);
  4399. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  4400. << E->getExprOperand()->getType()
  4401. << E->getExprOperand()->getSourceRange();
  4402. return false;
  4403. }
  4404. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4405. return Success(E);
  4406. }
  4407. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4408. // Handle static data members.
  4409. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4410. VisitIgnoredBaseExpression(E->getBase());
  4411. return VisitVarDecl(E, VD);
  4412. }
  4413. // Handle static member functions.
  4414. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4415. if (MD->isStatic()) {
  4416. VisitIgnoredBaseExpression(E->getBase());
  4417. return Success(MD);
  4418. }
  4419. }
  4420. // Handle non-static data members.
  4421. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4422. }
  4423. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4424. // FIXME: Deal with vectors as array subscript bases.
  4425. if (E->getBase()->getType()->isVectorType())
  4426. return Error(E);
  4427. if (!EvaluatePointer(E->getBase(), Result, Info))
  4428. return false;
  4429. APSInt Index;
  4430. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4431. return false;
  4432. return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
  4433. getExtValue(Index));
  4434. }
  4435. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4436. return EvaluatePointer(E->getSubExpr(), Result, Info);
  4437. }
  4438. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4439. if (!Visit(E->getSubExpr()))
  4440. return false;
  4441. // __real is a no-op on scalar lvalues.
  4442. if (E->getSubExpr()->getType()->isAnyComplexType())
  4443. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4444. return true;
  4445. }
  4446. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4447. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4448. "lvalue __imag__ on scalar?");
  4449. if (!Visit(E->getSubExpr()))
  4450. return false;
  4451. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4452. return true;
  4453. }
  4454. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4455. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4456. return Error(UO);
  4457. if (!this->Visit(UO->getSubExpr()))
  4458. return false;
  4459. return handleIncDec(
  4460. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4461. UO->isIncrementOp(), nullptr);
  4462. }
  4463. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4464. const CompoundAssignOperator *CAO) {
  4465. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4466. return Error(CAO);
  4467. APValue RHS;
  4468. // The overall lvalue result is the result of evaluating the LHS.
  4469. if (!this->Visit(CAO->getLHS())) {
  4470. if (Info.noteFailure())
  4471. Evaluate(RHS, this->Info, CAO->getRHS());
  4472. return false;
  4473. }
  4474. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4475. return false;
  4476. return handleCompoundAssignment(
  4477. this->Info, CAO,
  4478. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4479. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4480. }
  4481. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4482. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4483. return Error(E);
  4484. APValue NewVal;
  4485. if (!this->Visit(E->getLHS())) {
  4486. if (Info.noteFailure())
  4487. Evaluate(NewVal, this->Info, E->getRHS());
  4488. return false;
  4489. }
  4490. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4491. return false;
  4492. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4493. NewVal);
  4494. }
  4495. //===----------------------------------------------------------------------===//
  4496. // Pointer Evaluation
  4497. //===----------------------------------------------------------------------===//
  4498. namespace {
  4499. class PointerExprEvaluator
  4500. : public ExprEvaluatorBase<PointerExprEvaluator> {
  4501. LValue &Result;
  4502. bool Success(const Expr *E) {
  4503. Result.set(E);
  4504. return true;
  4505. }
  4506. public:
  4507. PointerExprEvaluator(EvalInfo &info, LValue &Result)
  4508. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4509. bool Success(const APValue &V, const Expr *E) {
  4510. Result.setFrom(Info.Ctx, V);
  4511. return true;
  4512. }
  4513. bool ZeroInitialization(const Expr *E) {
  4514. auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
  4515. Result.set((Expr*)nullptr, 0, false, true, Offset);
  4516. return true;
  4517. }
  4518. bool VisitBinaryOperator(const BinaryOperator *E);
  4519. bool VisitCastExpr(const CastExpr* E);
  4520. bool VisitUnaryAddrOf(const UnaryOperator *E);
  4521. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  4522. { return Success(E); }
  4523. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
  4524. { return Success(E); }
  4525. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  4526. { return Success(E); }
  4527. bool VisitCallExpr(const CallExpr *E);
  4528. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  4529. bool VisitBlockExpr(const BlockExpr *E) {
  4530. if (!E->getBlockDecl()->hasCaptures())
  4531. return Success(E);
  4532. return Error(E);
  4533. }
  4534. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  4535. // Can't look at 'this' when checking a potential constant expression.
  4536. if (Info.checkingPotentialConstantExpression())
  4537. return false;
  4538. if (!Info.CurrentCall->This) {
  4539. if (Info.getLangOpts().CPlusPlus11)
  4540. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  4541. else
  4542. Info.FFDiag(E);
  4543. return false;
  4544. }
  4545. Result = *Info.CurrentCall->This;
  4546. return true;
  4547. }
  4548. // FIXME: Missing: @protocol, @selector
  4549. };
  4550. } // end anonymous namespace
  4551. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
  4552. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  4553. return PointerExprEvaluator(Info, Result).Visit(E);
  4554. }
  4555. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4556. if (E->getOpcode() != BO_Add &&
  4557. E->getOpcode() != BO_Sub)
  4558. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4559. const Expr *PExp = E->getLHS();
  4560. const Expr *IExp = E->getRHS();
  4561. if (IExp->getType()->isPointerType())
  4562. std::swap(PExp, IExp);
  4563. bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
  4564. if (!EvalPtrOK && !Info.noteFailure())
  4565. return false;
  4566. llvm::APSInt Offset;
  4567. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  4568. return false;
  4569. int64_t AdditionalOffset = getExtValue(Offset);
  4570. if (E->getOpcode() == BO_Sub)
  4571. AdditionalOffset = -AdditionalOffset;
  4572. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  4573. return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
  4574. AdditionalOffset);
  4575. }
  4576. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  4577. return EvaluateLValue(E->getSubExpr(), Result, Info);
  4578. }
  4579. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  4580. const Expr* SubExpr = E->getSubExpr();
  4581. switch (E->getCastKind()) {
  4582. default:
  4583. break;
  4584. case CK_BitCast:
  4585. case CK_CPointerToObjCPointerCast:
  4586. case CK_BlockPointerToObjCPointerCast:
  4587. case CK_AnyPointerToBlockPointerCast:
  4588. case CK_AddressSpaceConversion:
  4589. if (!Visit(SubExpr))
  4590. return false;
  4591. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  4592. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  4593. // also static_casts, but we disallow them as a resolution to DR1312.
  4594. if (!E->getType()->isVoidPointerType()) {
  4595. Result.Designator.setInvalid();
  4596. if (SubExpr->getType()->isVoidPointerType())
  4597. CCEDiag(E, diag::note_constexpr_invalid_cast)
  4598. << 3 << SubExpr->getType();
  4599. else
  4600. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4601. }
  4602. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  4603. ZeroInitialization(E);
  4604. return true;
  4605. case CK_DerivedToBase:
  4606. case CK_UncheckedDerivedToBase:
  4607. if (!EvaluatePointer(E->getSubExpr(), Result, Info))
  4608. return false;
  4609. if (!Result.Base && Result.Offset.isZero())
  4610. return true;
  4611. // Now figure out the necessary offset to add to the base LV to get from
  4612. // the derived class to the base class.
  4613. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  4614. castAs<PointerType>()->getPointeeType(),
  4615. Result);
  4616. case CK_BaseToDerived:
  4617. if (!Visit(E->getSubExpr()))
  4618. return false;
  4619. if (!Result.Base && Result.Offset.isZero())
  4620. return true;
  4621. return HandleBaseToDerivedCast(Info, E, Result);
  4622. case CK_NullToPointer:
  4623. VisitIgnoredValue(E->getSubExpr());
  4624. return ZeroInitialization(E);
  4625. case CK_IntegralToPointer: {
  4626. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4627. APValue Value;
  4628. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  4629. break;
  4630. if (Value.isInt()) {
  4631. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  4632. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  4633. Result.Base = (Expr*)nullptr;
  4634. Result.InvalidBase = false;
  4635. Result.Offset = CharUnits::fromQuantity(N);
  4636. Result.CallIndex = 0;
  4637. Result.Designator.setInvalid();
  4638. Result.IsNullPtr = false;
  4639. return true;
  4640. } else {
  4641. // Cast is of an lvalue, no need to change value.
  4642. Result.setFrom(Info.Ctx, Value);
  4643. return true;
  4644. }
  4645. }
  4646. case CK_ArrayToPointerDecay:
  4647. if (SubExpr->isGLValue()) {
  4648. if (!EvaluateLValue(SubExpr, Result, Info))
  4649. return false;
  4650. } else {
  4651. Result.set(SubExpr, Info.CurrentCall->Index);
  4652. if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
  4653. Info, Result, SubExpr))
  4654. return false;
  4655. }
  4656. // The result is a pointer to the first element of the array.
  4657. if (const ConstantArrayType *CAT
  4658. = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
  4659. Result.addArray(Info, E, CAT);
  4660. else
  4661. Result.Designator.setInvalid();
  4662. return true;
  4663. case CK_FunctionToPointerDecay:
  4664. return EvaluateLValue(SubExpr, Result, Info);
  4665. }
  4666. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4667. }
  4668. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
  4669. // C++ [expr.alignof]p3:
  4670. // When alignof is applied to a reference type, the result is the
  4671. // alignment of the referenced type.
  4672. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  4673. T = Ref->getPointeeType();
  4674. // __alignof is defined to return the preferred alignment.
  4675. return Info.Ctx.toCharUnitsFromBits(
  4676. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  4677. }
  4678. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
  4679. E = E->IgnoreParens();
  4680. // The kinds of expressions that we have special-case logic here for
  4681. // should be kept up to date with the special checks for those
  4682. // expressions in Sema.
  4683. // alignof decl is always accepted, even if it doesn't make sense: we default
  4684. // to 1 in those cases.
  4685. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4686. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  4687. /*RefAsPointee*/true);
  4688. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  4689. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  4690. /*RefAsPointee*/true);
  4691. return GetAlignOfType(Info, E->getType());
  4692. }
  4693. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  4694. if (IsStringLiteralCall(E))
  4695. return Success(E);
  4696. if (unsigned BuiltinOp = E->getBuiltinCallee())
  4697. return VisitBuiltinCallExpr(E, BuiltinOp);
  4698. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4699. }
  4700. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  4701. unsigned BuiltinOp) {
  4702. switch (BuiltinOp) {
  4703. case Builtin::BI__builtin_addressof:
  4704. return EvaluateLValue(E->getArg(0), Result, Info);
  4705. case Builtin::BI__builtin_assume_aligned: {
  4706. // We need to be very careful here because: if the pointer does not have the
  4707. // asserted alignment, then the behavior is undefined, and undefined
  4708. // behavior is non-constant.
  4709. if (!EvaluatePointer(E->getArg(0), Result, Info))
  4710. return false;
  4711. LValue OffsetResult(Result);
  4712. APSInt Alignment;
  4713. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  4714. return false;
  4715. CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
  4716. if (E->getNumArgs() > 2) {
  4717. APSInt Offset;
  4718. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  4719. return false;
  4720. int64_t AdditionalOffset = -getExtValue(Offset);
  4721. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  4722. }
  4723. // If there is a base object, then it must have the correct alignment.
  4724. if (OffsetResult.Base) {
  4725. CharUnits BaseAlignment;
  4726. if (const ValueDecl *VD =
  4727. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  4728. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  4729. } else {
  4730. BaseAlignment =
  4731. GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
  4732. }
  4733. if (BaseAlignment < Align) {
  4734. Result.Designator.setInvalid();
  4735. // FIXME: Quantities here cast to integers because the plural modifier
  4736. // does not work on APSInts yet.
  4737. CCEDiag(E->getArg(0),
  4738. diag::note_constexpr_baa_insufficient_alignment) << 0
  4739. << (int) BaseAlignment.getQuantity()
  4740. << (unsigned) getExtValue(Alignment);
  4741. return false;
  4742. }
  4743. }
  4744. // The offset must also have the correct alignment.
  4745. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  4746. Result.Designator.setInvalid();
  4747. APSInt Offset(64, false);
  4748. Offset = OffsetResult.Offset.getQuantity();
  4749. if (OffsetResult.Base)
  4750. CCEDiag(E->getArg(0),
  4751. diag::note_constexpr_baa_insufficient_alignment) << 1
  4752. << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
  4753. else
  4754. CCEDiag(E->getArg(0),
  4755. diag::note_constexpr_baa_value_insufficient_alignment)
  4756. << Offset << (unsigned) getExtValue(Alignment);
  4757. return false;
  4758. }
  4759. return true;
  4760. }
  4761. case Builtin::BIstrchr:
  4762. case Builtin::BIwcschr:
  4763. case Builtin::BImemchr:
  4764. case Builtin::BIwmemchr:
  4765. if (Info.getLangOpts().CPlusPlus11)
  4766. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  4767. << /*isConstexpr*/0 << /*isConstructor*/0
  4768. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  4769. else
  4770. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  4771. // Fall through.
  4772. case Builtin::BI__builtin_strchr:
  4773. case Builtin::BI__builtin_wcschr:
  4774. case Builtin::BI__builtin_memchr:
  4775. case Builtin::BI__builtin_wmemchr: {
  4776. if (!Visit(E->getArg(0)))
  4777. return false;
  4778. APSInt Desired;
  4779. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  4780. return false;
  4781. uint64_t MaxLength = uint64_t(-1);
  4782. if (BuiltinOp != Builtin::BIstrchr &&
  4783. BuiltinOp != Builtin::BIwcschr &&
  4784. BuiltinOp != Builtin::BI__builtin_strchr &&
  4785. BuiltinOp != Builtin::BI__builtin_wcschr) {
  4786. APSInt N;
  4787. if (!EvaluateInteger(E->getArg(2), N, Info))
  4788. return false;
  4789. MaxLength = N.getExtValue();
  4790. }
  4791. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  4792. // Figure out what value we're actually looking for (after converting to
  4793. // the corresponding unsigned type if necessary).
  4794. uint64_t DesiredVal;
  4795. bool StopAtNull = false;
  4796. switch (BuiltinOp) {
  4797. case Builtin::BIstrchr:
  4798. case Builtin::BI__builtin_strchr:
  4799. // strchr compares directly to the passed integer, and therefore
  4800. // always fails if given an int that is not a char.
  4801. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  4802. E->getArg(1)->getType(),
  4803. Desired),
  4804. Desired))
  4805. return ZeroInitialization(E);
  4806. StopAtNull = true;
  4807. // Fall through.
  4808. case Builtin::BImemchr:
  4809. case Builtin::BI__builtin_memchr:
  4810. // memchr compares by converting both sides to unsigned char. That's also
  4811. // correct for strchr if we get this far (to cope with plain char being
  4812. // unsigned in the strchr case).
  4813. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  4814. break;
  4815. case Builtin::BIwcschr:
  4816. case Builtin::BI__builtin_wcschr:
  4817. StopAtNull = true;
  4818. // Fall through.
  4819. case Builtin::BIwmemchr:
  4820. case Builtin::BI__builtin_wmemchr:
  4821. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  4822. DesiredVal = Desired.getZExtValue();
  4823. break;
  4824. }
  4825. for (; MaxLength; --MaxLength) {
  4826. APValue Char;
  4827. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  4828. !Char.isInt())
  4829. return false;
  4830. if (Char.getInt().getZExtValue() == DesiredVal)
  4831. return true;
  4832. if (StopAtNull && !Char.getInt())
  4833. break;
  4834. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  4835. return false;
  4836. }
  4837. // Not found: return nullptr.
  4838. return ZeroInitialization(E);
  4839. }
  4840. default:
  4841. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4842. }
  4843. }
  4844. //===----------------------------------------------------------------------===//
  4845. // Member Pointer Evaluation
  4846. //===----------------------------------------------------------------------===//
  4847. namespace {
  4848. class MemberPointerExprEvaluator
  4849. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  4850. MemberPtr &Result;
  4851. bool Success(const ValueDecl *D) {
  4852. Result = MemberPtr(D);
  4853. return true;
  4854. }
  4855. public:
  4856. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  4857. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  4858. bool Success(const APValue &V, const Expr *E) {
  4859. Result.setFrom(V);
  4860. return true;
  4861. }
  4862. bool ZeroInitialization(const Expr *E) {
  4863. return Success((const ValueDecl*)nullptr);
  4864. }
  4865. bool VisitCastExpr(const CastExpr *E);
  4866. bool VisitUnaryAddrOf(const UnaryOperator *E);
  4867. };
  4868. } // end anonymous namespace
  4869. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  4870. EvalInfo &Info) {
  4871. assert(E->isRValue() && E->getType()->isMemberPointerType());
  4872. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  4873. }
  4874. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4875. switch (E->getCastKind()) {
  4876. default:
  4877. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4878. case CK_NullToMemberPointer:
  4879. VisitIgnoredValue(E->getSubExpr());
  4880. return ZeroInitialization(E);
  4881. case CK_BaseToDerivedMemberPointer: {
  4882. if (!Visit(E->getSubExpr()))
  4883. return false;
  4884. if (E->path_empty())
  4885. return true;
  4886. // Base-to-derived member pointer casts store the path in derived-to-base
  4887. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  4888. // the wrong end of the derived->base arc, so stagger the path by one class.
  4889. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  4890. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  4891. PathI != PathE; ++PathI) {
  4892. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  4893. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  4894. if (!Result.castToDerived(Derived))
  4895. return Error(E);
  4896. }
  4897. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  4898. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  4899. return Error(E);
  4900. return true;
  4901. }
  4902. case CK_DerivedToBaseMemberPointer:
  4903. if (!Visit(E->getSubExpr()))
  4904. return false;
  4905. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  4906. PathE = E->path_end(); PathI != PathE; ++PathI) {
  4907. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  4908. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  4909. if (!Result.castToBase(Base))
  4910. return Error(E);
  4911. }
  4912. return true;
  4913. }
  4914. }
  4915. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  4916. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  4917. // member can be formed.
  4918. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  4919. }
  4920. //===----------------------------------------------------------------------===//
  4921. // Record Evaluation
  4922. //===----------------------------------------------------------------------===//
  4923. namespace {
  4924. class RecordExprEvaluator
  4925. : public ExprEvaluatorBase<RecordExprEvaluator> {
  4926. const LValue &This;
  4927. APValue &Result;
  4928. public:
  4929. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  4930. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  4931. bool Success(const APValue &V, const Expr *E) {
  4932. Result = V;
  4933. return true;
  4934. }
  4935. bool ZeroInitialization(const Expr *E) {
  4936. return ZeroInitialization(E, E->getType());
  4937. }
  4938. bool ZeroInitialization(const Expr *E, QualType T);
  4939. bool VisitCallExpr(const CallExpr *E) {
  4940. return handleCallExpr(E, Result, &This);
  4941. }
  4942. bool VisitCastExpr(const CastExpr *E);
  4943. bool VisitInitListExpr(const InitListExpr *E);
  4944. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  4945. return VisitCXXConstructExpr(E, E->getType());
  4946. }
  4947. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  4948. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  4949. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  4950. };
  4951. }
  4952. /// Perform zero-initialization on an object of non-union class type.
  4953. /// C++11 [dcl.init]p5:
  4954. /// To zero-initialize an object or reference of type T means:
  4955. /// [...]
  4956. /// -- if T is a (possibly cv-qualified) non-union class type,
  4957. /// each non-static data member and each base-class subobject is
  4958. /// zero-initialized
  4959. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  4960. const RecordDecl *RD,
  4961. const LValue &This, APValue &Result) {
  4962. assert(!RD->isUnion() && "Expected non-union class type");
  4963. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  4964. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  4965. std::distance(RD->field_begin(), RD->field_end()));
  4966. if (RD->isInvalidDecl()) return false;
  4967. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4968. if (CD) {
  4969. unsigned Index = 0;
  4970. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  4971. End = CD->bases_end(); I != End; ++I, ++Index) {
  4972. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  4973. LValue Subobject = This;
  4974. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  4975. return false;
  4976. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  4977. Result.getStructBase(Index)))
  4978. return false;
  4979. }
  4980. }
  4981. for (const auto *I : RD->fields()) {
  4982. // -- if T is a reference type, no initialization is performed.
  4983. if (I->getType()->isReferenceType())
  4984. continue;
  4985. LValue Subobject = This;
  4986. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  4987. return false;
  4988. ImplicitValueInitExpr VIE(I->getType());
  4989. if (!EvaluateInPlace(
  4990. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  4991. return false;
  4992. }
  4993. return true;
  4994. }
  4995. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  4996. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  4997. if (RD->isInvalidDecl()) return false;
  4998. if (RD->isUnion()) {
  4999. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  5000. // object's first non-static named data member is zero-initialized
  5001. RecordDecl::field_iterator I = RD->field_begin();
  5002. if (I == RD->field_end()) {
  5003. Result = APValue((const FieldDecl*)nullptr);
  5004. return true;
  5005. }
  5006. LValue Subobject = This;
  5007. if (!HandleLValueMember(Info, E, Subobject, *I))
  5008. return false;
  5009. Result = APValue(*I);
  5010. ImplicitValueInitExpr VIE(I->getType());
  5011. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  5012. }
  5013. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  5014. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  5015. return false;
  5016. }
  5017. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  5018. }
  5019. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5020. switch (E->getCastKind()) {
  5021. default:
  5022. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5023. case CK_ConstructorConversion:
  5024. return Visit(E->getSubExpr());
  5025. case CK_DerivedToBase:
  5026. case CK_UncheckedDerivedToBase: {
  5027. APValue DerivedObject;
  5028. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  5029. return false;
  5030. if (!DerivedObject.isStruct())
  5031. return Error(E->getSubExpr());
  5032. // Derived-to-base rvalue conversion: just slice off the derived part.
  5033. APValue *Value = &DerivedObject;
  5034. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  5035. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5036. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5037. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  5038. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5039. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  5040. RD = Base;
  5041. }
  5042. Result = *Value;
  5043. return true;
  5044. }
  5045. }
  5046. }
  5047. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5048. if (E->isTransparent())
  5049. return Visit(E->getInit(0));
  5050. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  5051. if (RD->isInvalidDecl()) return false;
  5052. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5053. if (RD->isUnion()) {
  5054. const FieldDecl *Field = E->getInitializedFieldInUnion();
  5055. Result = APValue(Field);
  5056. if (!Field)
  5057. return true;
  5058. // If the initializer list for a union does not contain any elements, the
  5059. // first element of the union is value-initialized.
  5060. // FIXME: The element should be initialized from an initializer list.
  5061. // Is this difference ever observable for initializer lists which
  5062. // we don't build?
  5063. ImplicitValueInitExpr VIE(Field->getType());
  5064. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  5065. LValue Subobject = This;
  5066. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  5067. return false;
  5068. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5069. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5070. isa<CXXDefaultInitExpr>(InitExpr));
  5071. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  5072. }
  5073. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  5074. if (Result.isUninit())
  5075. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  5076. std::distance(RD->field_begin(), RD->field_end()));
  5077. unsigned ElementNo = 0;
  5078. bool Success = true;
  5079. // Initialize base classes.
  5080. if (CXXRD) {
  5081. for (const auto &Base : CXXRD->bases()) {
  5082. assert(ElementNo < E->getNumInits() && "missing init for base class");
  5083. const Expr *Init = E->getInit(ElementNo);
  5084. LValue Subobject = This;
  5085. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  5086. return false;
  5087. APValue &FieldVal = Result.getStructBase(ElementNo);
  5088. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  5089. if (!Info.noteFailure())
  5090. return false;
  5091. Success = false;
  5092. }
  5093. ++ElementNo;
  5094. }
  5095. }
  5096. // Initialize members.
  5097. for (const auto *Field : RD->fields()) {
  5098. // Anonymous bit-fields are not considered members of the class for
  5099. // purposes of aggregate initialization.
  5100. if (Field->isUnnamedBitfield())
  5101. continue;
  5102. LValue Subobject = This;
  5103. bool HaveInit = ElementNo < E->getNumInits();
  5104. // FIXME: Diagnostics here should point to the end of the initializer
  5105. // list, not the start.
  5106. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  5107. Subobject, Field, &Layout))
  5108. return false;
  5109. // Perform an implicit value-initialization for members beyond the end of
  5110. // the initializer list.
  5111. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  5112. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  5113. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5114. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5115. isa<CXXDefaultInitExpr>(Init));
  5116. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5117. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  5118. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  5119. FieldVal, Field))) {
  5120. if (!Info.noteFailure())
  5121. return false;
  5122. Success = false;
  5123. }
  5124. }
  5125. return Success;
  5126. }
  5127. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5128. QualType T) {
  5129. // Note that E's type is not necessarily the type of our class here; we might
  5130. // be initializing an array element instead.
  5131. const CXXConstructorDecl *FD = E->getConstructor();
  5132. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  5133. bool ZeroInit = E->requiresZeroInitialization();
  5134. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5135. // If we've already performed zero-initialization, we're already done.
  5136. if (!Result.isUninit())
  5137. return true;
  5138. // We can get here in two different ways:
  5139. // 1) We're performing value-initialization, and should zero-initialize
  5140. // the object, or
  5141. // 2) We're performing default-initialization of an object with a trivial
  5142. // constexpr default constructor, in which case we should start the
  5143. // lifetimes of all the base subobjects (there can be no data member
  5144. // subobjects in this case) per [basic.life]p1.
  5145. // Either way, ZeroInitialization is appropriate.
  5146. return ZeroInitialization(E, T);
  5147. }
  5148. const FunctionDecl *Definition = nullptr;
  5149. auto Body = FD->getBody(Definition);
  5150. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5151. return false;
  5152. // Avoid materializing a temporary for an elidable copy/move constructor.
  5153. if (E->isElidable() && !ZeroInit)
  5154. if (const MaterializeTemporaryExpr *ME
  5155. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  5156. return Visit(ME->GetTemporaryExpr());
  5157. if (ZeroInit && !ZeroInitialization(E, T))
  5158. return false;
  5159. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5160. return HandleConstructorCall(E, This, Args,
  5161. cast<CXXConstructorDecl>(Definition), Info,
  5162. Result);
  5163. }
  5164. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  5165. const CXXInheritedCtorInitExpr *E) {
  5166. if (!Info.CurrentCall) {
  5167. assert(Info.checkingPotentialConstantExpression());
  5168. return false;
  5169. }
  5170. const CXXConstructorDecl *FD = E->getConstructor();
  5171. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  5172. return false;
  5173. const FunctionDecl *Definition = nullptr;
  5174. auto Body = FD->getBody(Definition);
  5175. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5176. return false;
  5177. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  5178. cast<CXXConstructorDecl>(Definition), Info,
  5179. Result);
  5180. }
  5181. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  5182. const CXXStdInitializerListExpr *E) {
  5183. const ConstantArrayType *ArrayType =
  5184. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  5185. LValue Array;
  5186. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  5187. return false;
  5188. // Get a pointer to the first element of the array.
  5189. Array.addArray(Info, E, ArrayType);
  5190. // FIXME: Perform the checks on the field types in SemaInit.
  5191. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  5192. RecordDecl::field_iterator Field = Record->field_begin();
  5193. if (Field == Record->field_end())
  5194. return Error(E);
  5195. // Start pointer.
  5196. if (!Field->getType()->isPointerType() ||
  5197. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5198. ArrayType->getElementType()))
  5199. return Error(E);
  5200. // FIXME: What if the initializer_list type has base classes, etc?
  5201. Result = APValue(APValue::UninitStruct(), 0, 2);
  5202. Array.moveInto(Result.getStructField(0));
  5203. if (++Field == Record->field_end())
  5204. return Error(E);
  5205. if (Field->getType()->isPointerType() &&
  5206. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5207. ArrayType->getElementType())) {
  5208. // End pointer.
  5209. if (!HandleLValueArrayAdjustment(Info, E, Array,
  5210. ArrayType->getElementType(),
  5211. ArrayType->getSize().getZExtValue()))
  5212. return false;
  5213. Array.moveInto(Result.getStructField(1));
  5214. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  5215. // Length.
  5216. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  5217. else
  5218. return Error(E);
  5219. if (++Field != Record->field_end())
  5220. return Error(E);
  5221. return true;
  5222. }
  5223. static bool EvaluateRecord(const Expr *E, const LValue &This,
  5224. APValue &Result, EvalInfo &Info) {
  5225. assert(E->isRValue() && E->getType()->isRecordType() &&
  5226. "can't evaluate expression as a record rvalue");
  5227. return RecordExprEvaluator(Info, This, Result).Visit(E);
  5228. }
  5229. //===----------------------------------------------------------------------===//
  5230. // Temporary Evaluation
  5231. //
  5232. // Temporaries are represented in the AST as rvalues, but generally behave like
  5233. // lvalues. The full-object of which the temporary is a subobject is implicitly
  5234. // materialized so that a reference can bind to it.
  5235. //===----------------------------------------------------------------------===//
  5236. namespace {
  5237. class TemporaryExprEvaluator
  5238. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  5239. public:
  5240. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  5241. LValueExprEvaluatorBaseTy(Info, Result) {}
  5242. /// Visit an expression which constructs the value of this temporary.
  5243. bool VisitConstructExpr(const Expr *E) {
  5244. Result.set(E, Info.CurrentCall->Index);
  5245. return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
  5246. Info, Result, E);
  5247. }
  5248. bool VisitCastExpr(const CastExpr *E) {
  5249. switch (E->getCastKind()) {
  5250. default:
  5251. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  5252. case CK_ConstructorConversion:
  5253. return VisitConstructExpr(E->getSubExpr());
  5254. }
  5255. }
  5256. bool VisitInitListExpr(const InitListExpr *E) {
  5257. return VisitConstructExpr(E);
  5258. }
  5259. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5260. return VisitConstructExpr(E);
  5261. }
  5262. bool VisitCallExpr(const CallExpr *E) {
  5263. return VisitConstructExpr(E);
  5264. }
  5265. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  5266. return VisitConstructExpr(E);
  5267. }
  5268. };
  5269. } // end anonymous namespace
  5270. /// Evaluate an expression of record type as a temporary.
  5271. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  5272. assert(E->isRValue() && E->getType()->isRecordType());
  5273. return TemporaryExprEvaluator(Info, Result).Visit(E);
  5274. }
  5275. //===----------------------------------------------------------------------===//
  5276. // Vector Evaluation
  5277. //===----------------------------------------------------------------------===//
  5278. namespace {
  5279. class VectorExprEvaluator
  5280. : public ExprEvaluatorBase<VectorExprEvaluator> {
  5281. APValue &Result;
  5282. public:
  5283. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  5284. : ExprEvaluatorBaseTy(info), Result(Result) {}
  5285. bool Success(ArrayRef<APValue> V, const Expr *E) {
  5286. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  5287. // FIXME: remove this APValue copy.
  5288. Result = APValue(V.data(), V.size());
  5289. return true;
  5290. }
  5291. bool Success(const APValue &V, const Expr *E) {
  5292. assert(V.isVector());
  5293. Result = V;
  5294. return true;
  5295. }
  5296. bool ZeroInitialization(const Expr *E);
  5297. bool VisitUnaryReal(const UnaryOperator *E)
  5298. { return Visit(E->getSubExpr()); }
  5299. bool VisitCastExpr(const CastExpr* E);
  5300. bool VisitInitListExpr(const InitListExpr *E);
  5301. bool VisitUnaryImag(const UnaryOperator *E);
  5302. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  5303. // binary comparisons, binary and/or/xor,
  5304. // shufflevector, ExtVectorElementExpr
  5305. };
  5306. } // end anonymous namespace
  5307. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  5308. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  5309. return VectorExprEvaluator(Info, Result).Visit(E);
  5310. }
  5311. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5312. const VectorType *VTy = E->getType()->castAs<VectorType>();
  5313. unsigned NElts = VTy->getNumElements();
  5314. const Expr *SE = E->getSubExpr();
  5315. QualType SETy = SE->getType();
  5316. switch (E->getCastKind()) {
  5317. case CK_VectorSplat: {
  5318. APValue Val = APValue();
  5319. if (SETy->isIntegerType()) {
  5320. APSInt IntResult;
  5321. if (!EvaluateInteger(SE, IntResult, Info))
  5322. return false;
  5323. Val = APValue(std::move(IntResult));
  5324. } else if (SETy->isRealFloatingType()) {
  5325. APFloat FloatResult(0.0);
  5326. if (!EvaluateFloat(SE, FloatResult, Info))
  5327. return false;
  5328. Val = APValue(std::move(FloatResult));
  5329. } else {
  5330. return Error(E);
  5331. }
  5332. // Splat and create vector APValue.
  5333. SmallVector<APValue, 4> Elts(NElts, Val);
  5334. return Success(Elts, E);
  5335. }
  5336. case CK_BitCast: {
  5337. // Evaluate the operand into an APInt we can extract from.
  5338. llvm::APInt SValInt;
  5339. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  5340. return false;
  5341. // Extract the elements
  5342. QualType EltTy = VTy->getElementType();
  5343. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  5344. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  5345. SmallVector<APValue, 4> Elts;
  5346. if (EltTy->isRealFloatingType()) {
  5347. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  5348. unsigned FloatEltSize = EltSize;
  5349. if (&Sem == &APFloat::x87DoubleExtended())
  5350. FloatEltSize = 80;
  5351. for (unsigned i = 0; i < NElts; i++) {
  5352. llvm::APInt Elt;
  5353. if (BigEndian)
  5354. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  5355. else
  5356. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  5357. Elts.push_back(APValue(APFloat(Sem, Elt)));
  5358. }
  5359. } else if (EltTy->isIntegerType()) {
  5360. for (unsigned i = 0; i < NElts; i++) {
  5361. llvm::APInt Elt;
  5362. if (BigEndian)
  5363. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  5364. else
  5365. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  5366. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  5367. }
  5368. } else {
  5369. return Error(E);
  5370. }
  5371. return Success(Elts, E);
  5372. }
  5373. default:
  5374. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5375. }
  5376. }
  5377. bool
  5378. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5379. const VectorType *VT = E->getType()->castAs<VectorType>();
  5380. unsigned NumInits = E->getNumInits();
  5381. unsigned NumElements = VT->getNumElements();
  5382. QualType EltTy = VT->getElementType();
  5383. SmallVector<APValue, 4> Elements;
  5384. // The number of initializers can be less than the number of
  5385. // vector elements. For OpenCL, this can be due to nested vector
  5386. // initialization. For GCC compatibility, missing trailing elements
  5387. // should be initialized with zeroes.
  5388. unsigned CountInits = 0, CountElts = 0;
  5389. while (CountElts < NumElements) {
  5390. // Handle nested vector initialization.
  5391. if (CountInits < NumInits
  5392. && E->getInit(CountInits)->getType()->isVectorType()) {
  5393. APValue v;
  5394. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  5395. return Error(E);
  5396. unsigned vlen = v.getVectorLength();
  5397. for (unsigned j = 0; j < vlen; j++)
  5398. Elements.push_back(v.getVectorElt(j));
  5399. CountElts += vlen;
  5400. } else if (EltTy->isIntegerType()) {
  5401. llvm::APSInt sInt(32);
  5402. if (CountInits < NumInits) {
  5403. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  5404. return false;
  5405. } else // trailing integer zero.
  5406. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  5407. Elements.push_back(APValue(sInt));
  5408. CountElts++;
  5409. } else {
  5410. llvm::APFloat f(0.0);
  5411. if (CountInits < NumInits) {
  5412. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  5413. return false;
  5414. } else // trailing float zero.
  5415. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  5416. Elements.push_back(APValue(f));
  5417. CountElts++;
  5418. }
  5419. CountInits++;
  5420. }
  5421. return Success(Elements, E);
  5422. }
  5423. bool
  5424. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  5425. const VectorType *VT = E->getType()->getAs<VectorType>();
  5426. QualType EltTy = VT->getElementType();
  5427. APValue ZeroElement;
  5428. if (EltTy->isIntegerType())
  5429. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  5430. else
  5431. ZeroElement =
  5432. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  5433. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  5434. return Success(Elements, E);
  5435. }
  5436. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  5437. VisitIgnoredValue(E->getSubExpr());
  5438. return ZeroInitialization(E);
  5439. }
  5440. //===----------------------------------------------------------------------===//
  5441. // Array Evaluation
  5442. //===----------------------------------------------------------------------===//
  5443. namespace {
  5444. class ArrayExprEvaluator
  5445. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  5446. const LValue &This;
  5447. APValue &Result;
  5448. public:
  5449. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  5450. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  5451. bool Success(const APValue &V, const Expr *E) {
  5452. assert((V.isArray() || V.isLValue()) &&
  5453. "expected array or string literal");
  5454. Result = V;
  5455. return true;
  5456. }
  5457. bool ZeroInitialization(const Expr *E) {
  5458. const ConstantArrayType *CAT =
  5459. Info.Ctx.getAsConstantArrayType(E->getType());
  5460. if (!CAT)
  5461. return Error(E);
  5462. Result = APValue(APValue::UninitArray(), 0,
  5463. CAT->getSize().getZExtValue());
  5464. if (!Result.hasArrayFiller()) return true;
  5465. // Zero-initialize all elements.
  5466. LValue Subobject = This;
  5467. Subobject.addArray(Info, E, CAT);
  5468. ImplicitValueInitExpr VIE(CAT->getElementType());
  5469. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  5470. }
  5471. bool VisitCallExpr(const CallExpr *E) {
  5472. return handleCallExpr(E, Result, &This);
  5473. }
  5474. bool VisitInitListExpr(const InitListExpr *E);
  5475. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  5476. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  5477. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  5478. const LValue &Subobject,
  5479. APValue *Value, QualType Type);
  5480. };
  5481. } // end anonymous namespace
  5482. static bool EvaluateArray(const Expr *E, const LValue &This,
  5483. APValue &Result, EvalInfo &Info) {
  5484. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  5485. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  5486. }
  5487. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5488. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  5489. if (!CAT)
  5490. return Error(E);
  5491. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  5492. // an appropriately-typed string literal enclosed in braces.
  5493. if (E->isStringLiteralInit()) {
  5494. LValue LV;
  5495. if (!EvaluateLValue(E->getInit(0), LV, Info))
  5496. return false;
  5497. APValue Val;
  5498. LV.moveInto(Val);
  5499. return Success(Val, E);
  5500. }
  5501. bool Success = true;
  5502. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  5503. "zero-initialized array shouldn't have any initialized elts");
  5504. APValue Filler;
  5505. if (Result.isArray() && Result.hasArrayFiller())
  5506. Filler = Result.getArrayFiller();
  5507. unsigned NumEltsToInit = E->getNumInits();
  5508. unsigned NumElts = CAT->getSize().getZExtValue();
  5509. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  5510. // If the initializer might depend on the array index, run it for each
  5511. // array element. For now, just whitelist non-class value-initialization.
  5512. if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
  5513. NumEltsToInit = NumElts;
  5514. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  5515. // If the array was previously zero-initialized, preserve the
  5516. // zero-initialized values.
  5517. if (!Filler.isUninit()) {
  5518. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  5519. Result.getArrayInitializedElt(I) = Filler;
  5520. if (Result.hasArrayFiller())
  5521. Result.getArrayFiller() = Filler;
  5522. }
  5523. LValue Subobject = This;
  5524. Subobject.addArray(Info, E, CAT);
  5525. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  5526. const Expr *Init =
  5527. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  5528. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  5529. Info, Subobject, Init) ||
  5530. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  5531. CAT->getElementType(), 1)) {
  5532. if (!Info.noteFailure())
  5533. return false;
  5534. Success = false;
  5535. }
  5536. }
  5537. if (!Result.hasArrayFiller())
  5538. return Success;
  5539. // If we get here, we have a trivial filler, which we can just evaluate
  5540. // once and splat over the rest of the array elements.
  5541. assert(FillerExpr && "no array filler for incomplete init list");
  5542. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  5543. FillerExpr) && Success;
  5544. }
  5545. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  5546. if (E->getCommonExpr() &&
  5547. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  5548. Info, E->getCommonExpr()->getSourceExpr()))
  5549. return false;
  5550. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  5551. uint64_t Elements = CAT->getSize().getZExtValue();
  5552. Result = APValue(APValue::UninitArray(), Elements, Elements);
  5553. LValue Subobject = This;
  5554. Subobject.addArray(Info, E, CAT);
  5555. bool Success = true;
  5556. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  5557. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  5558. Info, Subobject, E->getSubExpr()) ||
  5559. !HandleLValueArrayAdjustment(Info, E, Subobject,
  5560. CAT->getElementType(), 1)) {
  5561. if (!Info.noteFailure())
  5562. return false;
  5563. Success = false;
  5564. }
  5565. }
  5566. return Success;
  5567. }
  5568. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5569. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  5570. }
  5571. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5572. const LValue &Subobject,
  5573. APValue *Value,
  5574. QualType Type) {
  5575. bool HadZeroInit = !Value->isUninit();
  5576. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  5577. unsigned N = CAT->getSize().getZExtValue();
  5578. // Preserve the array filler if we had prior zero-initialization.
  5579. APValue Filler =
  5580. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  5581. : APValue();
  5582. *Value = APValue(APValue::UninitArray(), N, N);
  5583. if (HadZeroInit)
  5584. for (unsigned I = 0; I != N; ++I)
  5585. Value->getArrayInitializedElt(I) = Filler;
  5586. // Initialize the elements.
  5587. LValue ArrayElt = Subobject;
  5588. ArrayElt.addArray(Info, E, CAT);
  5589. for (unsigned I = 0; I != N; ++I)
  5590. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  5591. CAT->getElementType()) ||
  5592. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  5593. CAT->getElementType(), 1))
  5594. return false;
  5595. return true;
  5596. }
  5597. if (!Type->isRecordType())
  5598. return Error(E);
  5599. return RecordExprEvaluator(Info, Subobject, *Value)
  5600. .VisitCXXConstructExpr(E, Type);
  5601. }
  5602. //===----------------------------------------------------------------------===//
  5603. // Integer Evaluation
  5604. //
  5605. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  5606. // types and back in constant folding. Integer values are thus represented
  5607. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  5608. //===----------------------------------------------------------------------===//
  5609. namespace {
  5610. class IntExprEvaluator
  5611. : public ExprEvaluatorBase<IntExprEvaluator> {
  5612. APValue &Result;
  5613. public:
  5614. IntExprEvaluator(EvalInfo &info, APValue &result)
  5615. : ExprEvaluatorBaseTy(info), Result(result) {}
  5616. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  5617. assert(E->getType()->isIntegralOrEnumerationType() &&
  5618. "Invalid evaluation result.");
  5619. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  5620. "Invalid evaluation result.");
  5621. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  5622. "Invalid evaluation result.");
  5623. Result = APValue(SI);
  5624. return true;
  5625. }
  5626. bool Success(const llvm::APSInt &SI, const Expr *E) {
  5627. return Success(SI, E, Result);
  5628. }
  5629. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  5630. assert(E->getType()->isIntegralOrEnumerationType() &&
  5631. "Invalid evaluation result.");
  5632. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  5633. "Invalid evaluation result.");
  5634. Result = APValue(APSInt(I));
  5635. Result.getInt().setIsUnsigned(
  5636. E->getType()->isUnsignedIntegerOrEnumerationType());
  5637. return true;
  5638. }
  5639. bool Success(const llvm::APInt &I, const Expr *E) {
  5640. return Success(I, E, Result);
  5641. }
  5642. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  5643. assert(E->getType()->isIntegralOrEnumerationType() &&
  5644. "Invalid evaluation result.");
  5645. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  5646. return true;
  5647. }
  5648. bool Success(uint64_t Value, const Expr *E) {
  5649. return Success(Value, E, Result);
  5650. }
  5651. bool Success(CharUnits Size, const Expr *E) {
  5652. return Success(Size.getQuantity(), E);
  5653. }
  5654. bool Success(const APValue &V, const Expr *E) {
  5655. if (V.isLValue() || V.isAddrLabelDiff()) {
  5656. Result = V;
  5657. return true;
  5658. }
  5659. return Success(V.getInt(), E);
  5660. }
  5661. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  5662. //===--------------------------------------------------------------------===//
  5663. // Visitor Methods
  5664. //===--------------------------------------------------------------------===//
  5665. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  5666. return Success(E->getValue(), E);
  5667. }
  5668. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  5669. return Success(E->getValue(), E);
  5670. }
  5671. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  5672. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5673. if (CheckReferencedDecl(E, E->getDecl()))
  5674. return true;
  5675. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  5676. }
  5677. bool VisitMemberExpr(const MemberExpr *E) {
  5678. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  5679. VisitIgnoredBaseExpression(E->getBase());
  5680. return true;
  5681. }
  5682. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  5683. }
  5684. bool VisitCallExpr(const CallExpr *E);
  5685. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5686. bool VisitBinaryOperator(const BinaryOperator *E);
  5687. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  5688. bool VisitUnaryOperator(const UnaryOperator *E);
  5689. bool VisitCastExpr(const CastExpr* E);
  5690. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  5691. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  5692. return Success(E->getValue(), E);
  5693. }
  5694. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  5695. return Success(E->getValue(), E);
  5696. }
  5697. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  5698. if (Info.ArrayInitIndex == uint64_t(-1)) {
  5699. // We were asked to evaluate this subexpression independent of the
  5700. // enclosing ArrayInitLoopExpr. We can't do that.
  5701. Info.FFDiag(E);
  5702. return false;
  5703. }
  5704. return Success(Info.ArrayInitIndex, E);
  5705. }
  5706. // Note, GNU defines __null as an integer, not a pointer.
  5707. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  5708. return ZeroInitialization(E);
  5709. }
  5710. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  5711. return Success(E->getValue(), E);
  5712. }
  5713. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  5714. return Success(E->getValue(), E);
  5715. }
  5716. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  5717. return Success(E->getValue(), E);
  5718. }
  5719. bool VisitUnaryReal(const UnaryOperator *E);
  5720. bool VisitUnaryImag(const UnaryOperator *E);
  5721. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  5722. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  5723. private:
  5724. bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
  5725. // FIXME: Missing: array subscript of vector, member of vector
  5726. };
  5727. } // end anonymous namespace
  5728. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  5729. /// produce either the integer value or a pointer.
  5730. ///
  5731. /// GCC has a heinous extension which folds casts between pointer types and
  5732. /// pointer-sized integral types. We support this by allowing the evaluation of
  5733. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  5734. /// Some simple arithmetic on such values is supported (they are treated much
  5735. /// like char*).
  5736. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  5737. EvalInfo &Info) {
  5738. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  5739. return IntExprEvaluator(Info, Result).Visit(E);
  5740. }
  5741. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  5742. APValue Val;
  5743. if (!EvaluateIntegerOrLValue(E, Val, Info))
  5744. return false;
  5745. if (!Val.isInt()) {
  5746. // FIXME: It would be better to produce the diagnostic for casting
  5747. // a pointer to an integer.
  5748. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5749. return false;
  5750. }
  5751. Result = Val.getInt();
  5752. return true;
  5753. }
  5754. /// Check whether the given declaration can be directly converted to an integral
  5755. /// rvalue. If not, no diagnostic is produced; there are other things we can
  5756. /// try.
  5757. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  5758. // Enums are integer constant exprs.
  5759. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  5760. // Check for signedness/width mismatches between E type and ECD value.
  5761. bool SameSign = (ECD->getInitVal().isSigned()
  5762. == E->getType()->isSignedIntegerOrEnumerationType());
  5763. bool SameWidth = (ECD->getInitVal().getBitWidth()
  5764. == Info.Ctx.getIntWidth(E->getType()));
  5765. if (SameSign && SameWidth)
  5766. return Success(ECD->getInitVal(), E);
  5767. else {
  5768. // Get rid of mismatch (otherwise Success assertions will fail)
  5769. // by computing a new value matching the type of E.
  5770. llvm::APSInt Val = ECD->getInitVal();
  5771. if (!SameSign)
  5772. Val.setIsSigned(!ECD->getInitVal().isSigned());
  5773. if (!SameWidth)
  5774. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  5775. return Success(Val, E);
  5776. }
  5777. }
  5778. return false;
  5779. }
  5780. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  5781. /// as GCC.
  5782. static int EvaluateBuiltinClassifyType(const CallExpr *E,
  5783. const LangOptions &LangOpts) {
  5784. // The following enum mimics the values returned by GCC.
  5785. // FIXME: Does GCC differ between lvalue and rvalue references here?
  5786. enum gcc_type_class {
  5787. no_type_class = -1,
  5788. void_type_class, integer_type_class, char_type_class,
  5789. enumeral_type_class, boolean_type_class,
  5790. pointer_type_class, reference_type_class, offset_type_class,
  5791. real_type_class, complex_type_class,
  5792. function_type_class, method_type_class,
  5793. record_type_class, union_type_class,
  5794. array_type_class, string_type_class,
  5795. lang_type_class
  5796. };
  5797. // If no argument was supplied, default to "no_type_class". This isn't
  5798. // ideal, however it is what gcc does.
  5799. if (E->getNumArgs() == 0)
  5800. return no_type_class;
  5801. QualType CanTy = E->getArg(0)->getType().getCanonicalType();
  5802. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  5803. switch (CanTy->getTypeClass()) {
  5804. #define TYPE(ID, BASE)
  5805. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  5806. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  5807. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  5808. #include "clang/AST/TypeNodes.def"
  5809. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5810. case Type::Builtin:
  5811. switch (BT->getKind()) {
  5812. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  5813. #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
  5814. #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
  5815. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
  5816. #include "clang/AST/BuiltinTypes.def"
  5817. case BuiltinType::Void:
  5818. return void_type_class;
  5819. case BuiltinType::Bool:
  5820. return boolean_type_class;
  5821. case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
  5822. case BuiltinType::UChar:
  5823. case BuiltinType::UShort:
  5824. case BuiltinType::UInt:
  5825. case BuiltinType::ULong:
  5826. case BuiltinType::ULongLong:
  5827. case BuiltinType::UInt128:
  5828. return integer_type_class;
  5829. case BuiltinType::NullPtr:
  5830. return pointer_type_class;
  5831. case BuiltinType::WChar_U:
  5832. case BuiltinType::Char16:
  5833. case BuiltinType::Char32:
  5834. case BuiltinType::ObjCId:
  5835. case BuiltinType::ObjCClass:
  5836. case BuiltinType::ObjCSel:
  5837. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5838. case BuiltinType::Id:
  5839. #include "clang/Basic/OpenCLImageTypes.def"
  5840. case BuiltinType::OCLSampler:
  5841. case BuiltinType::OCLEvent:
  5842. case BuiltinType::OCLClkEvent:
  5843. case BuiltinType::OCLQueue:
  5844. case BuiltinType::OCLNDRange:
  5845. case BuiltinType::OCLReserveID:
  5846. case BuiltinType::Dependent:
  5847. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5848. };
  5849. case Type::Enum:
  5850. return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
  5851. break;
  5852. case Type::Pointer:
  5853. return pointer_type_class;
  5854. break;
  5855. case Type::MemberPointer:
  5856. if (CanTy->isMemberDataPointerType())
  5857. return offset_type_class;
  5858. else {
  5859. // We expect member pointers to be either data or function pointers,
  5860. // nothing else.
  5861. assert(CanTy->isMemberFunctionPointerType());
  5862. return method_type_class;
  5863. }
  5864. case Type::Complex:
  5865. return complex_type_class;
  5866. case Type::FunctionNoProto:
  5867. case Type::FunctionProto:
  5868. return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
  5869. case Type::Record:
  5870. if (const RecordType *RT = CanTy->getAs<RecordType>()) {
  5871. switch (RT->getDecl()->getTagKind()) {
  5872. case TagTypeKind::TTK_Struct:
  5873. case TagTypeKind::TTK_Class:
  5874. case TagTypeKind::TTK_Interface:
  5875. return record_type_class;
  5876. case TagTypeKind::TTK_Enum:
  5877. return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
  5878. case TagTypeKind::TTK_Union:
  5879. return union_type_class;
  5880. }
  5881. }
  5882. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5883. case Type::ConstantArray:
  5884. case Type::VariableArray:
  5885. case Type::IncompleteArray:
  5886. return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
  5887. case Type::BlockPointer:
  5888. case Type::LValueReference:
  5889. case Type::RValueReference:
  5890. case Type::Vector:
  5891. case Type::ExtVector:
  5892. case Type::Auto:
  5893. case Type::ObjCObject:
  5894. case Type::ObjCInterface:
  5895. case Type::ObjCObjectPointer:
  5896. case Type::Pipe:
  5897. case Type::Atomic:
  5898. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5899. }
  5900. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  5901. }
  5902. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  5903. /// __builtin_constant_p when applied to the given lvalue.
  5904. ///
  5905. /// An lvalue is only "constant" if it is a pointer or reference to the first
  5906. /// character of a string literal.
  5907. template<typename LValue>
  5908. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  5909. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  5910. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  5911. }
  5912. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  5913. /// GCC as we can manage.
  5914. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  5915. QualType ArgType = Arg->getType();
  5916. // __builtin_constant_p always has one operand. The rules which gcc follows
  5917. // are not precisely documented, but are as follows:
  5918. //
  5919. // - If the operand is of integral, floating, complex or enumeration type,
  5920. // and can be folded to a known value of that type, it returns 1.
  5921. // - If the operand and can be folded to a pointer to the first character
  5922. // of a string literal (or such a pointer cast to an integral type), it
  5923. // returns 1.
  5924. //
  5925. // Otherwise, it returns 0.
  5926. //
  5927. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  5928. // its support for this does not currently work.
  5929. if (ArgType->isIntegralOrEnumerationType()) {
  5930. Expr::EvalResult Result;
  5931. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  5932. return false;
  5933. APValue &V = Result.Val;
  5934. if (V.getKind() == APValue::Int)
  5935. return true;
  5936. if (V.getKind() == APValue::LValue)
  5937. return EvaluateBuiltinConstantPForLValue(V);
  5938. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  5939. return Arg->isEvaluatable(Ctx);
  5940. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  5941. LValue LV;
  5942. Expr::EvalStatus Status;
  5943. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  5944. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  5945. : EvaluatePointer(Arg, LV, Info)) &&
  5946. !Status.HasSideEffects)
  5947. return EvaluateBuiltinConstantPForLValue(LV);
  5948. }
  5949. // Anything else isn't considered to be sufficiently constant.
  5950. return false;
  5951. }
  5952. /// Retrieves the "underlying object type" of the given expression,
  5953. /// as used by __builtin_object_size.
  5954. static QualType getObjectType(APValue::LValueBase B) {
  5955. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  5956. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  5957. return VD->getType();
  5958. } else if (const Expr *E = B.get<const Expr*>()) {
  5959. if (isa<CompoundLiteralExpr>(E))
  5960. return E->getType();
  5961. }
  5962. return QualType();
  5963. }
  5964. /// A more selective version of E->IgnoreParenCasts for
  5965. /// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  5966. /// to change the type of E.
  5967. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  5968. ///
  5969. /// Always returns an RValue with a pointer representation.
  5970. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  5971. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5972. auto *NoParens = E->IgnoreParens();
  5973. auto *Cast = dyn_cast<CastExpr>(NoParens);
  5974. if (Cast == nullptr)
  5975. return NoParens;
  5976. // We only conservatively allow a few kinds of casts, because this code is
  5977. // inherently a simple solution that seeks to support the common case.
  5978. auto CastKind = Cast->getCastKind();
  5979. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  5980. CastKind != CK_AddressSpaceConversion)
  5981. return NoParens;
  5982. auto *SubExpr = Cast->getSubExpr();
  5983. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  5984. return NoParens;
  5985. return ignorePointerCastsAndParens(SubExpr);
  5986. }
  5987. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  5988. /// record layout. e.g.
  5989. /// struct { struct { int a, b; } fst, snd; } obj;
  5990. /// obj.fst // no
  5991. /// obj.snd // yes
  5992. /// obj.fst.a // no
  5993. /// obj.fst.b // no
  5994. /// obj.snd.a // no
  5995. /// obj.snd.b // yes
  5996. ///
  5997. /// Please note: this function is specialized for how __builtin_object_size
  5998. /// views "objects".
  5999. ///
  6000. /// If this encounters an invalid RecordDecl, it will always return true.
  6001. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  6002. assert(!LVal.Designator.Invalid);
  6003. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  6004. const RecordDecl *Parent = FD->getParent();
  6005. Invalid = Parent->isInvalidDecl();
  6006. if (Invalid || Parent->isUnion())
  6007. return true;
  6008. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  6009. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  6010. };
  6011. auto &Base = LVal.getLValueBase();
  6012. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  6013. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  6014. bool Invalid;
  6015. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6016. return Invalid;
  6017. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  6018. for (auto *FD : IFD->chain()) {
  6019. bool Invalid;
  6020. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  6021. return Invalid;
  6022. }
  6023. }
  6024. }
  6025. QualType BaseType = getType(Base);
  6026. for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
  6027. if (BaseType->isArrayType()) {
  6028. // Because __builtin_object_size treats arrays as objects, we can ignore
  6029. // the index iff this is the last array in the Designator.
  6030. if (I + 1 == E)
  6031. return true;
  6032. auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  6033. uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
  6034. if (Index + 1 != CAT->getSize())
  6035. return false;
  6036. BaseType = CAT->getElementType();
  6037. } else if (BaseType->isAnyComplexType()) {
  6038. auto *CT = BaseType->castAs<ComplexType>();
  6039. uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
  6040. if (Index != 1)
  6041. return false;
  6042. BaseType = CT->getElementType();
  6043. } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
  6044. bool Invalid;
  6045. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6046. return Invalid;
  6047. BaseType = FD->getType();
  6048. } else {
  6049. assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
  6050. "Expecting cast to a base class");
  6051. return false;
  6052. }
  6053. }
  6054. return true;
  6055. }
  6056. /// Tests to see if the LValue has a designator (that isn't necessarily valid).
  6057. static bool refersToCompleteObject(const LValue &LVal) {
  6058. if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
  6059. return false;
  6060. if (!LVal.InvalidBase)
  6061. return true;
  6062. auto *E = LVal.Base.dyn_cast<const Expr *>();
  6063. (void)E;
  6064. assert(E != nullptr && isa<MemberExpr>(E));
  6065. return false;
  6066. }
  6067. /// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
  6068. /// true and stores the result in @p Size.
  6069. ///
  6070. /// If @p WasError is non-null, this will report whether the failure to evaluate
  6071. /// is to be treated as an Error in IntExprEvaluator.
  6072. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  6073. EvalInfo &Info, uint64_t &Size,
  6074. bool *WasError = nullptr) {
  6075. if (WasError != nullptr)
  6076. *WasError = false;
  6077. auto Error = [&](const Expr *E) {
  6078. if (WasError != nullptr)
  6079. *WasError = true;
  6080. return false;
  6081. };
  6082. auto Success = [&](uint64_t S, const Expr *E) {
  6083. Size = S;
  6084. return true;
  6085. };
  6086. // Determine the denoted object.
  6087. LValue Base;
  6088. {
  6089. // The operand of __builtin_object_size is never evaluated for side-effects.
  6090. // If there are any, but we can determine the pointed-to object anyway, then
  6091. // ignore the side-effects.
  6092. SpeculativeEvaluationRAII SpeculativeEval(Info);
  6093. FoldOffsetRAII Fold(Info, Type & 1);
  6094. if (E->isGLValue()) {
  6095. // It's possible for us to be given GLValues if we're called via
  6096. // Expr::tryEvaluateObjectSize.
  6097. APValue RVal;
  6098. if (!EvaluateAsRValue(Info, E, RVal))
  6099. return false;
  6100. Base.setFrom(Info.Ctx, RVal);
  6101. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
  6102. return false;
  6103. }
  6104. CharUnits BaseOffset = Base.getLValueOffset();
  6105. // If we point to before the start of the object, there are no accessible
  6106. // bytes.
  6107. if (BaseOffset.isNegative())
  6108. return Success(0, E);
  6109. // In the case where we're not dealing with a subobject, we discard the
  6110. // subobject bit.
  6111. bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
  6112. // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
  6113. // exist. If we can't verify the base, then we can't do that.
  6114. //
  6115. // As a special case, we produce a valid object size for an unknown object
  6116. // with a known designator if Type & 1 is 1. For instance:
  6117. //
  6118. // extern struct X { char buff[32]; int a, b, c; } *p;
  6119. // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
  6120. // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
  6121. //
  6122. // This matches GCC's behavior.
  6123. if (Base.InvalidBase && !SubobjectOnly)
  6124. return Error(E);
  6125. // If we're not examining only the subobject, then we reset to a complete
  6126. // object designator
  6127. //
  6128. // If Type is 1 and we've lost track of the subobject, just find the complete
  6129. // object instead. (If Type is 3, that's not correct behavior and we should
  6130. // return 0 instead.)
  6131. LValue End = Base;
  6132. if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
  6133. QualType T = getObjectType(End.getLValueBase());
  6134. if (T.isNull())
  6135. End.Designator.setInvalid();
  6136. else {
  6137. End.Designator = SubobjectDesignator(T);
  6138. End.Offset = CharUnits::Zero();
  6139. }
  6140. }
  6141. // If it is not possible to determine which objects ptr points to at compile
  6142. // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
  6143. // and (size_t) 0 for type 2 or 3.
  6144. if (End.Designator.Invalid)
  6145. return false;
  6146. // According to the GCC documentation, we want the size of the subobject
  6147. // denoted by the pointer. But that's not quite right -- what we actually
  6148. // want is the size of the immediately-enclosing array, if there is one.
  6149. int64_t AmountToAdd = 1;
  6150. if (End.Designator.MostDerivedIsArrayElement &&
  6151. End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
  6152. // We got a pointer to an array. Step to its end.
  6153. AmountToAdd = End.Designator.MostDerivedArraySize -
  6154. End.Designator.Entries.back().ArrayIndex;
  6155. } else if (End.Designator.isOnePastTheEnd()) {
  6156. // We're already pointing at the end of the object.
  6157. AmountToAdd = 0;
  6158. }
  6159. QualType PointeeType = End.Designator.MostDerivedType;
  6160. assert(!PointeeType.isNull());
  6161. if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
  6162. return Error(E);
  6163. if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
  6164. AmountToAdd))
  6165. return false;
  6166. auto EndOffset = End.getLValueOffset();
  6167. // The following is a moderately common idiom in C:
  6168. //
  6169. // struct Foo { int a; char c[1]; };
  6170. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  6171. // strcpy(&F->c[0], Bar);
  6172. //
  6173. // So, if we see that we're examining an array at the end of a struct with an
  6174. // unknown base, we give up instead of breaking code that behaves this way.
  6175. // Note that we only do this when Type=1, because Type=3 is a lower bound, so
  6176. // answering conservatively is fine.
  6177. //
  6178. // We used to be a bit more aggressive here; we'd only be conservative if the
  6179. // array at the end was flexible, or if it had 0 or 1 elements. This broke
  6180. // some common standard library extensions (PR30346), but was otherwise
  6181. // seemingly fine. It may be useful to reintroduce this behavior with some
  6182. // sort of whitelist. OTOH, it seems that GCC is always conservative with the
  6183. // last element in structs (if it's an array), so our current behavior is more
  6184. // compatible than a whitelisting approach would be.
  6185. if (End.InvalidBase && SubobjectOnly && Type == 1 &&
  6186. End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
  6187. End.Designator.MostDerivedIsArrayElement &&
  6188. isDesignatorAtObjectEnd(Info.Ctx, End))
  6189. return false;
  6190. if (BaseOffset > EndOffset)
  6191. return Success(0, E);
  6192. return Success((EndOffset - BaseOffset).getQuantity(), E);
  6193. }
  6194. bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
  6195. unsigned Type) {
  6196. uint64_t Size;
  6197. bool WasError;
  6198. if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
  6199. return Success(Size, E);
  6200. if (WasError)
  6201. return Error(E);
  6202. return false;
  6203. }
  6204. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6205. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6206. return VisitBuiltinCallExpr(E, BuiltinOp);
  6207. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  6208. }
  6209. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6210. unsigned BuiltinOp) {
  6211. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  6212. default:
  6213. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  6214. case Builtin::BI__builtin_object_size: {
  6215. // The type was checked when we built the expression.
  6216. unsigned Type =
  6217. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  6218. assert(Type <= 3 && "unexpected type");
  6219. if (TryEvaluateBuiltinObjectSize(E, Type))
  6220. return true;
  6221. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  6222. return Success((Type & 2) ? 0 : -1, E);
  6223. // Expression had no side effects, but we couldn't statically determine the
  6224. // size of the referenced object.
  6225. switch (Info.EvalMode) {
  6226. case EvalInfo::EM_ConstantExpression:
  6227. case EvalInfo::EM_PotentialConstantExpression:
  6228. case EvalInfo::EM_ConstantFold:
  6229. case EvalInfo::EM_EvaluateForOverflow:
  6230. case EvalInfo::EM_IgnoreSideEffects:
  6231. case EvalInfo::EM_DesignatorFold:
  6232. // Leave it to IR generation.
  6233. return Error(E);
  6234. case EvalInfo::EM_ConstantExpressionUnevaluated:
  6235. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  6236. // Reduce it to a constant now.
  6237. return Success((Type & 2) ? 0 : -1, E);
  6238. }
  6239. llvm_unreachable("unexpected EvalMode");
  6240. }
  6241. case Builtin::BI__builtin_bswap16:
  6242. case Builtin::BI__builtin_bswap32:
  6243. case Builtin::BI__builtin_bswap64: {
  6244. APSInt Val;
  6245. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6246. return false;
  6247. return Success(Val.byteSwap(), E);
  6248. }
  6249. case Builtin::BI__builtin_classify_type:
  6250. return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  6251. // FIXME: BI__builtin_clrsb
  6252. // FIXME: BI__builtin_clrsbl
  6253. // FIXME: BI__builtin_clrsbll
  6254. case Builtin::BI__builtin_clz:
  6255. case Builtin::BI__builtin_clzl:
  6256. case Builtin::BI__builtin_clzll:
  6257. case Builtin::BI__builtin_clzs: {
  6258. APSInt Val;
  6259. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6260. return false;
  6261. if (!Val)
  6262. return Error(E);
  6263. return Success(Val.countLeadingZeros(), E);
  6264. }
  6265. case Builtin::BI__builtin_constant_p:
  6266. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  6267. case Builtin::BI__builtin_ctz:
  6268. case Builtin::BI__builtin_ctzl:
  6269. case Builtin::BI__builtin_ctzll:
  6270. case Builtin::BI__builtin_ctzs: {
  6271. APSInt Val;
  6272. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6273. return false;
  6274. if (!Val)
  6275. return Error(E);
  6276. return Success(Val.countTrailingZeros(), E);
  6277. }
  6278. case Builtin::BI__builtin_eh_return_data_regno: {
  6279. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  6280. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  6281. return Success(Operand, E);
  6282. }
  6283. case Builtin::BI__builtin_expect:
  6284. return Visit(E->getArg(0));
  6285. case Builtin::BI__builtin_ffs:
  6286. case Builtin::BI__builtin_ffsl:
  6287. case Builtin::BI__builtin_ffsll: {
  6288. APSInt Val;
  6289. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6290. return false;
  6291. unsigned N = Val.countTrailingZeros();
  6292. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  6293. }
  6294. case Builtin::BI__builtin_fpclassify: {
  6295. APFloat Val(0.0);
  6296. if (!EvaluateFloat(E->getArg(5), Val, Info))
  6297. return false;
  6298. unsigned Arg;
  6299. switch (Val.getCategory()) {
  6300. case APFloat::fcNaN: Arg = 0; break;
  6301. case APFloat::fcInfinity: Arg = 1; break;
  6302. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  6303. case APFloat::fcZero: Arg = 4; break;
  6304. }
  6305. return Visit(E->getArg(Arg));
  6306. }
  6307. case Builtin::BI__builtin_isinf_sign: {
  6308. APFloat Val(0.0);
  6309. return EvaluateFloat(E->getArg(0), Val, Info) &&
  6310. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  6311. }
  6312. case Builtin::BI__builtin_isinf: {
  6313. APFloat Val(0.0);
  6314. return EvaluateFloat(E->getArg(0), Val, Info) &&
  6315. Success(Val.isInfinity() ? 1 : 0, E);
  6316. }
  6317. case Builtin::BI__builtin_isfinite: {
  6318. APFloat Val(0.0);
  6319. return EvaluateFloat(E->getArg(0), Val, Info) &&
  6320. Success(Val.isFinite() ? 1 : 0, E);
  6321. }
  6322. case Builtin::BI__builtin_isnan: {
  6323. APFloat Val(0.0);
  6324. return EvaluateFloat(E->getArg(0), Val, Info) &&
  6325. Success(Val.isNaN() ? 1 : 0, E);
  6326. }
  6327. case Builtin::BI__builtin_isnormal: {
  6328. APFloat Val(0.0);
  6329. return EvaluateFloat(E->getArg(0), Val, Info) &&
  6330. Success(Val.isNormal() ? 1 : 0, E);
  6331. }
  6332. case Builtin::BI__builtin_parity:
  6333. case Builtin::BI__builtin_parityl:
  6334. case Builtin::BI__builtin_parityll: {
  6335. APSInt Val;
  6336. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6337. return false;
  6338. return Success(Val.countPopulation() % 2, E);
  6339. }
  6340. case Builtin::BI__builtin_popcount:
  6341. case Builtin::BI__builtin_popcountl:
  6342. case Builtin::BI__builtin_popcountll: {
  6343. APSInt Val;
  6344. if (!EvaluateInteger(E->getArg(0), Val, Info))
  6345. return false;
  6346. return Success(Val.countPopulation(), E);
  6347. }
  6348. case Builtin::BIstrlen:
  6349. case Builtin::BIwcslen:
  6350. // A call to strlen is not a constant expression.
  6351. if (Info.getLangOpts().CPlusPlus11)
  6352. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6353. << /*isConstexpr*/0 << /*isConstructor*/0
  6354. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6355. else
  6356. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6357. // Fall through.
  6358. case Builtin::BI__builtin_strlen:
  6359. case Builtin::BI__builtin_wcslen: {
  6360. // As an extension, we support __builtin_strlen() as a constant expression,
  6361. // and support folding strlen() to a constant.
  6362. LValue String;
  6363. if (!EvaluatePointer(E->getArg(0), String, Info))
  6364. return false;
  6365. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  6366. // Fast path: if it's a string literal, search the string value.
  6367. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  6368. String.getLValueBase().dyn_cast<const Expr *>())) {
  6369. // The string literal may have embedded null characters. Find the first
  6370. // one and truncate there.
  6371. StringRef Str = S->getBytes();
  6372. int64_t Off = String.Offset.getQuantity();
  6373. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  6374. S->getCharByteWidth() == 1 &&
  6375. // FIXME: Add fast-path for wchar_t too.
  6376. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  6377. Str = Str.substr(Off);
  6378. StringRef::size_type Pos = Str.find(0);
  6379. if (Pos != StringRef::npos)
  6380. Str = Str.substr(0, Pos);
  6381. return Success(Str.size(), E);
  6382. }
  6383. // Fall through to slow path to issue appropriate diagnostic.
  6384. }
  6385. // Slow path: scan the bytes of the string looking for the terminating 0.
  6386. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  6387. APValue Char;
  6388. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  6389. !Char.isInt())
  6390. return false;
  6391. if (!Char.getInt())
  6392. return Success(Strlen, E);
  6393. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  6394. return false;
  6395. }
  6396. }
  6397. case Builtin::BIstrcmp:
  6398. case Builtin::BIwcscmp:
  6399. case Builtin::BIstrncmp:
  6400. case Builtin::BIwcsncmp:
  6401. case Builtin::BImemcmp:
  6402. case Builtin::BIwmemcmp:
  6403. // A call to strlen is not a constant expression.
  6404. if (Info.getLangOpts().CPlusPlus11)
  6405. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6406. << /*isConstexpr*/0 << /*isConstructor*/0
  6407. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6408. else
  6409. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6410. // Fall through.
  6411. case Builtin::BI__builtin_strcmp:
  6412. case Builtin::BI__builtin_wcscmp:
  6413. case Builtin::BI__builtin_strncmp:
  6414. case Builtin::BI__builtin_wcsncmp:
  6415. case Builtin::BI__builtin_memcmp:
  6416. case Builtin::BI__builtin_wmemcmp: {
  6417. LValue String1, String2;
  6418. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  6419. !EvaluatePointer(E->getArg(1), String2, Info))
  6420. return false;
  6421. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  6422. uint64_t MaxLength = uint64_t(-1);
  6423. if (BuiltinOp != Builtin::BIstrcmp &&
  6424. BuiltinOp != Builtin::BIwcscmp &&
  6425. BuiltinOp != Builtin::BI__builtin_strcmp &&
  6426. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  6427. APSInt N;
  6428. if (!EvaluateInteger(E->getArg(2), N, Info))
  6429. return false;
  6430. MaxLength = N.getExtValue();
  6431. }
  6432. bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
  6433. BuiltinOp != Builtin::BIwmemcmp &&
  6434. BuiltinOp != Builtin::BI__builtin_memcmp &&
  6435. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  6436. for (; MaxLength; --MaxLength) {
  6437. APValue Char1, Char2;
  6438. if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
  6439. !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
  6440. !Char1.isInt() || !Char2.isInt())
  6441. return false;
  6442. if (Char1.getInt() != Char2.getInt())
  6443. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  6444. if (StopAtNull && !Char1.getInt())
  6445. return Success(0, E);
  6446. assert(!(StopAtNull && !Char2.getInt()));
  6447. if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
  6448. !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
  6449. return false;
  6450. }
  6451. // We hit the strncmp / memcmp limit.
  6452. return Success(0, E);
  6453. }
  6454. case Builtin::BI__atomic_always_lock_free:
  6455. case Builtin::BI__atomic_is_lock_free:
  6456. case Builtin::BI__c11_atomic_is_lock_free: {
  6457. APSInt SizeVal;
  6458. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  6459. return false;
  6460. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  6461. // of two less than the maximum inline atomic width, we know it is
  6462. // lock-free. If the size isn't a power of two, or greater than the
  6463. // maximum alignment where we promote atomics, we know it is not lock-free
  6464. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  6465. // the answer can only be determined at runtime; for example, 16-byte
  6466. // atomics have lock-free implementations on some, but not all,
  6467. // x86-64 processors.
  6468. // Check power-of-two.
  6469. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  6470. if (Size.isPowerOfTwo()) {
  6471. // Check against inlining width.
  6472. unsigned InlineWidthBits =
  6473. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  6474. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  6475. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  6476. Size == CharUnits::One() ||
  6477. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  6478. Expr::NPC_NeverValueDependent))
  6479. // OK, we will inline appropriately-aligned operations of this size,
  6480. // and _Atomic(T) is appropriately-aligned.
  6481. return Success(1, E);
  6482. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  6483. castAs<PointerType>()->getPointeeType();
  6484. if (!PointeeType->isIncompleteType() &&
  6485. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  6486. // OK, we will inline operations on this object.
  6487. return Success(1, E);
  6488. }
  6489. }
  6490. }
  6491. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  6492. Success(0, E) : Error(E);
  6493. }
  6494. }
  6495. }
  6496. static bool HasSameBase(const LValue &A, const LValue &B) {
  6497. if (!A.getLValueBase())
  6498. return !B.getLValueBase();
  6499. if (!B.getLValueBase())
  6500. return false;
  6501. if (A.getLValueBase().getOpaqueValue() !=
  6502. B.getLValueBase().getOpaqueValue()) {
  6503. const Decl *ADecl = GetLValueBaseDecl(A);
  6504. if (!ADecl)
  6505. return false;
  6506. const Decl *BDecl = GetLValueBaseDecl(B);
  6507. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  6508. return false;
  6509. }
  6510. return IsGlobalLValue(A.getLValueBase()) ||
  6511. A.getLValueCallIndex() == B.getLValueCallIndex();
  6512. }
  6513. /// \brief Determine whether this is a pointer past the end of the complete
  6514. /// object referred to by the lvalue.
  6515. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  6516. const LValue &LV) {
  6517. // A null pointer can be viewed as being "past the end" but we don't
  6518. // choose to look at it that way here.
  6519. if (!LV.getLValueBase())
  6520. return false;
  6521. // If the designator is valid and refers to a subobject, we're not pointing
  6522. // past the end.
  6523. if (!LV.getLValueDesignator().Invalid &&
  6524. !LV.getLValueDesignator().isOnePastTheEnd())
  6525. return false;
  6526. // A pointer to an incomplete type might be past-the-end if the type's size is
  6527. // zero. We cannot tell because the type is incomplete.
  6528. QualType Ty = getType(LV.getLValueBase());
  6529. if (Ty->isIncompleteType())
  6530. return true;
  6531. // We're a past-the-end pointer if we point to the byte after the object,
  6532. // no matter what our type or path is.
  6533. auto Size = Ctx.getTypeSizeInChars(Ty);
  6534. return LV.getLValueOffset() == Size;
  6535. }
  6536. namespace {
  6537. /// \brief Data recursive integer evaluator of certain binary operators.
  6538. ///
  6539. /// We use a data recursive algorithm for binary operators so that we are able
  6540. /// to handle extreme cases of chained binary operators without causing stack
  6541. /// overflow.
  6542. class DataRecursiveIntBinOpEvaluator {
  6543. struct EvalResult {
  6544. APValue Val;
  6545. bool Failed;
  6546. EvalResult() : Failed(false) { }
  6547. void swap(EvalResult &RHS) {
  6548. Val.swap(RHS.Val);
  6549. Failed = RHS.Failed;
  6550. RHS.Failed = false;
  6551. }
  6552. };
  6553. struct Job {
  6554. const Expr *E;
  6555. EvalResult LHSResult; // meaningful only for binary operator expression.
  6556. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  6557. Job() = default;
  6558. Job(Job &&) = default;
  6559. void startSpeculativeEval(EvalInfo &Info) {
  6560. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  6561. }
  6562. private:
  6563. SpeculativeEvaluationRAII SpecEvalRAII;
  6564. };
  6565. SmallVector<Job, 16> Queue;
  6566. IntExprEvaluator &IntEval;
  6567. EvalInfo &Info;
  6568. APValue &FinalResult;
  6569. public:
  6570. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  6571. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  6572. /// \brief True if \param E is a binary operator that we are going to handle
  6573. /// data recursively.
  6574. /// We handle binary operators that are comma, logical, or that have operands
  6575. /// with integral or enumeration type.
  6576. static bool shouldEnqueue(const BinaryOperator *E) {
  6577. return E->getOpcode() == BO_Comma ||
  6578. E->isLogicalOp() ||
  6579. (E->isRValue() &&
  6580. E->getType()->isIntegralOrEnumerationType() &&
  6581. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6582. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6583. }
  6584. bool Traverse(const BinaryOperator *E) {
  6585. enqueue(E);
  6586. EvalResult PrevResult;
  6587. while (!Queue.empty())
  6588. process(PrevResult);
  6589. if (PrevResult.Failed) return false;
  6590. FinalResult.swap(PrevResult.Val);
  6591. return true;
  6592. }
  6593. private:
  6594. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6595. return IntEval.Success(Value, E, Result);
  6596. }
  6597. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  6598. return IntEval.Success(Value, E, Result);
  6599. }
  6600. bool Error(const Expr *E) {
  6601. return IntEval.Error(E);
  6602. }
  6603. bool Error(const Expr *E, diag::kind D) {
  6604. return IntEval.Error(E, D);
  6605. }
  6606. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  6607. return Info.CCEDiag(E, D);
  6608. }
  6609. // \brief Returns true if visiting the RHS is necessary, false otherwise.
  6610. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  6611. bool &SuppressRHSDiags);
  6612. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  6613. const BinaryOperator *E, APValue &Result);
  6614. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  6615. Result.Failed = !Evaluate(Result.Val, Info, E);
  6616. if (Result.Failed)
  6617. Result.Val = APValue();
  6618. }
  6619. void process(EvalResult &Result);
  6620. void enqueue(const Expr *E) {
  6621. E = E->IgnoreParens();
  6622. Queue.resize(Queue.size()+1);
  6623. Queue.back().E = E;
  6624. Queue.back().Kind = Job::AnyExprKind;
  6625. }
  6626. };
  6627. }
  6628. bool DataRecursiveIntBinOpEvaluator::
  6629. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  6630. bool &SuppressRHSDiags) {
  6631. if (E->getOpcode() == BO_Comma) {
  6632. // Ignore LHS but note if we could not evaluate it.
  6633. if (LHSResult.Failed)
  6634. return Info.noteSideEffect();
  6635. return true;
  6636. }
  6637. if (E->isLogicalOp()) {
  6638. bool LHSAsBool;
  6639. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  6640. // We were able to evaluate the LHS, see if we can get away with not
  6641. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  6642. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  6643. Success(LHSAsBool, E, LHSResult.Val);
  6644. return false; // Ignore RHS
  6645. }
  6646. } else {
  6647. LHSResult.Failed = true;
  6648. // Since we weren't able to evaluate the left hand side, it
  6649. // might have had side effects.
  6650. if (!Info.noteSideEffect())
  6651. return false;
  6652. // We can't evaluate the LHS; however, sometimes the result
  6653. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  6654. // Don't ignore RHS and suppress diagnostics from this arm.
  6655. SuppressRHSDiags = true;
  6656. }
  6657. return true;
  6658. }
  6659. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6660. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6661. if (LHSResult.Failed && !Info.noteFailure())
  6662. return false; // Ignore RHS;
  6663. return true;
  6664. }
  6665. bool DataRecursiveIntBinOpEvaluator::
  6666. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  6667. const BinaryOperator *E, APValue &Result) {
  6668. if (E->getOpcode() == BO_Comma) {
  6669. if (RHSResult.Failed)
  6670. return false;
  6671. Result = RHSResult.Val;
  6672. return true;
  6673. }
  6674. if (E->isLogicalOp()) {
  6675. bool lhsResult, rhsResult;
  6676. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  6677. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  6678. if (LHSIsOK) {
  6679. if (RHSIsOK) {
  6680. if (E->getOpcode() == BO_LOr)
  6681. return Success(lhsResult || rhsResult, E, Result);
  6682. else
  6683. return Success(lhsResult && rhsResult, E, Result);
  6684. }
  6685. } else {
  6686. if (RHSIsOK) {
  6687. // We can't evaluate the LHS; however, sometimes the result
  6688. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  6689. if (rhsResult == (E->getOpcode() == BO_LOr))
  6690. return Success(rhsResult, E, Result);
  6691. }
  6692. }
  6693. return false;
  6694. }
  6695. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  6696. E->getRHS()->getType()->isIntegralOrEnumerationType());
  6697. if (LHSResult.Failed || RHSResult.Failed)
  6698. return false;
  6699. const APValue &LHSVal = LHSResult.Val;
  6700. const APValue &RHSVal = RHSResult.Val;
  6701. // Handle cases like (unsigned long)&a + 4.
  6702. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  6703. Result = LHSVal;
  6704. CharUnits AdditionalOffset =
  6705. CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
  6706. if (E->getOpcode() == BO_Add)
  6707. Result.getLValueOffset() += AdditionalOffset;
  6708. else
  6709. Result.getLValueOffset() -= AdditionalOffset;
  6710. return true;
  6711. }
  6712. // Handle cases like 4 + (unsigned long)&a
  6713. if (E->getOpcode() == BO_Add &&
  6714. RHSVal.isLValue() && LHSVal.isInt()) {
  6715. Result = RHSVal;
  6716. Result.getLValueOffset() +=
  6717. CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
  6718. return true;
  6719. }
  6720. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  6721. // Handle (intptr_t)&&A - (intptr_t)&&B.
  6722. if (!LHSVal.getLValueOffset().isZero() ||
  6723. !RHSVal.getLValueOffset().isZero())
  6724. return false;
  6725. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  6726. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  6727. if (!LHSExpr || !RHSExpr)
  6728. return false;
  6729. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  6730. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  6731. if (!LHSAddrExpr || !RHSAddrExpr)
  6732. return false;
  6733. // Make sure both labels come from the same function.
  6734. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  6735. RHSAddrExpr->getLabel()->getDeclContext())
  6736. return false;
  6737. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  6738. return true;
  6739. }
  6740. // All the remaining cases expect both operands to be an integer
  6741. if (!LHSVal.isInt() || !RHSVal.isInt())
  6742. return Error(E);
  6743. // Set up the width and signedness manually, in case it can't be deduced
  6744. // from the operation we're performing.
  6745. // FIXME: Don't do this in the cases where we can deduce it.
  6746. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  6747. E->getType()->isUnsignedIntegerOrEnumerationType());
  6748. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  6749. RHSVal.getInt(), Value))
  6750. return false;
  6751. return Success(Value, E, Result);
  6752. }
  6753. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  6754. Job &job = Queue.back();
  6755. switch (job.Kind) {
  6756. case Job::AnyExprKind: {
  6757. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  6758. if (shouldEnqueue(Bop)) {
  6759. job.Kind = Job::BinOpKind;
  6760. enqueue(Bop->getLHS());
  6761. return;
  6762. }
  6763. }
  6764. EvaluateExpr(job.E, Result);
  6765. Queue.pop_back();
  6766. return;
  6767. }
  6768. case Job::BinOpKind: {
  6769. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  6770. bool SuppressRHSDiags = false;
  6771. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  6772. Queue.pop_back();
  6773. return;
  6774. }
  6775. if (SuppressRHSDiags)
  6776. job.startSpeculativeEval(Info);
  6777. job.LHSResult.swap(Result);
  6778. job.Kind = Job::BinOpVisitedLHSKind;
  6779. enqueue(Bop->getRHS());
  6780. return;
  6781. }
  6782. case Job::BinOpVisitedLHSKind: {
  6783. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  6784. EvalResult RHS;
  6785. RHS.swap(Result);
  6786. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  6787. Queue.pop_back();
  6788. return;
  6789. }
  6790. }
  6791. llvm_unreachable("Invalid Job::Kind!");
  6792. }
  6793. namespace {
  6794. /// Used when we determine that we should fail, but can keep evaluating prior to
  6795. /// noting that we had a failure.
  6796. class DelayedNoteFailureRAII {
  6797. EvalInfo &Info;
  6798. bool NoteFailure;
  6799. public:
  6800. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  6801. : Info(Info), NoteFailure(NoteFailure) {}
  6802. ~DelayedNoteFailureRAII() {
  6803. if (NoteFailure) {
  6804. bool ContinueAfterFailure = Info.noteFailure();
  6805. (void)ContinueAfterFailure;
  6806. assert(ContinueAfterFailure &&
  6807. "Shouldn't have kept evaluating on failure.");
  6808. }
  6809. }
  6810. };
  6811. }
  6812. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  6813. // We don't call noteFailure immediately because the assignment happens after
  6814. // we evaluate LHS and RHS.
  6815. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  6816. return Error(E);
  6817. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  6818. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  6819. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  6820. QualType LHSTy = E->getLHS()->getType();
  6821. QualType RHSTy = E->getRHS()->getType();
  6822. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  6823. ComplexValue LHS, RHS;
  6824. bool LHSOK;
  6825. if (E->isAssignmentOp()) {
  6826. LValue LV;
  6827. EvaluateLValue(E->getLHS(), LV, Info);
  6828. LHSOK = false;
  6829. } else if (LHSTy->isRealFloatingType()) {
  6830. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  6831. if (LHSOK) {
  6832. LHS.makeComplexFloat();
  6833. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  6834. }
  6835. } else {
  6836. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  6837. }
  6838. if (!LHSOK && !Info.noteFailure())
  6839. return false;
  6840. if (E->getRHS()->getType()->isRealFloatingType()) {
  6841. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  6842. return false;
  6843. RHS.makeComplexFloat();
  6844. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  6845. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  6846. return false;
  6847. if (LHS.isComplexFloat()) {
  6848. APFloat::cmpResult CR_r =
  6849. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  6850. APFloat::cmpResult CR_i =
  6851. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  6852. if (E->getOpcode() == BO_EQ)
  6853. return Success((CR_r == APFloat::cmpEqual &&
  6854. CR_i == APFloat::cmpEqual), E);
  6855. else {
  6856. assert(E->getOpcode() == BO_NE &&
  6857. "Invalid complex comparison.");
  6858. return Success(((CR_r == APFloat::cmpGreaterThan ||
  6859. CR_r == APFloat::cmpLessThan ||
  6860. CR_r == APFloat::cmpUnordered) ||
  6861. (CR_i == APFloat::cmpGreaterThan ||
  6862. CR_i == APFloat::cmpLessThan ||
  6863. CR_i == APFloat::cmpUnordered)), E);
  6864. }
  6865. } else {
  6866. if (E->getOpcode() == BO_EQ)
  6867. return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  6868. LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
  6869. else {
  6870. assert(E->getOpcode() == BO_NE &&
  6871. "Invalid compex comparison.");
  6872. return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
  6873. LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
  6874. }
  6875. }
  6876. }
  6877. if (LHSTy->isRealFloatingType() &&
  6878. RHSTy->isRealFloatingType()) {
  6879. APFloat RHS(0.0), LHS(0.0);
  6880. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  6881. if (!LHSOK && !Info.noteFailure())
  6882. return false;
  6883. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  6884. return false;
  6885. APFloat::cmpResult CR = LHS.compare(RHS);
  6886. switch (E->getOpcode()) {
  6887. default:
  6888. llvm_unreachable("Invalid binary operator!");
  6889. case BO_LT:
  6890. return Success(CR == APFloat::cmpLessThan, E);
  6891. case BO_GT:
  6892. return Success(CR == APFloat::cmpGreaterThan, E);
  6893. case BO_LE:
  6894. return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
  6895. case BO_GE:
  6896. return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
  6897. E);
  6898. case BO_EQ:
  6899. return Success(CR == APFloat::cmpEqual, E);
  6900. case BO_NE:
  6901. return Success(CR == APFloat::cmpGreaterThan
  6902. || CR == APFloat::cmpLessThan
  6903. || CR == APFloat::cmpUnordered, E);
  6904. }
  6905. }
  6906. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  6907. if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
  6908. LValue LHSValue, RHSValue;
  6909. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  6910. if (!LHSOK && !Info.noteFailure())
  6911. return false;
  6912. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  6913. return false;
  6914. // Reject differing bases from the normal codepath; we special-case
  6915. // comparisons to null.
  6916. if (!HasSameBase(LHSValue, RHSValue)) {
  6917. if (E->getOpcode() == BO_Sub) {
  6918. // Handle &&A - &&B.
  6919. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  6920. return Error(E);
  6921. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  6922. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
  6923. if (!LHSExpr || !RHSExpr)
  6924. return Error(E);
  6925. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  6926. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  6927. if (!LHSAddrExpr || !RHSAddrExpr)
  6928. return Error(E);
  6929. // Make sure both labels come from the same function.
  6930. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  6931. RHSAddrExpr->getLabel()->getDeclContext())
  6932. return Error(E);
  6933. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  6934. }
  6935. // Inequalities and subtractions between unrelated pointers have
  6936. // unspecified or undefined behavior.
  6937. if (!E->isEqualityOp())
  6938. return Error(E);
  6939. // A constant address may compare equal to the address of a symbol.
  6940. // The one exception is that address of an object cannot compare equal
  6941. // to a null pointer constant.
  6942. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  6943. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  6944. return Error(E);
  6945. // It's implementation-defined whether distinct literals will have
  6946. // distinct addresses. In clang, the result of such a comparison is
  6947. // unspecified, so it is not a constant expression. However, we do know
  6948. // that the address of a literal will be non-null.
  6949. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  6950. LHSValue.Base && RHSValue.Base)
  6951. return Error(E);
  6952. // We can't tell whether weak symbols will end up pointing to the same
  6953. // object.
  6954. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  6955. return Error(E);
  6956. // We can't compare the address of the start of one object with the
  6957. // past-the-end address of another object, per C++ DR1652.
  6958. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  6959. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  6960. (RHSValue.Base && RHSValue.Offset.isZero() &&
  6961. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  6962. return Error(E);
  6963. // We can't tell whether an object is at the same address as another
  6964. // zero sized object.
  6965. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  6966. (LHSValue.Base && isZeroSized(RHSValue)))
  6967. return Error(E);
  6968. // Pointers with different bases cannot represent the same object.
  6969. // (Note that clang defaults to -fmerge-all-constants, which can
  6970. // lead to inconsistent results for comparisons involving the address
  6971. // of a constant; this generally doesn't matter in practice.)
  6972. return Success(E->getOpcode() == BO_NE, E);
  6973. }
  6974. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  6975. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  6976. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  6977. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  6978. if (E->getOpcode() == BO_Sub) {
  6979. // C++11 [expr.add]p6:
  6980. // Unless both pointers point to elements of the same array object, or
  6981. // one past the last element of the array object, the behavior is
  6982. // undefined.
  6983. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  6984. !AreElementsOfSameArray(getType(LHSValue.Base),
  6985. LHSDesignator, RHSDesignator))
  6986. CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  6987. QualType Type = E->getLHS()->getType();
  6988. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  6989. CharUnits ElementSize;
  6990. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  6991. return false;
  6992. // As an extension, a type may have zero size (empty struct or union in
  6993. // C, array of zero length). Pointer subtraction in such cases has
  6994. // undefined behavior, so is not constant.
  6995. if (ElementSize.isZero()) {
  6996. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  6997. << ElementType;
  6998. return false;
  6999. }
  7000. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  7001. // and produce incorrect results when it overflows. Such behavior
  7002. // appears to be non-conforming, but is common, so perhaps we should
  7003. // assume the standard intended for such cases to be undefined behavior
  7004. // and check for them.
  7005. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  7006. // overflow in the final conversion to ptrdiff_t.
  7007. APSInt LHS(
  7008. llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  7009. APSInt RHS(
  7010. llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  7011. APSInt ElemSize(
  7012. llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
  7013. APSInt TrueResult = (LHS - RHS) / ElemSize;
  7014. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  7015. if (Result.extend(65) != TrueResult &&
  7016. !HandleOverflow(Info, E, TrueResult, E->getType()))
  7017. return false;
  7018. return Success(Result, E);
  7019. }
  7020. // C++11 [expr.rel]p3:
  7021. // Pointers to void (after pointer conversions) can be compared, with a
  7022. // result defined as follows: If both pointers represent the same
  7023. // address or are both the null pointer value, the result is true if the
  7024. // operator is <= or >= and false otherwise; otherwise the result is
  7025. // unspecified.
  7026. // We interpret this as applying to pointers to *cv* void.
  7027. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
  7028. E->isRelationalOp())
  7029. CCEDiag(E, diag::note_constexpr_void_comparison);
  7030. // C++11 [expr.rel]p2:
  7031. // - If two pointers point to non-static data members of the same object,
  7032. // or to subobjects or array elements fo such members, recursively, the
  7033. // pointer to the later declared member compares greater provided the
  7034. // two members have the same access control and provided their class is
  7035. // not a union.
  7036. // [...]
  7037. // - Otherwise pointer comparisons are unspecified.
  7038. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  7039. E->isRelationalOp()) {
  7040. bool WasArrayIndex;
  7041. unsigned Mismatch =
  7042. FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
  7043. RHSDesignator, WasArrayIndex);
  7044. // At the point where the designators diverge, the comparison has a
  7045. // specified value if:
  7046. // - we are comparing array indices
  7047. // - we are comparing fields of a union, or fields with the same access
  7048. // Otherwise, the result is unspecified and thus the comparison is not a
  7049. // constant expression.
  7050. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  7051. Mismatch < RHSDesignator.Entries.size()) {
  7052. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  7053. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  7054. if (!LF && !RF)
  7055. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  7056. else if (!LF)
  7057. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  7058. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  7059. << RF->getParent() << RF;
  7060. else if (!RF)
  7061. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  7062. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  7063. << LF->getParent() << LF;
  7064. else if (!LF->getParent()->isUnion() &&
  7065. LF->getAccess() != RF->getAccess())
  7066. CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
  7067. << LF << LF->getAccess() << RF << RF->getAccess()
  7068. << LF->getParent();
  7069. }
  7070. }
  7071. // The comparison here must be unsigned, and performed with the same
  7072. // width as the pointer.
  7073. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  7074. uint64_t CompareLHS = LHSOffset.getQuantity();
  7075. uint64_t CompareRHS = RHSOffset.getQuantity();
  7076. assert(PtrSize <= 64 && "Unexpected pointer width");
  7077. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  7078. CompareLHS &= Mask;
  7079. CompareRHS &= Mask;
  7080. // If there is a base and this is a relational operator, we can only
  7081. // compare pointers within the object in question; otherwise, the result
  7082. // depends on where the object is located in memory.
  7083. if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
  7084. QualType BaseTy = getType(LHSValue.Base);
  7085. if (BaseTy->isIncompleteType())
  7086. return Error(E);
  7087. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  7088. uint64_t OffsetLimit = Size.getQuantity();
  7089. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  7090. return Error(E);
  7091. }
  7092. switch (E->getOpcode()) {
  7093. default: llvm_unreachable("missing comparison operator");
  7094. case BO_LT: return Success(CompareLHS < CompareRHS, E);
  7095. case BO_GT: return Success(CompareLHS > CompareRHS, E);
  7096. case BO_LE: return Success(CompareLHS <= CompareRHS, E);
  7097. case BO_GE: return Success(CompareLHS >= CompareRHS, E);
  7098. case BO_EQ: return Success(CompareLHS == CompareRHS, E);
  7099. case BO_NE: return Success(CompareLHS != CompareRHS, E);
  7100. }
  7101. }
  7102. }
  7103. if (LHSTy->isMemberPointerType()) {
  7104. assert(E->isEqualityOp() && "unexpected member pointer operation");
  7105. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  7106. MemberPtr LHSValue, RHSValue;
  7107. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  7108. if (!LHSOK && !Info.noteFailure())
  7109. return false;
  7110. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7111. return false;
  7112. // C++11 [expr.eq]p2:
  7113. // If both operands are null, they compare equal. Otherwise if only one is
  7114. // null, they compare unequal.
  7115. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  7116. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  7117. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  7118. }
  7119. // Otherwise if either is a pointer to a virtual member function, the
  7120. // result is unspecified.
  7121. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  7122. if (MD->isVirtual())
  7123. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  7124. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  7125. if (MD->isVirtual())
  7126. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  7127. // Otherwise they compare equal if and only if they would refer to the
  7128. // same member of the same most derived object or the same subobject if
  7129. // they were dereferenced with a hypothetical object of the associated
  7130. // class type.
  7131. bool Equal = LHSValue == RHSValue;
  7132. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  7133. }
  7134. if (LHSTy->isNullPtrType()) {
  7135. assert(E->isComparisonOp() && "unexpected nullptr operation");
  7136. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  7137. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  7138. // are compared, the result is true of the operator is <=, >= or ==, and
  7139. // false otherwise.
  7140. BinaryOperator::Opcode Opcode = E->getOpcode();
  7141. return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
  7142. }
  7143. assert((!LHSTy->isIntegralOrEnumerationType() ||
  7144. !RHSTy->isIntegralOrEnumerationType()) &&
  7145. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  7146. // We can't continue from here for non-integral types.
  7147. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7148. }
  7149. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  7150. /// a result as the expression's type.
  7151. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  7152. const UnaryExprOrTypeTraitExpr *E) {
  7153. switch(E->getKind()) {
  7154. case UETT_AlignOf: {
  7155. if (E->isArgumentType())
  7156. return Success(GetAlignOfType(Info, E->getArgumentType()), E);
  7157. else
  7158. return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
  7159. }
  7160. case UETT_VecStep: {
  7161. QualType Ty = E->getTypeOfArgument();
  7162. if (Ty->isVectorType()) {
  7163. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  7164. // The vec_step built-in functions that take a 3-component
  7165. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  7166. if (n == 3)
  7167. n = 4;
  7168. return Success(n, E);
  7169. } else
  7170. return Success(1, E);
  7171. }
  7172. case UETT_SizeOf: {
  7173. QualType SrcTy = E->getTypeOfArgument();
  7174. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  7175. // the result is the size of the referenced type."
  7176. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  7177. SrcTy = Ref->getPointeeType();
  7178. CharUnits Sizeof;
  7179. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  7180. return false;
  7181. return Success(Sizeof, E);
  7182. }
  7183. case UETT_OpenMPRequiredSimdAlign:
  7184. assert(E->isArgumentType());
  7185. return Success(
  7186. Info.Ctx.toCharUnitsFromBits(
  7187. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  7188. .getQuantity(),
  7189. E);
  7190. }
  7191. llvm_unreachable("unknown expr/type trait");
  7192. }
  7193. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  7194. CharUnits Result;
  7195. unsigned n = OOE->getNumComponents();
  7196. if (n == 0)
  7197. return Error(OOE);
  7198. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  7199. for (unsigned i = 0; i != n; ++i) {
  7200. OffsetOfNode ON = OOE->getComponent(i);
  7201. switch (ON.getKind()) {
  7202. case OffsetOfNode::Array: {
  7203. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  7204. APSInt IdxResult;
  7205. if (!EvaluateInteger(Idx, IdxResult, Info))
  7206. return false;
  7207. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  7208. if (!AT)
  7209. return Error(OOE);
  7210. CurrentType = AT->getElementType();
  7211. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  7212. Result += IdxResult.getSExtValue() * ElementSize;
  7213. break;
  7214. }
  7215. case OffsetOfNode::Field: {
  7216. FieldDecl *MemberDecl = ON.getField();
  7217. const RecordType *RT = CurrentType->getAs<RecordType>();
  7218. if (!RT)
  7219. return Error(OOE);
  7220. RecordDecl *RD = RT->getDecl();
  7221. if (RD->isInvalidDecl()) return false;
  7222. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  7223. unsigned i = MemberDecl->getFieldIndex();
  7224. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  7225. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  7226. CurrentType = MemberDecl->getType().getNonReferenceType();
  7227. break;
  7228. }
  7229. case OffsetOfNode::Identifier:
  7230. llvm_unreachable("dependent __builtin_offsetof");
  7231. case OffsetOfNode::Base: {
  7232. CXXBaseSpecifier *BaseSpec = ON.getBase();
  7233. if (BaseSpec->isVirtual())
  7234. return Error(OOE);
  7235. // Find the layout of the class whose base we are looking into.
  7236. const RecordType *RT = CurrentType->getAs<RecordType>();
  7237. if (!RT)
  7238. return Error(OOE);
  7239. RecordDecl *RD = RT->getDecl();
  7240. if (RD->isInvalidDecl()) return false;
  7241. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  7242. // Find the base class itself.
  7243. CurrentType = BaseSpec->getType();
  7244. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  7245. if (!BaseRT)
  7246. return Error(OOE);
  7247. // Add the offset to the base.
  7248. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  7249. break;
  7250. }
  7251. }
  7252. }
  7253. return Success(Result, OOE);
  7254. }
  7255. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  7256. switch (E->getOpcode()) {
  7257. default:
  7258. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  7259. // See C99 6.6p3.
  7260. return Error(E);
  7261. case UO_Extension:
  7262. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  7263. // If so, we could clear the diagnostic ID.
  7264. return Visit(E->getSubExpr());
  7265. case UO_Plus:
  7266. // The result is just the value.
  7267. return Visit(E->getSubExpr());
  7268. case UO_Minus: {
  7269. if (!Visit(E->getSubExpr()))
  7270. return false;
  7271. if (!Result.isInt()) return Error(E);
  7272. const APSInt &Value = Result.getInt();
  7273. if (Value.isSigned() && Value.isMinSignedValue() &&
  7274. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  7275. E->getType()))
  7276. return false;
  7277. return Success(-Value, E);
  7278. }
  7279. case UO_Not: {
  7280. if (!Visit(E->getSubExpr()))
  7281. return false;
  7282. if (!Result.isInt()) return Error(E);
  7283. return Success(~Result.getInt(), E);
  7284. }
  7285. case UO_LNot: {
  7286. bool bres;
  7287. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  7288. return false;
  7289. return Success(!bres, E);
  7290. }
  7291. }
  7292. }
  7293. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  7294. /// result type is integer.
  7295. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7296. const Expr *SubExpr = E->getSubExpr();
  7297. QualType DestType = E->getType();
  7298. QualType SrcType = SubExpr->getType();
  7299. switch (E->getCastKind()) {
  7300. case CK_BaseToDerived:
  7301. case CK_DerivedToBase:
  7302. case CK_UncheckedDerivedToBase:
  7303. case CK_Dynamic:
  7304. case CK_ToUnion:
  7305. case CK_ArrayToPointerDecay:
  7306. case CK_FunctionToPointerDecay:
  7307. case CK_NullToPointer:
  7308. case CK_NullToMemberPointer:
  7309. case CK_BaseToDerivedMemberPointer:
  7310. case CK_DerivedToBaseMemberPointer:
  7311. case CK_ReinterpretMemberPointer:
  7312. case CK_ConstructorConversion:
  7313. case CK_IntegralToPointer:
  7314. case CK_ToVoid:
  7315. case CK_VectorSplat:
  7316. case CK_IntegralToFloating:
  7317. case CK_FloatingCast:
  7318. case CK_CPointerToObjCPointerCast:
  7319. case CK_BlockPointerToObjCPointerCast:
  7320. case CK_AnyPointerToBlockPointerCast:
  7321. case CK_ObjCObjectLValueCast:
  7322. case CK_FloatingRealToComplex:
  7323. case CK_FloatingComplexToReal:
  7324. case CK_FloatingComplexCast:
  7325. case CK_FloatingComplexToIntegralComplex:
  7326. case CK_IntegralRealToComplex:
  7327. case CK_IntegralComplexCast:
  7328. case CK_IntegralComplexToFloatingComplex:
  7329. case CK_BuiltinFnToFnPtr:
  7330. case CK_ZeroToOCLEvent:
  7331. case CK_NonAtomicToAtomic:
  7332. case CK_AddressSpaceConversion:
  7333. case CK_IntToOCLSampler:
  7334. llvm_unreachable("invalid cast kind for integral value");
  7335. case CK_BitCast:
  7336. case CK_Dependent:
  7337. case CK_LValueBitCast:
  7338. case CK_ARCProduceObject:
  7339. case CK_ARCConsumeObject:
  7340. case CK_ARCReclaimReturnedObject:
  7341. case CK_ARCExtendBlockObject:
  7342. case CK_CopyAndAutoreleaseBlockObject:
  7343. return Error(E);
  7344. case CK_UserDefinedConversion:
  7345. case CK_LValueToRValue:
  7346. case CK_AtomicToNonAtomic:
  7347. case CK_NoOp:
  7348. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7349. case CK_MemberPointerToBoolean:
  7350. case CK_PointerToBoolean:
  7351. case CK_IntegralToBoolean:
  7352. case CK_FloatingToBoolean:
  7353. case CK_BooleanToSignedIntegral:
  7354. case CK_FloatingComplexToBoolean:
  7355. case CK_IntegralComplexToBoolean: {
  7356. bool BoolResult;
  7357. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  7358. return false;
  7359. uint64_t IntResult = BoolResult;
  7360. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  7361. IntResult = (uint64_t)-1;
  7362. return Success(IntResult, E);
  7363. }
  7364. case CK_IntegralCast: {
  7365. if (!Visit(SubExpr))
  7366. return false;
  7367. if (!Result.isInt()) {
  7368. // Allow casts of address-of-label differences if they are no-ops
  7369. // or narrowing. (The narrowing case isn't actually guaranteed to
  7370. // be constant-evaluatable except in some narrow cases which are hard
  7371. // to detect here. We let it through on the assumption the user knows
  7372. // what they are doing.)
  7373. if (Result.isAddrLabelDiff())
  7374. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  7375. // Only allow casts of lvalues if they are lossless.
  7376. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  7377. }
  7378. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  7379. Result.getInt()), E);
  7380. }
  7381. case CK_PointerToIntegral: {
  7382. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  7383. LValue LV;
  7384. if (!EvaluatePointer(SubExpr, LV, Info))
  7385. return false;
  7386. if (LV.getLValueBase()) {
  7387. // Only allow based lvalue casts if they are lossless.
  7388. // FIXME: Allow a larger integer size than the pointer size, and allow
  7389. // narrowing back down to pointer width in subsequent integral casts.
  7390. // FIXME: Check integer type's active bits, not its type size.
  7391. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  7392. return Error(E);
  7393. LV.Designator.setInvalid();
  7394. LV.moveInto(Result);
  7395. return true;
  7396. }
  7397. uint64_t V;
  7398. if (LV.isNullPointer())
  7399. V = Info.Ctx.getTargetNullPointerValue(SrcType);
  7400. else
  7401. V = LV.getLValueOffset().getQuantity();
  7402. APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
  7403. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  7404. }
  7405. case CK_IntegralComplexToReal: {
  7406. ComplexValue C;
  7407. if (!EvaluateComplex(SubExpr, C, Info))
  7408. return false;
  7409. return Success(C.getComplexIntReal(), E);
  7410. }
  7411. case CK_FloatingToIntegral: {
  7412. APFloat F(0.0);
  7413. if (!EvaluateFloat(SubExpr, F, Info))
  7414. return false;
  7415. APSInt Value;
  7416. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  7417. return false;
  7418. return Success(Value, E);
  7419. }
  7420. }
  7421. llvm_unreachable("unknown cast resulting in integral value");
  7422. }
  7423. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  7424. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  7425. ComplexValue LV;
  7426. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  7427. return false;
  7428. if (!LV.isComplexInt())
  7429. return Error(E);
  7430. return Success(LV.getComplexIntReal(), E);
  7431. }
  7432. return Visit(E->getSubExpr());
  7433. }
  7434. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7435. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  7436. ComplexValue LV;
  7437. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  7438. return false;
  7439. if (!LV.isComplexInt())
  7440. return Error(E);
  7441. return Success(LV.getComplexIntImag(), E);
  7442. }
  7443. VisitIgnoredValue(E->getSubExpr());
  7444. return Success(0, E);
  7445. }
  7446. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  7447. return Success(E->getPackLength(), E);
  7448. }
  7449. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  7450. return Success(E->getValue(), E);
  7451. }
  7452. //===----------------------------------------------------------------------===//
  7453. // Float Evaluation
  7454. //===----------------------------------------------------------------------===//
  7455. namespace {
  7456. class FloatExprEvaluator
  7457. : public ExprEvaluatorBase<FloatExprEvaluator> {
  7458. APFloat &Result;
  7459. public:
  7460. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  7461. : ExprEvaluatorBaseTy(info), Result(result) {}
  7462. bool Success(const APValue &V, const Expr *e) {
  7463. Result = V.getFloat();
  7464. return true;
  7465. }
  7466. bool ZeroInitialization(const Expr *E) {
  7467. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  7468. return true;
  7469. }
  7470. bool VisitCallExpr(const CallExpr *E);
  7471. bool VisitUnaryOperator(const UnaryOperator *E);
  7472. bool VisitBinaryOperator(const BinaryOperator *E);
  7473. bool VisitFloatingLiteral(const FloatingLiteral *E);
  7474. bool VisitCastExpr(const CastExpr *E);
  7475. bool VisitUnaryReal(const UnaryOperator *E);
  7476. bool VisitUnaryImag(const UnaryOperator *E);
  7477. // FIXME: Missing: array subscript of vector, member of vector
  7478. };
  7479. } // end anonymous namespace
  7480. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  7481. assert(E->isRValue() && E->getType()->isRealFloatingType());
  7482. return FloatExprEvaluator(Info, Result).Visit(E);
  7483. }
  7484. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  7485. QualType ResultTy,
  7486. const Expr *Arg,
  7487. bool SNaN,
  7488. llvm::APFloat &Result) {
  7489. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  7490. if (!S) return false;
  7491. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  7492. llvm::APInt fill;
  7493. // Treat empty strings as if they were zero.
  7494. if (S->getString().empty())
  7495. fill = llvm::APInt(32, 0);
  7496. else if (S->getString().getAsInteger(0, fill))
  7497. return false;
  7498. if (Context.getTargetInfo().isNan2008()) {
  7499. if (SNaN)
  7500. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  7501. else
  7502. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  7503. } else {
  7504. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  7505. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  7506. // a different encoding to what became a standard in 2008, and for pre-
  7507. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  7508. // sNaN. This is now known as "legacy NaN" encoding.
  7509. if (SNaN)
  7510. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  7511. else
  7512. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  7513. }
  7514. return true;
  7515. }
  7516. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7517. switch (E->getBuiltinCallee()) {
  7518. default:
  7519. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7520. case Builtin::BI__builtin_huge_val:
  7521. case Builtin::BI__builtin_huge_valf:
  7522. case Builtin::BI__builtin_huge_vall:
  7523. case Builtin::BI__builtin_inf:
  7524. case Builtin::BI__builtin_inff:
  7525. case Builtin::BI__builtin_infl: {
  7526. const llvm::fltSemantics &Sem =
  7527. Info.Ctx.getFloatTypeSemantics(E->getType());
  7528. Result = llvm::APFloat::getInf(Sem);
  7529. return true;
  7530. }
  7531. case Builtin::BI__builtin_nans:
  7532. case Builtin::BI__builtin_nansf:
  7533. case Builtin::BI__builtin_nansl:
  7534. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  7535. true, Result))
  7536. return Error(E);
  7537. return true;
  7538. case Builtin::BI__builtin_nan:
  7539. case Builtin::BI__builtin_nanf:
  7540. case Builtin::BI__builtin_nanl:
  7541. // If this is __builtin_nan() turn this into a nan, otherwise we
  7542. // can't constant fold it.
  7543. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  7544. false, Result))
  7545. return Error(E);
  7546. return true;
  7547. case Builtin::BI__builtin_fabs:
  7548. case Builtin::BI__builtin_fabsf:
  7549. case Builtin::BI__builtin_fabsl:
  7550. if (!EvaluateFloat(E->getArg(0), Result, Info))
  7551. return false;
  7552. if (Result.isNegative())
  7553. Result.changeSign();
  7554. return true;
  7555. // FIXME: Builtin::BI__builtin_powi
  7556. // FIXME: Builtin::BI__builtin_powif
  7557. // FIXME: Builtin::BI__builtin_powil
  7558. case Builtin::BI__builtin_copysign:
  7559. case Builtin::BI__builtin_copysignf:
  7560. case Builtin::BI__builtin_copysignl: {
  7561. APFloat RHS(0.);
  7562. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  7563. !EvaluateFloat(E->getArg(1), RHS, Info))
  7564. return false;
  7565. Result.copySign(RHS);
  7566. return true;
  7567. }
  7568. }
  7569. }
  7570. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  7571. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  7572. ComplexValue CV;
  7573. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  7574. return false;
  7575. Result = CV.FloatReal;
  7576. return true;
  7577. }
  7578. return Visit(E->getSubExpr());
  7579. }
  7580. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  7581. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  7582. ComplexValue CV;
  7583. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  7584. return false;
  7585. Result = CV.FloatImag;
  7586. return true;
  7587. }
  7588. VisitIgnoredValue(E->getSubExpr());
  7589. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  7590. Result = llvm::APFloat::getZero(Sem);
  7591. return true;
  7592. }
  7593. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  7594. switch (E->getOpcode()) {
  7595. default: return Error(E);
  7596. case UO_Plus:
  7597. return EvaluateFloat(E->getSubExpr(), Result, Info);
  7598. case UO_Minus:
  7599. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  7600. return false;
  7601. Result.changeSign();
  7602. return true;
  7603. }
  7604. }
  7605. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7606. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  7607. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7608. APFloat RHS(0.0);
  7609. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  7610. if (!LHSOK && !Info.noteFailure())
  7611. return false;
  7612. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  7613. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  7614. }
  7615. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  7616. Result = E->getValue();
  7617. return true;
  7618. }
  7619. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7620. const Expr* SubExpr = E->getSubExpr();
  7621. switch (E->getCastKind()) {
  7622. default:
  7623. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7624. case CK_IntegralToFloating: {
  7625. APSInt IntResult;
  7626. return EvaluateInteger(SubExpr, IntResult, Info) &&
  7627. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  7628. E->getType(), Result);
  7629. }
  7630. case CK_FloatingCast: {
  7631. if (!Visit(SubExpr))
  7632. return false;
  7633. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  7634. Result);
  7635. }
  7636. case CK_FloatingComplexToReal: {
  7637. ComplexValue V;
  7638. if (!EvaluateComplex(SubExpr, V, Info))
  7639. return false;
  7640. Result = V.getComplexFloatReal();
  7641. return true;
  7642. }
  7643. }
  7644. }
  7645. //===----------------------------------------------------------------------===//
  7646. // Complex Evaluation (for float and integer)
  7647. //===----------------------------------------------------------------------===//
  7648. namespace {
  7649. class ComplexExprEvaluator
  7650. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  7651. ComplexValue &Result;
  7652. public:
  7653. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  7654. : ExprEvaluatorBaseTy(info), Result(Result) {}
  7655. bool Success(const APValue &V, const Expr *e) {
  7656. Result.setFrom(V);
  7657. return true;
  7658. }
  7659. bool ZeroInitialization(const Expr *E);
  7660. //===--------------------------------------------------------------------===//
  7661. // Visitor Methods
  7662. //===--------------------------------------------------------------------===//
  7663. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  7664. bool VisitCastExpr(const CastExpr *E);
  7665. bool VisitBinaryOperator(const BinaryOperator *E);
  7666. bool VisitUnaryOperator(const UnaryOperator *E);
  7667. bool VisitInitListExpr(const InitListExpr *E);
  7668. };
  7669. } // end anonymous namespace
  7670. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  7671. EvalInfo &Info) {
  7672. assert(E->isRValue() && E->getType()->isAnyComplexType());
  7673. return ComplexExprEvaluator(Info, Result).Visit(E);
  7674. }
  7675. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  7676. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  7677. if (ElemTy->isRealFloatingType()) {
  7678. Result.makeComplexFloat();
  7679. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  7680. Result.FloatReal = Zero;
  7681. Result.FloatImag = Zero;
  7682. } else {
  7683. Result.makeComplexInt();
  7684. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  7685. Result.IntReal = Zero;
  7686. Result.IntImag = Zero;
  7687. }
  7688. return true;
  7689. }
  7690. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  7691. const Expr* SubExpr = E->getSubExpr();
  7692. if (SubExpr->getType()->isRealFloatingType()) {
  7693. Result.makeComplexFloat();
  7694. APFloat &Imag = Result.FloatImag;
  7695. if (!EvaluateFloat(SubExpr, Imag, Info))
  7696. return false;
  7697. Result.FloatReal = APFloat(Imag.getSemantics());
  7698. return true;
  7699. } else {
  7700. assert(SubExpr->getType()->isIntegerType() &&
  7701. "Unexpected imaginary literal.");
  7702. Result.makeComplexInt();
  7703. APSInt &Imag = Result.IntImag;
  7704. if (!EvaluateInteger(SubExpr, Imag, Info))
  7705. return false;
  7706. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  7707. return true;
  7708. }
  7709. }
  7710. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  7711. switch (E->getCastKind()) {
  7712. case CK_BitCast:
  7713. case CK_BaseToDerived:
  7714. case CK_DerivedToBase:
  7715. case CK_UncheckedDerivedToBase:
  7716. case CK_Dynamic:
  7717. case CK_ToUnion:
  7718. case CK_ArrayToPointerDecay:
  7719. case CK_FunctionToPointerDecay:
  7720. case CK_NullToPointer:
  7721. case CK_NullToMemberPointer:
  7722. case CK_BaseToDerivedMemberPointer:
  7723. case CK_DerivedToBaseMemberPointer:
  7724. case CK_MemberPointerToBoolean:
  7725. case CK_ReinterpretMemberPointer:
  7726. case CK_ConstructorConversion:
  7727. case CK_IntegralToPointer:
  7728. case CK_PointerToIntegral:
  7729. case CK_PointerToBoolean:
  7730. case CK_ToVoid:
  7731. case CK_VectorSplat:
  7732. case CK_IntegralCast:
  7733. case CK_BooleanToSignedIntegral:
  7734. case CK_IntegralToBoolean:
  7735. case CK_IntegralToFloating:
  7736. case CK_FloatingToIntegral:
  7737. case CK_FloatingToBoolean:
  7738. case CK_FloatingCast:
  7739. case CK_CPointerToObjCPointerCast:
  7740. case CK_BlockPointerToObjCPointerCast:
  7741. case CK_AnyPointerToBlockPointerCast:
  7742. case CK_ObjCObjectLValueCast:
  7743. case CK_FloatingComplexToReal:
  7744. case CK_FloatingComplexToBoolean:
  7745. case CK_IntegralComplexToReal:
  7746. case CK_IntegralComplexToBoolean:
  7747. case CK_ARCProduceObject:
  7748. case CK_ARCConsumeObject:
  7749. case CK_ARCReclaimReturnedObject:
  7750. case CK_ARCExtendBlockObject:
  7751. case CK_CopyAndAutoreleaseBlockObject:
  7752. case CK_BuiltinFnToFnPtr:
  7753. case CK_ZeroToOCLEvent:
  7754. case CK_NonAtomicToAtomic:
  7755. case CK_AddressSpaceConversion:
  7756. case CK_IntToOCLSampler:
  7757. llvm_unreachable("invalid cast kind for complex value");
  7758. case CK_LValueToRValue:
  7759. case CK_AtomicToNonAtomic:
  7760. case CK_NoOp:
  7761. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  7762. case CK_Dependent:
  7763. case CK_LValueBitCast:
  7764. case CK_UserDefinedConversion:
  7765. return Error(E);
  7766. case CK_FloatingRealToComplex: {
  7767. APFloat &Real = Result.FloatReal;
  7768. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  7769. return false;
  7770. Result.makeComplexFloat();
  7771. Result.FloatImag = APFloat(Real.getSemantics());
  7772. return true;
  7773. }
  7774. case CK_FloatingComplexCast: {
  7775. if (!Visit(E->getSubExpr()))
  7776. return false;
  7777. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7778. QualType From
  7779. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7780. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  7781. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  7782. }
  7783. case CK_FloatingComplexToIntegralComplex: {
  7784. if (!Visit(E->getSubExpr()))
  7785. return false;
  7786. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7787. QualType From
  7788. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7789. Result.makeComplexInt();
  7790. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  7791. To, Result.IntReal) &&
  7792. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  7793. To, Result.IntImag);
  7794. }
  7795. case CK_IntegralRealToComplex: {
  7796. APSInt &Real = Result.IntReal;
  7797. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  7798. return false;
  7799. Result.makeComplexInt();
  7800. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  7801. return true;
  7802. }
  7803. case CK_IntegralComplexCast: {
  7804. if (!Visit(E->getSubExpr()))
  7805. return false;
  7806. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  7807. QualType From
  7808. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  7809. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  7810. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  7811. return true;
  7812. }
  7813. case CK_IntegralComplexToFloatingComplex: {
  7814. if (!Visit(E->getSubExpr()))
  7815. return false;
  7816. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  7817. QualType From
  7818. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  7819. Result.makeComplexFloat();
  7820. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  7821. To, Result.FloatReal) &&
  7822. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  7823. To, Result.FloatImag);
  7824. }
  7825. }
  7826. llvm_unreachable("unknown cast resulting in complex value");
  7827. }
  7828. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  7829. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  7830. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  7831. // Track whether the LHS or RHS is real at the type system level. When this is
  7832. // the case we can simplify our evaluation strategy.
  7833. bool LHSReal = false, RHSReal = false;
  7834. bool LHSOK;
  7835. if (E->getLHS()->getType()->isRealFloatingType()) {
  7836. LHSReal = true;
  7837. APFloat &Real = Result.FloatReal;
  7838. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  7839. if (LHSOK) {
  7840. Result.makeComplexFloat();
  7841. Result.FloatImag = APFloat(Real.getSemantics());
  7842. }
  7843. } else {
  7844. LHSOK = Visit(E->getLHS());
  7845. }
  7846. if (!LHSOK && !Info.noteFailure())
  7847. return false;
  7848. ComplexValue RHS;
  7849. if (E->getRHS()->getType()->isRealFloatingType()) {
  7850. RHSReal = true;
  7851. APFloat &Real = RHS.FloatReal;
  7852. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  7853. return false;
  7854. RHS.makeComplexFloat();
  7855. RHS.FloatImag = APFloat(Real.getSemantics());
  7856. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7857. return false;
  7858. assert(!(LHSReal && RHSReal) &&
  7859. "Cannot have both operands of a complex operation be real.");
  7860. switch (E->getOpcode()) {
  7861. default: return Error(E);
  7862. case BO_Add:
  7863. if (Result.isComplexFloat()) {
  7864. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  7865. APFloat::rmNearestTiesToEven);
  7866. if (LHSReal)
  7867. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  7868. else if (!RHSReal)
  7869. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  7870. APFloat::rmNearestTiesToEven);
  7871. } else {
  7872. Result.getComplexIntReal() += RHS.getComplexIntReal();
  7873. Result.getComplexIntImag() += RHS.getComplexIntImag();
  7874. }
  7875. break;
  7876. case BO_Sub:
  7877. if (Result.isComplexFloat()) {
  7878. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  7879. APFloat::rmNearestTiesToEven);
  7880. if (LHSReal) {
  7881. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  7882. Result.getComplexFloatImag().changeSign();
  7883. } else if (!RHSReal) {
  7884. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  7885. APFloat::rmNearestTiesToEven);
  7886. }
  7887. } else {
  7888. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  7889. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  7890. }
  7891. break;
  7892. case BO_Mul:
  7893. if (Result.isComplexFloat()) {
  7894. // This is an implementation of complex multiplication according to the
  7895. // constraints laid out in C11 Annex G. The implemantion uses the
  7896. // following naming scheme:
  7897. // (a + ib) * (c + id)
  7898. ComplexValue LHS = Result;
  7899. APFloat &A = LHS.getComplexFloatReal();
  7900. APFloat &B = LHS.getComplexFloatImag();
  7901. APFloat &C = RHS.getComplexFloatReal();
  7902. APFloat &D = RHS.getComplexFloatImag();
  7903. APFloat &ResR = Result.getComplexFloatReal();
  7904. APFloat &ResI = Result.getComplexFloatImag();
  7905. if (LHSReal) {
  7906. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  7907. ResR = A * C;
  7908. ResI = A * D;
  7909. } else if (RHSReal) {
  7910. ResR = C * A;
  7911. ResI = C * B;
  7912. } else {
  7913. // In the fully general case, we need to handle NaNs and infinities
  7914. // robustly.
  7915. APFloat AC = A * C;
  7916. APFloat BD = B * D;
  7917. APFloat AD = A * D;
  7918. APFloat BC = B * C;
  7919. ResR = AC - BD;
  7920. ResI = AD + BC;
  7921. if (ResR.isNaN() && ResI.isNaN()) {
  7922. bool Recalc = false;
  7923. if (A.isInfinity() || B.isInfinity()) {
  7924. A = APFloat::copySign(
  7925. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  7926. B = APFloat::copySign(
  7927. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  7928. if (C.isNaN())
  7929. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  7930. if (D.isNaN())
  7931. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  7932. Recalc = true;
  7933. }
  7934. if (C.isInfinity() || D.isInfinity()) {
  7935. C = APFloat::copySign(
  7936. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  7937. D = APFloat::copySign(
  7938. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  7939. if (A.isNaN())
  7940. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  7941. if (B.isNaN())
  7942. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  7943. Recalc = true;
  7944. }
  7945. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  7946. AD.isInfinity() || BC.isInfinity())) {
  7947. if (A.isNaN())
  7948. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  7949. if (B.isNaN())
  7950. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  7951. if (C.isNaN())
  7952. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  7953. if (D.isNaN())
  7954. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  7955. Recalc = true;
  7956. }
  7957. if (Recalc) {
  7958. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  7959. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  7960. }
  7961. }
  7962. }
  7963. } else {
  7964. ComplexValue LHS = Result;
  7965. Result.getComplexIntReal() =
  7966. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  7967. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  7968. Result.getComplexIntImag() =
  7969. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  7970. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  7971. }
  7972. break;
  7973. case BO_Div:
  7974. if (Result.isComplexFloat()) {
  7975. // This is an implementation of complex division according to the
  7976. // constraints laid out in C11 Annex G. The implemantion uses the
  7977. // following naming scheme:
  7978. // (a + ib) / (c + id)
  7979. ComplexValue LHS = Result;
  7980. APFloat &A = LHS.getComplexFloatReal();
  7981. APFloat &B = LHS.getComplexFloatImag();
  7982. APFloat &C = RHS.getComplexFloatReal();
  7983. APFloat &D = RHS.getComplexFloatImag();
  7984. APFloat &ResR = Result.getComplexFloatReal();
  7985. APFloat &ResI = Result.getComplexFloatImag();
  7986. if (RHSReal) {
  7987. ResR = A / C;
  7988. ResI = B / C;
  7989. } else {
  7990. if (LHSReal) {
  7991. // No real optimizations we can do here, stub out with zero.
  7992. B = APFloat::getZero(A.getSemantics());
  7993. }
  7994. int DenomLogB = 0;
  7995. APFloat MaxCD = maxnum(abs(C), abs(D));
  7996. if (MaxCD.isFinite()) {
  7997. DenomLogB = ilogb(MaxCD);
  7998. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  7999. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  8000. }
  8001. APFloat Denom = C * C + D * D;
  8002. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  8003. APFloat::rmNearestTiesToEven);
  8004. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  8005. APFloat::rmNearestTiesToEven);
  8006. if (ResR.isNaN() && ResI.isNaN()) {
  8007. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  8008. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  8009. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  8010. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  8011. D.isFinite()) {
  8012. A = APFloat::copySign(
  8013. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  8014. B = APFloat::copySign(
  8015. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  8016. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  8017. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  8018. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  8019. C = APFloat::copySign(
  8020. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  8021. D = APFloat::copySign(
  8022. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  8023. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  8024. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  8025. }
  8026. }
  8027. }
  8028. } else {
  8029. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  8030. return Error(E, diag::note_expr_divide_by_zero);
  8031. ComplexValue LHS = Result;
  8032. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  8033. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  8034. Result.getComplexIntReal() =
  8035. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  8036. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  8037. Result.getComplexIntImag() =
  8038. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  8039. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  8040. }
  8041. break;
  8042. }
  8043. return true;
  8044. }
  8045. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8046. // Get the operand value into 'Result'.
  8047. if (!Visit(E->getSubExpr()))
  8048. return false;
  8049. switch (E->getOpcode()) {
  8050. default:
  8051. return Error(E);
  8052. case UO_Extension:
  8053. return true;
  8054. case UO_Plus:
  8055. // The result is always just the subexpr.
  8056. return true;
  8057. case UO_Minus:
  8058. if (Result.isComplexFloat()) {
  8059. Result.getComplexFloatReal().changeSign();
  8060. Result.getComplexFloatImag().changeSign();
  8061. }
  8062. else {
  8063. Result.getComplexIntReal() = -Result.getComplexIntReal();
  8064. Result.getComplexIntImag() = -Result.getComplexIntImag();
  8065. }
  8066. return true;
  8067. case UO_Not:
  8068. if (Result.isComplexFloat())
  8069. Result.getComplexFloatImag().changeSign();
  8070. else
  8071. Result.getComplexIntImag() = -Result.getComplexIntImag();
  8072. return true;
  8073. }
  8074. }
  8075. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  8076. if (E->getNumInits() == 2) {
  8077. if (E->getType()->isComplexType()) {
  8078. Result.makeComplexFloat();
  8079. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  8080. return false;
  8081. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  8082. return false;
  8083. } else {
  8084. Result.makeComplexInt();
  8085. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  8086. return false;
  8087. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  8088. return false;
  8089. }
  8090. return true;
  8091. }
  8092. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  8093. }
  8094. //===----------------------------------------------------------------------===//
  8095. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  8096. // implicit conversion.
  8097. //===----------------------------------------------------------------------===//
  8098. namespace {
  8099. class AtomicExprEvaluator :
  8100. public ExprEvaluatorBase<AtomicExprEvaluator> {
  8101. APValue &Result;
  8102. public:
  8103. AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
  8104. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  8105. bool Success(const APValue &V, const Expr *E) {
  8106. Result = V;
  8107. return true;
  8108. }
  8109. bool ZeroInitialization(const Expr *E) {
  8110. ImplicitValueInitExpr VIE(
  8111. E->getType()->castAs<AtomicType>()->getValueType());
  8112. return Evaluate(Result, Info, &VIE);
  8113. }
  8114. bool VisitCastExpr(const CastExpr *E) {
  8115. switch (E->getCastKind()) {
  8116. default:
  8117. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8118. case CK_NonAtomicToAtomic:
  8119. return Evaluate(Result, Info, E->getSubExpr());
  8120. }
  8121. }
  8122. };
  8123. } // end anonymous namespace
  8124. static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
  8125. assert(E->isRValue() && E->getType()->isAtomicType());
  8126. return AtomicExprEvaluator(Info, Result).Visit(E);
  8127. }
  8128. //===----------------------------------------------------------------------===//
  8129. // Void expression evaluation, primarily for a cast to void on the LHS of a
  8130. // comma operator
  8131. //===----------------------------------------------------------------------===//
  8132. namespace {
  8133. class VoidExprEvaluator
  8134. : public ExprEvaluatorBase<VoidExprEvaluator> {
  8135. public:
  8136. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  8137. bool Success(const APValue &V, const Expr *e) { return true; }
  8138. bool VisitCastExpr(const CastExpr *E) {
  8139. switch (E->getCastKind()) {
  8140. default:
  8141. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8142. case CK_ToVoid:
  8143. VisitIgnoredValue(E->getSubExpr());
  8144. return true;
  8145. }
  8146. }
  8147. bool VisitCallExpr(const CallExpr *E) {
  8148. switch (E->getBuiltinCallee()) {
  8149. default:
  8150. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8151. case Builtin::BI__assume:
  8152. case Builtin::BI__builtin_assume:
  8153. // The argument is not evaluated!
  8154. return true;
  8155. }
  8156. }
  8157. };
  8158. } // end anonymous namespace
  8159. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  8160. assert(E->isRValue() && E->getType()->isVoidType());
  8161. return VoidExprEvaluator(Info).Visit(E);
  8162. }
  8163. //===----------------------------------------------------------------------===//
  8164. // Top level Expr::EvaluateAsRValue method.
  8165. //===----------------------------------------------------------------------===//
  8166. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  8167. // In C, function designators are not lvalues, but we evaluate them as if they
  8168. // are.
  8169. QualType T = E->getType();
  8170. if (E->isGLValue() || T->isFunctionType()) {
  8171. LValue LV;
  8172. if (!EvaluateLValue(E, LV, Info))
  8173. return false;
  8174. LV.moveInto(Result);
  8175. } else if (T->isVectorType()) {
  8176. if (!EvaluateVector(E, Result, Info))
  8177. return false;
  8178. } else if (T->isIntegralOrEnumerationType()) {
  8179. if (!IntExprEvaluator(Info, Result).Visit(E))
  8180. return false;
  8181. } else if (T->hasPointerRepresentation()) {
  8182. LValue LV;
  8183. if (!EvaluatePointer(E, LV, Info))
  8184. return false;
  8185. LV.moveInto(Result);
  8186. } else if (T->isRealFloatingType()) {
  8187. llvm::APFloat F(0.0);
  8188. if (!EvaluateFloat(E, F, Info))
  8189. return false;
  8190. Result = APValue(F);
  8191. } else if (T->isAnyComplexType()) {
  8192. ComplexValue C;
  8193. if (!EvaluateComplex(E, C, Info))
  8194. return false;
  8195. C.moveInto(Result);
  8196. } else if (T->isMemberPointerType()) {
  8197. MemberPtr P;
  8198. if (!EvaluateMemberPointer(E, P, Info))
  8199. return false;
  8200. P.moveInto(Result);
  8201. return true;
  8202. } else if (T->isArrayType()) {
  8203. LValue LV;
  8204. LV.set(E, Info.CurrentCall->Index);
  8205. APValue &Value = Info.CurrentCall->createTemporary(E, false);
  8206. if (!EvaluateArray(E, LV, Value, Info))
  8207. return false;
  8208. Result = Value;
  8209. } else if (T->isRecordType()) {
  8210. LValue LV;
  8211. LV.set(E, Info.CurrentCall->Index);
  8212. APValue &Value = Info.CurrentCall->createTemporary(E, false);
  8213. if (!EvaluateRecord(E, LV, Value, Info))
  8214. return false;
  8215. Result = Value;
  8216. } else if (T->isVoidType()) {
  8217. if (!Info.getLangOpts().CPlusPlus11)
  8218. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  8219. << E->getType();
  8220. if (!EvaluateVoid(E, Info))
  8221. return false;
  8222. } else if (T->isAtomicType()) {
  8223. if (!EvaluateAtomic(E, Result, Info))
  8224. return false;
  8225. } else if (Info.getLangOpts().CPlusPlus11) {
  8226. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  8227. return false;
  8228. } else {
  8229. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8230. return false;
  8231. }
  8232. return true;
  8233. }
  8234. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  8235. /// cases, the in-place evaluation is essential, since later initializers for
  8236. /// an object can indirectly refer to subobjects which were initialized earlier.
  8237. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  8238. const Expr *E, bool AllowNonLiteralTypes) {
  8239. assert(!E->isValueDependent());
  8240. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  8241. return false;
  8242. if (E->isRValue()) {
  8243. // Evaluate arrays and record types in-place, so that later initializers can
  8244. // refer to earlier-initialized members of the object.
  8245. if (E->getType()->isArrayType())
  8246. return EvaluateArray(E, This, Result, Info);
  8247. else if (E->getType()->isRecordType())
  8248. return EvaluateRecord(E, This, Result, Info);
  8249. }
  8250. // For any other type, in-place evaluation is unimportant.
  8251. return Evaluate(Result, Info, E);
  8252. }
  8253. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  8254. /// lvalue-to-rvalue cast if it is an lvalue.
  8255. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  8256. if (E->getType().isNull())
  8257. return false;
  8258. if (!CheckLiteralType(Info, E))
  8259. return false;
  8260. if (!::Evaluate(Result, Info, E))
  8261. return false;
  8262. if (E->isGLValue()) {
  8263. LValue LV;
  8264. LV.setFrom(Info.Ctx, Result);
  8265. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8266. return false;
  8267. }
  8268. // Check this core constant expression is a constant expression.
  8269. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8270. }
  8271. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  8272. const ASTContext &Ctx, bool &IsConst) {
  8273. // Fast-path evaluations of integer literals, since we sometimes see files
  8274. // containing vast quantities of these.
  8275. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  8276. Result.Val = APValue(APSInt(L->getValue(),
  8277. L->getType()->isUnsignedIntegerType()));
  8278. IsConst = true;
  8279. return true;
  8280. }
  8281. // This case should be rare, but we need to check it before we check on
  8282. // the type below.
  8283. if (Exp->getType().isNull()) {
  8284. IsConst = false;
  8285. return true;
  8286. }
  8287. // FIXME: Evaluating values of large array and record types can cause
  8288. // performance problems. Only do so in C++11 for now.
  8289. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  8290. Exp->getType()->isRecordType()) &&
  8291. !Ctx.getLangOpts().CPlusPlus11) {
  8292. IsConst = false;
  8293. return true;
  8294. }
  8295. return false;
  8296. }
  8297. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  8298. /// any crazy technique (that has nothing to do with language standards) that
  8299. /// we want to. If this function returns true, it returns the folded constant
  8300. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  8301. /// will be applied to the result.
  8302. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  8303. bool IsConst;
  8304. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  8305. return IsConst;
  8306. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  8307. return ::EvaluateAsRValue(Info, this, Result.Val);
  8308. }
  8309. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  8310. const ASTContext &Ctx) const {
  8311. EvalResult Scratch;
  8312. return EvaluateAsRValue(Scratch, Ctx) &&
  8313. HandleConversionToBool(Scratch.Val, Result);
  8314. }
  8315. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  8316. Expr::SideEffectsKind SEK) {
  8317. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  8318. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  8319. }
  8320. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  8321. SideEffectsKind AllowSideEffects) const {
  8322. if (!getType()->isIntegralOrEnumerationType())
  8323. return false;
  8324. EvalResult ExprResult;
  8325. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  8326. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  8327. return false;
  8328. Result = ExprResult.Val.getInt();
  8329. return true;
  8330. }
  8331. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  8332. SideEffectsKind AllowSideEffects) const {
  8333. if (!getType()->isRealFloatingType())
  8334. return false;
  8335. EvalResult ExprResult;
  8336. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  8337. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  8338. return false;
  8339. Result = ExprResult.Val.getFloat();
  8340. return true;
  8341. }
  8342. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  8343. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  8344. LValue LV;
  8345. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  8346. !CheckLValueConstantExpression(Info, getExprLoc(),
  8347. Ctx.getLValueReferenceType(getType()), LV))
  8348. return false;
  8349. LV.moveInto(Result.Val);
  8350. return true;
  8351. }
  8352. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  8353. const VarDecl *VD,
  8354. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  8355. // FIXME: Evaluating initializers for large array and record types can cause
  8356. // performance problems. Only do so in C++11 for now.
  8357. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  8358. !Ctx.getLangOpts().CPlusPlus11)
  8359. return false;
  8360. Expr::EvalStatus EStatus;
  8361. EStatus.Diag = &Notes;
  8362. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  8363. ? EvalInfo::EM_ConstantExpression
  8364. : EvalInfo::EM_ConstantFold);
  8365. InitInfo.setEvaluatingDecl(VD, Value);
  8366. LValue LVal;
  8367. LVal.set(VD);
  8368. // C++11 [basic.start.init]p2:
  8369. // Variables with static storage duration or thread storage duration shall be
  8370. // zero-initialized before any other initialization takes place.
  8371. // This behavior is not present in C.
  8372. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  8373. !VD->getType()->isReferenceType()) {
  8374. ImplicitValueInitExpr VIE(VD->getType());
  8375. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  8376. /*AllowNonLiteralTypes=*/true))
  8377. return false;
  8378. }
  8379. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  8380. /*AllowNonLiteralTypes=*/true) ||
  8381. EStatus.HasSideEffects)
  8382. return false;
  8383. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  8384. Value);
  8385. }
  8386. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  8387. /// constant folded, but discard the result.
  8388. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  8389. EvalResult Result;
  8390. return EvaluateAsRValue(Result, Ctx) &&
  8391. !hasUnacceptableSideEffect(Result, SEK);
  8392. }
  8393. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  8394. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  8395. EvalResult EvalResult;
  8396. EvalResult.Diag = Diag;
  8397. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  8398. (void)Result;
  8399. assert(Result && "Could not evaluate expression");
  8400. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  8401. return EvalResult.Val.getInt();
  8402. }
  8403. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  8404. bool IsConst;
  8405. EvalResult EvalResult;
  8406. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  8407. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  8408. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  8409. }
  8410. }
  8411. bool Expr::EvalResult::isGlobalLValue() const {
  8412. assert(Val.isLValue());
  8413. return IsGlobalLValue(Val.getLValueBase());
  8414. }
  8415. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  8416. /// an integer constant expression.
  8417. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  8418. /// comma, etc
  8419. // CheckICE - This function does the fundamental ICE checking: the returned
  8420. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  8421. // and a (possibly null) SourceLocation indicating the location of the problem.
  8422. //
  8423. // Note that to reduce code duplication, this helper does no evaluation
  8424. // itself; the caller checks whether the expression is evaluatable, and
  8425. // in the rare cases where CheckICE actually cares about the evaluated
  8426. // value, it calls into Evalute.
  8427. namespace {
  8428. enum ICEKind {
  8429. /// This expression is an ICE.
  8430. IK_ICE,
  8431. /// This expression is not an ICE, but if it isn't evaluated, it's
  8432. /// a legal subexpression for an ICE. This return value is used to handle
  8433. /// the comma operator in C99 mode, and non-constant subexpressions.
  8434. IK_ICEIfUnevaluated,
  8435. /// This expression is not an ICE, and is not a legal subexpression for one.
  8436. IK_NotICE
  8437. };
  8438. struct ICEDiag {
  8439. ICEKind Kind;
  8440. SourceLocation Loc;
  8441. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  8442. };
  8443. }
  8444. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  8445. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  8446. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  8447. Expr::EvalResult EVResult;
  8448. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  8449. !EVResult.Val.isInt())
  8450. return ICEDiag(IK_NotICE, E->getLocStart());
  8451. return NoDiag();
  8452. }
  8453. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  8454. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  8455. if (!E->getType()->isIntegralOrEnumerationType())
  8456. return ICEDiag(IK_NotICE, E->getLocStart());
  8457. switch (E->getStmtClass()) {
  8458. #define ABSTRACT_STMT(Node)
  8459. #define STMT(Node, Base) case Expr::Node##Class:
  8460. #define EXPR(Node, Base)
  8461. #include "clang/AST/StmtNodes.inc"
  8462. case Expr::PredefinedExprClass:
  8463. case Expr::FloatingLiteralClass:
  8464. case Expr::ImaginaryLiteralClass:
  8465. case Expr::StringLiteralClass:
  8466. case Expr::ArraySubscriptExprClass:
  8467. case Expr::OMPArraySectionExprClass:
  8468. case Expr::MemberExprClass:
  8469. case Expr::CompoundAssignOperatorClass:
  8470. case Expr::CompoundLiteralExprClass:
  8471. case Expr::ExtVectorElementExprClass:
  8472. case Expr::DesignatedInitExprClass:
  8473. case Expr::ArrayInitLoopExprClass:
  8474. case Expr::ArrayInitIndexExprClass:
  8475. case Expr::NoInitExprClass:
  8476. case Expr::DesignatedInitUpdateExprClass:
  8477. case Expr::ImplicitValueInitExprClass:
  8478. case Expr::ParenListExprClass:
  8479. case Expr::VAArgExprClass:
  8480. case Expr::AddrLabelExprClass:
  8481. case Expr::StmtExprClass:
  8482. case Expr::CXXMemberCallExprClass:
  8483. case Expr::CUDAKernelCallExprClass:
  8484. case Expr::CXXDynamicCastExprClass:
  8485. case Expr::CXXTypeidExprClass:
  8486. case Expr::CXXUuidofExprClass:
  8487. case Expr::MSPropertyRefExprClass:
  8488. case Expr::MSPropertySubscriptExprClass:
  8489. case Expr::CXXNullPtrLiteralExprClass:
  8490. case Expr::UserDefinedLiteralClass:
  8491. case Expr::CXXThisExprClass:
  8492. case Expr::CXXThrowExprClass:
  8493. case Expr::CXXNewExprClass:
  8494. case Expr::CXXDeleteExprClass:
  8495. case Expr::CXXPseudoDestructorExprClass:
  8496. case Expr::UnresolvedLookupExprClass:
  8497. case Expr::TypoExprClass:
  8498. case Expr::DependentScopeDeclRefExprClass:
  8499. case Expr::CXXConstructExprClass:
  8500. case Expr::CXXInheritedCtorInitExprClass:
  8501. case Expr::CXXStdInitializerListExprClass:
  8502. case Expr::CXXBindTemporaryExprClass:
  8503. case Expr::ExprWithCleanupsClass:
  8504. case Expr::CXXTemporaryObjectExprClass:
  8505. case Expr::CXXUnresolvedConstructExprClass:
  8506. case Expr::CXXDependentScopeMemberExprClass:
  8507. case Expr::UnresolvedMemberExprClass:
  8508. case Expr::ObjCStringLiteralClass:
  8509. case Expr::ObjCBoxedExprClass:
  8510. case Expr::ObjCArrayLiteralClass:
  8511. case Expr::ObjCDictionaryLiteralClass:
  8512. case Expr::ObjCEncodeExprClass:
  8513. case Expr::ObjCMessageExprClass:
  8514. case Expr::ObjCSelectorExprClass:
  8515. case Expr::ObjCProtocolExprClass:
  8516. case Expr::ObjCIvarRefExprClass:
  8517. case Expr::ObjCPropertyRefExprClass:
  8518. case Expr::ObjCSubscriptRefExprClass:
  8519. case Expr::ObjCIsaExprClass:
  8520. case Expr::ObjCAvailabilityCheckExprClass:
  8521. case Expr::ShuffleVectorExprClass:
  8522. case Expr::ConvertVectorExprClass:
  8523. case Expr::BlockExprClass:
  8524. case Expr::NoStmtClass:
  8525. case Expr::OpaqueValueExprClass:
  8526. case Expr::PackExpansionExprClass:
  8527. case Expr::SubstNonTypeTemplateParmPackExprClass:
  8528. case Expr::FunctionParmPackExprClass:
  8529. case Expr::AsTypeExprClass:
  8530. case Expr::ObjCIndirectCopyRestoreExprClass:
  8531. case Expr::MaterializeTemporaryExprClass:
  8532. case Expr::PseudoObjectExprClass:
  8533. case Expr::AtomicExprClass:
  8534. case Expr::LambdaExprClass:
  8535. case Expr::CXXFoldExprClass:
  8536. case Expr::CoawaitExprClass:
  8537. case Expr::CoyieldExprClass:
  8538. return ICEDiag(IK_NotICE, E->getLocStart());
  8539. case Expr::InitListExprClass: {
  8540. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  8541. // form "T x = { a };" is equivalent to "T x = a;".
  8542. // Unless we're initializing a reference, T is a scalar as it is known to be
  8543. // of integral or enumeration type.
  8544. if (E->isRValue())
  8545. if (cast<InitListExpr>(E)->getNumInits() == 1)
  8546. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  8547. return ICEDiag(IK_NotICE, E->getLocStart());
  8548. }
  8549. case Expr::SizeOfPackExprClass:
  8550. case Expr::GNUNullExprClass:
  8551. // GCC considers the GNU __null value to be an integral constant expression.
  8552. return NoDiag();
  8553. case Expr::SubstNonTypeTemplateParmExprClass:
  8554. return
  8555. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  8556. case Expr::ParenExprClass:
  8557. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  8558. case Expr::GenericSelectionExprClass:
  8559. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  8560. case Expr::IntegerLiteralClass:
  8561. case Expr::CharacterLiteralClass:
  8562. case Expr::ObjCBoolLiteralExprClass:
  8563. case Expr::CXXBoolLiteralExprClass:
  8564. case Expr::CXXScalarValueInitExprClass:
  8565. case Expr::TypeTraitExprClass:
  8566. case Expr::ArrayTypeTraitExprClass:
  8567. case Expr::ExpressionTraitExprClass:
  8568. case Expr::CXXNoexceptExprClass:
  8569. return NoDiag();
  8570. case Expr::CallExprClass:
  8571. case Expr::CXXOperatorCallExprClass: {
  8572. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  8573. // constant expressions, but they can never be ICEs because an ICE cannot
  8574. // contain an operand of (pointer to) function type.
  8575. const CallExpr *CE = cast<CallExpr>(E);
  8576. if (CE->getBuiltinCallee())
  8577. return CheckEvalInICE(E, Ctx);
  8578. return ICEDiag(IK_NotICE, E->getLocStart());
  8579. }
  8580. case Expr::DeclRefExprClass: {
  8581. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  8582. return NoDiag();
  8583. const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
  8584. if (Ctx.getLangOpts().CPlusPlus &&
  8585. D && IsConstNonVolatile(D->getType())) {
  8586. // Parameter variables are never constants. Without this check,
  8587. // getAnyInitializer() can find a default argument, which leads
  8588. // to chaos.
  8589. if (isa<ParmVarDecl>(D))
  8590. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  8591. // C++ 7.1.5.1p2
  8592. // A variable of non-volatile const-qualified integral or enumeration
  8593. // type initialized by an ICE can be used in ICEs.
  8594. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  8595. if (!Dcl->getType()->isIntegralOrEnumerationType())
  8596. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  8597. const VarDecl *VD;
  8598. // Look for a declaration of this variable that has an initializer, and
  8599. // check whether it is an ICE.
  8600. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  8601. return NoDiag();
  8602. else
  8603. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  8604. }
  8605. }
  8606. return ICEDiag(IK_NotICE, E->getLocStart());
  8607. }
  8608. case Expr::UnaryOperatorClass: {
  8609. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  8610. switch (Exp->getOpcode()) {
  8611. case UO_PostInc:
  8612. case UO_PostDec:
  8613. case UO_PreInc:
  8614. case UO_PreDec:
  8615. case UO_AddrOf:
  8616. case UO_Deref:
  8617. case UO_Coawait:
  8618. // C99 6.6/3 allows increment and decrement within unevaluated
  8619. // subexpressions of constant expressions, but they can never be ICEs
  8620. // because an ICE cannot contain an lvalue operand.
  8621. return ICEDiag(IK_NotICE, E->getLocStart());
  8622. case UO_Extension:
  8623. case UO_LNot:
  8624. case UO_Plus:
  8625. case UO_Minus:
  8626. case UO_Not:
  8627. case UO_Real:
  8628. case UO_Imag:
  8629. return CheckICE(Exp->getSubExpr(), Ctx);
  8630. }
  8631. // OffsetOf falls through here.
  8632. }
  8633. case Expr::OffsetOfExprClass: {
  8634. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  8635. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  8636. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  8637. // compliance: we should warn earlier for offsetof expressions with
  8638. // array subscripts that aren't ICEs, and if the array subscripts
  8639. // are ICEs, the value of the offsetof must be an integer constant.
  8640. return CheckEvalInICE(E, Ctx);
  8641. }
  8642. case Expr::UnaryExprOrTypeTraitExprClass: {
  8643. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  8644. if ((Exp->getKind() == UETT_SizeOf) &&
  8645. Exp->getTypeOfArgument()->isVariableArrayType())
  8646. return ICEDiag(IK_NotICE, E->getLocStart());
  8647. return NoDiag();
  8648. }
  8649. case Expr::BinaryOperatorClass: {
  8650. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  8651. switch (Exp->getOpcode()) {
  8652. case BO_PtrMemD:
  8653. case BO_PtrMemI:
  8654. case BO_Assign:
  8655. case BO_MulAssign:
  8656. case BO_DivAssign:
  8657. case BO_RemAssign:
  8658. case BO_AddAssign:
  8659. case BO_SubAssign:
  8660. case BO_ShlAssign:
  8661. case BO_ShrAssign:
  8662. case BO_AndAssign:
  8663. case BO_XorAssign:
  8664. case BO_OrAssign:
  8665. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  8666. // constant expressions, but they can never be ICEs because an ICE cannot
  8667. // contain an lvalue operand.
  8668. return ICEDiag(IK_NotICE, E->getLocStart());
  8669. case BO_Mul:
  8670. case BO_Div:
  8671. case BO_Rem:
  8672. case BO_Add:
  8673. case BO_Sub:
  8674. case BO_Shl:
  8675. case BO_Shr:
  8676. case BO_LT:
  8677. case BO_GT:
  8678. case BO_LE:
  8679. case BO_GE:
  8680. case BO_EQ:
  8681. case BO_NE:
  8682. case BO_And:
  8683. case BO_Xor:
  8684. case BO_Or:
  8685. case BO_Comma: {
  8686. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  8687. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  8688. if (Exp->getOpcode() == BO_Div ||
  8689. Exp->getOpcode() == BO_Rem) {
  8690. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  8691. // we don't evaluate one.
  8692. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  8693. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  8694. if (REval == 0)
  8695. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8696. if (REval.isSigned() && REval.isAllOnesValue()) {
  8697. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  8698. if (LEval.isMinSignedValue())
  8699. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8700. }
  8701. }
  8702. }
  8703. if (Exp->getOpcode() == BO_Comma) {
  8704. if (Ctx.getLangOpts().C99) {
  8705. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  8706. // if it isn't evaluated.
  8707. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  8708. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  8709. } else {
  8710. // In both C89 and C++, commas in ICEs are illegal.
  8711. return ICEDiag(IK_NotICE, E->getLocStart());
  8712. }
  8713. }
  8714. return Worst(LHSResult, RHSResult);
  8715. }
  8716. case BO_LAnd:
  8717. case BO_LOr: {
  8718. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  8719. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  8720. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  8721. // Rare case where the RHS has a comma "side-effect"; we need
  8722. // to actually check the condition to see whether the side
  8723. // with the comma is evaluated.
  8724. if ((Exp->getOpcode() == BO_LAnd) !=
  8725. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  8726. return RHSResult;
  8727. return NoDiag();
  8728. }
  8729. return Worst(LHSResult, RHSResult);
  8730. }
  8731. }
  8732. }
  8733. case Expr::ImplicitCastExprClass:
  8734. case Expr::CStyleCastExprClass:
  8735. case Expr::CXXFunctionalCastExprClass:
  8736. case Expr::CXXStaticCastExprClass:
  8737. case Expr::CXXReinterpretCastExprClass:
  8738. case Expr::CXXConstCastExprClass:
  8739. case Expr::ObjCBridgedCastExprClass: {
  8740. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  8741. if (isa<ExplicitCastExpr>(E)) {
  8742. if (const FloatingLiteral *FL
  8743. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  8744. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  8745. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  8746. APSInt IgnoredVal(DestWidth, !DestSigned);
  8747. bool Ignored;
  8748. // If the value does not fit in the destination type, the behavior is
  8749. // undefined, so we are not required to treat it as a constant
  8750. // expression.
  8751. if (FL->getValue().convertToInteger(IgnoredVal,
  8752. llvm::APFloat::rmTowardZero,
  8753. &Ignored) & APFloat::opInvalidOp)
  8754. return ICEDiag(IK_NotICE, E->getLocStart());
  8755. return NoDiag();
  8756. }
  8757. }
  8758. switch (cast<CastExpr>(E)->getCastKind()) {
  8759. case CK_LValueToRValue:
  8760. case CK_AtomicToNonAtomic:
  8761. case CK_NonAtomicToAtomic:
  8762. case CK_NoOp:
  8763. case CK_IntegralToBoolean:
  8764. case CK_IntegralCast:
  8765. return CheckICE(SubExpr, Ctx);
  8766. default:
  8767. return ICEDiag(IK_NotICE, E->getLocStart());
  8768. }
  8769. }
  8770. case Expr::BinaryConditionalOperatorClass: {
  8771. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  8772. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  8773. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  8774. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  8775. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  8776. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  8777. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  8778. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  8779. return FalseResult;
  8780. }
  8781. case Expr::ConditionalOperatorClass: {
  8782. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  8783. // If the condition (ignoring parens) is a __builtin_constant_p call,
  8784. // then only the true side is actually considered in an integer constant
  8785. // expression, and it is fully evaluated. This is an important GNU
  8786. // extension. See GCC PR38377 for discussion.
  8787. if (const CallExpr *CallCE
  8788. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  8789. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  8790. return CheckEvalInICE(E, Ctx);
  8791. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  8792. if (CondResult.Kind == IK_NotICE)
  8793. return CondResult;
  8794. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  8795. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  8796. if (TrueResult.Kind == IK_NotICE)
  8797. return TrueResult;
  8798. if (FalseResult.Kind == IK_NotICE)
  8799. return FalseResult;
  8800. if (CondResult.Kind == IK_ICEIfUnevaluated)
  8801. return CondResult;
  8802. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  8803. return NoDiag();
  8804. // Rare case where the diagnostics depend on which side is evaluated
  8805. // Note that if we get here, CondResult is 0, and at least one of
  8806. // TrueResult and FalseResult is non-zero.
  8807. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  8808. return FalseResult;
  8809. return TrueResult;
  8810. }
  8811. case Expr::CXXDefaultArgExprClass:
  8812. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  8813. case Expr::CXXDefaultInitExprClass:
  8814. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  8815. case Expr::ChooseExprClass: {
  8816. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  8817. }
  8818. }
  8819. llvm_unreachable("Invalid StmtClass!");
  8820. }
  8821. /// Evaluate an expression as a C++11 integral constant expression.
  8822. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  8823. const Expr *E,
  8824. llvm::APSInt *Value,
  8825. SourceLocation *Loc) {
  8826. if (!E->getType()->isIntegralOrEnumerationType()) {
  8827. if (Loc) *Loc = E->getExprLoc();
  8828. return false;
  8829. }
  8830. APValue Result;
  8831. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  8832. return false;
  8833. if (!Result.isInt()) {
  8834. if (Loc) *Loc = E->getExprLoc();
  8835. return false;
  8836. }
  8837. if (Value) *Value = Result.getInt();
  8838. return true;
  8839. }
  8840. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  8841. SourceLocation *Loc) const {
  8842. if (Ctx.getLangOpts().CPlusPlus11)
  8843. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  8844. ICEDiag D = CheckICE(this, Ctx);
  8845. if (D.Kind != IK_ICE) {
  8846. if (Loc) *Loc = D.Loc;
  8847. return false;
  8848. }
  8849. return true;
  8850. }
  8851. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  8852. SourceLocation *Loc, bool isEvaluated) const {
  8853. if (Ctx.getLangOpts().CPlusPlus11)
  8854. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  8855. if (!isIntegerConstantExpr(Ctx, Loc))
  8856. return false;
  8857. // The only possible side-effects here are due to UB discovered in the
  8858. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  8859. // required to treat the expression as an ICE, so we produce the folded
  8860. // value.
  8861. if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
  8862. llvm_unreachable("ICE cannot be evaluated!");
  8863. return true;
  8864. }
  8865. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  8866. return CheckICE(this, Ctx).Kind == IK_ICE;
  8867. }
  8868. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  8869. SourceLocation *Loc) const {
  8870. // We support this checking in C++98 mode in order to diagnose compatibility
  8871. // issues.
  8872. assert(Ctx.getLangOpts().CPlusPlus);
  8873. // Build evaluation settings.
  8874. Expr::EvalStatus Status;
  8875. SmallVector<PartialDiagnosticAt, 8> Diags;
  8876. Status.Diag = &Diags;
  8877. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  8878. APValue Scratch;
  8879. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  8880. if (!Diags.empty()) {
  8881. IsConstExpr = false;
  8882. if (Loc) *Loc = Diags[0].first;
  8883. } else if (!IsConstExpr) {
  8884. // FIXME: This shouldn't happen.
  8885. if (Loc) *Loc = getExprLoc();
  8886. }
  8887. return IsConstExpr;
  8888. }
  8889. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  8890. const FunctionDecl *Callee,
  8891. ArrayRef<const Expr*> Args) const {
  8892. Expr::EvalStatus Status;
  8893. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  8894. ArgVector ArgValues(Args.size());
  8895. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  8896. I != E; ++I) {
  8897. if ((*I)->isValueDependent() ||
  8898. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  8899. // If evaluation fails, throw away the argument entirely.
  8900. ArgValues[I - Args.begin()] = APValue();
  8901. if (Info.EvalStatus.HasSideEffects)
  8902. return false;
  8903. }
  8904. // Build fake call to Callee.
  8905. CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
  8906. ArgValues.data());
  8907. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  8908. }
  8909. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  8910. SmallVectorImpl<
  8911. PartialDiagnosticAt> &Diags) {
  8912. // FIXME: It would be useful to check constexpr function templates, but at the
  8913. // moment the constant expression evaluator cannot cope with the non-rigorous
  8914. // ASTs which we build for dependent expressions.
  8915. if (FD->isDependentContext())
  8916. return true;
  8917. Expr::EvalStatus Status;
  8918. Status.Diag = &Diags;
  8919. EvalInfo Info(FD->getASTContext(), Status,
  8920. EvalInfo::EM_PotentialConstantExpression);
  8921. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  8922. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  8923. // Fabricate an arbitrary expression on the stack and pretend that it
  8924. // is a temporary being used as the 'this' pointer.
  8925. LValue This;
  8926. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  8927. This.set(&VIE, Info.CurrentCall->Index);
  8928. ArrayRef<const Expr*> Args;
  8929. APValue Scratch;
  8930. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  8931. // Evaluate the call as a constant initializer, to allow the construction
  8932. // of objects of non-literal types.
  8933. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  8934. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  8935. } else {
  8936. SourceLocation Loc = FD->getLocation();
  8937. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  8938. Args, FD->getBody(), Info, Scratch, nullptr);
  8939. }
  8940. return Diags.empty();
  8941. }
  8942. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  8943. const FunctionDecl *FD,
  8944. SmallVectorImpl<
  8945. PartialDiagnosticAt> &Diags) {
  8946. Expr::EvalStatus Status;
  8947. Status.Diag = &Diags;
  8948. EvalInfo Info(FD->getASTContext(), Status,
  8949. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  8950. // Fabricate a call stack frame to give the arguments a plausible cover story.
  8951. ArrayRef<const Expr*> Args;
  8952. ArgVector ArgValues(0);
  8953. bool Success = EvaluateArgs(Args, ArgValues, Info);
  8954. (void)Success;
  8955. assert(Success &&
  8956. "Failed to set up arguments for potential constant evaluation");
  8957. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  8958. APValue ResultScratch;
  8959. Evaluate(ResultScratch, Info, E);
  8960. return Diags.empty();
  8961. }
  8962. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  8963. unsigned Type) const {
  8964. if (!getType()->isPointerType())
  8965. return false;
  8966. Expr::EvalStatus Status;
  8967. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  8968. return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  8969. }