ExprConstant.cpp 407 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483
  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. #define DEBUG_TYPE "exprconstant"
  50. using namespace clang;
  51. using llvm::APSInt;
  52. using llvm::APFloat;
  53. static bool IsGlobalLValue(APValue::LValueBase B);
  54. namespace {
  55. struct LValue;
  56. struct CallStackFrame;
  57. struct EvalInfo;
  58. static QualType getType(APValue::LValueBase B) {
  59. if (!B) return QualType();
  60. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  61. // FIXME: It's unclear where we're supposed to take the type from, and
  62. // this actually matters for arrays of unknown bound. Eg:
  63. //
  64. // extern int arr[]; void f() { extern int arr[3]; };
  65. // constexpr int *p = &arr[1]; // valid?
  66. //
  67. // For now, we take the array bound from the most recent declaration.
  68. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  69. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  70. QualType T = Redecl->getType();
  71. if (!T->isIncompleteArrayType())
  72. return T;
  73. }
  74. return D->getType();
  75. }
  76. const Expr *Base = B.get<const Expr*>();
  77. // For a materialized temporary, the type of the temporary we materialized
  78. // may not be the type of the expression.
  79. if (const MaterializeTemporaryExpr *MTE =
  80. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  81. SmallVector<const Expr *, 2> CommaLHSs;
  82. SmallVector<SubobjectAdjustment, 2> Adjustments;
  83. const Expr *Temp = MTE->GetTemporaryExpr();
  84. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  85. Adjustments);
  86. // Keep any cv-qualifiers from the reference if we generated a temporary
  87. // for it directly. Otherwise use the type after adjustment.
  88. if (!Adjustments.empty())
  89. return Inner->getType();
  90. }
  91. return Base->getType();
  92. }
  93. /// Get an LValue path entry, which is known to not be an array index, as a
  94. /// field or base class.
  95. static
  96. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  97. APValue::BaseOrMemberType Value;
  98. Value.setFromOpaqueValue(E.BaseOrMember);
  99. return Value;
  100. }
  101. /// Get an LValue path entry, which is known to not be an array index, as a
  102. /// field declaration.
  103. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  104. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  105. }
  106. /// Get an LValue path entry, which is known to not be an array index, as a
  107. /// base class declaration.
  108. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  109. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  110. }
  111. /// Determine whether this LValue path entry for a base class names a virtual
  112. /// base class.
  113. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  114. return getAsBaseOrMember(E).getInt();
  115. }
  116. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  117. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  118. const FunctionDecl *Callee = CE->getDirectCallee();
  119. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  120. }
  121. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  122. /// This will look through a single cast.
  123. ///
  124. /// Returns null if we couldn't unwrap a function with alloc_size.
  125. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  126. if (!E->getType()->isPointerType())
  127. return nullptr;
  128. E = E->IgnoreParens();
  129. // If we're doing a variable assignment from e.g. malloc(N), there will
  130. // probably be a cast of some kind. In exotic cases, we might also see a
  131. // top-level ExprWithCleanups. Ignore them either way.
  132. if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
  133. E = EC->getSubExpr()->IgnoreParens();
  134. if (const auto *Cast = dyn_cast<CastExpr>(E))
  135. E = Cast->getSubExpr()->IgnoreParens();
  136. if (const auto *CE = dyn_cast<CallExpr>(E))
  137. return getAllocSizeAttr(CE) ? CE : nullptr;
  138. return nullptr;
  139. }
  140. /// Determines whether or not the given Base contains a call to a function
  141. /// with the alloc_size attribute.
  142. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  143. const auto *E = Base.dyn_cast<const Expr *>();
  144. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  145. }
  146. /// The bound to claim that an array of unknown bound has.
  147. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  148. /// to an arbitrary value that's likely to loudly break things if it's used.
  149. static const uint64_t AssumedSizeForUnsizedArray =
  150. std::numeric_limits<uint64_t>::max() / 2;
  151. /// Determines if an LValue with the given LValueBase will have an unsized
  152. /// array in its designator.
  153. /// Find the path length and type of the most-derived subobject in the given
  154. /// path, and find the size of the containing array, if any.
  155. static unsigned
  156. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  157. ArrayRef<APValue::LValuePathEntry> Path,
  158. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  159. bool &FirstEntryIsUnsizedArray) {
  160. // This only accepts LValueBases from APValues, and APValues don't support
  161. // arrays that lack size info.
  162. assert(!isBaseAnAllocSizeCall(Base) &&
  163. "Unsized arrays shouldn't appear here");
  164. unsigned MostDerivedLength = 0;
  165. Type = getType(Base);
  166. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  167. if (Type->isArrayType()) {
  168. const ArrayType *AT = Ctx.getAsArrayType(Type);
  169. Type = AT->getElementType();
  170. MostDerivedLength = I + 1;
  171. IsArray = true;
  172. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  173. ArraySize = CAT->getSize().getZExtValue();
  174. } else {
  175. assert(I == 0 && "unexpected unsized array designator");
  176. FirstEntryIsUnsizedArray = true;
  177. ArraySize = AssumedSizeForUnsizedArray;
  178. }
  179. } else if (Type->isAnyComplexType()) {
  180. const ComplexType *CT = Type->castAs<ComplexType>();
  181. Type = CT->getElementType();
  182. ArraySize = 2;
  183. MostDerivedLength = I + 1;
  184. IsArray = true;
  185. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  186. Type = FD->getType();
  187. ArraySize = 0;
  188. MostDerivedLength = I + 1;
  189. IsArray = false;
  190. } else {
  191. // Path[I] describes a base class.
  192. ArraySize = 0;
  193. IsArray = false;
  194. }
  195. }
  196. return MostDerivedLength;
  197. }
  198. // The order of this enum is important for diagnostics.
  199. enum CheckSubobjectKind {
  200. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  201. CSK_This, CSK_Real, CSK_Imag
  202. };
  203. /// A path from a glvalue to a subobject of that glvalue.
  204. struct SubobjectDesignator {
  205. /// True if the subobject was named in a manner not supported by C++11. Such
  206. /// lvalues can still be folded, but they are not core constant expressions
  207. /// and we cannot perform lvalue-to-rvalue conversions on them.
  208. unsigned Invalid : 1;
  209. /// Is this a pointer one past the end of an object?
  210. unsigned IsOnePastTheEnd : 1;
  211. /// Indicator of whether the first entry is an unsized array.
  212. unsigned FirstEntryIsAnUnsizedArray : 1;
  213. /// Indicator of whether the most-derived object is an array element.
  214. unsigned MostDerivedIsArrayElement : 1;
  215. /// The length of the path to the most-derived object of which this is a
  216. /// subobject.
  217. unsigned MostDerivedPathLength : 28;
  218. /// The size of the array of which the most-derived object is an element.
  219. /// This will always be 0 if the most-derived object is not an array
  220. /// element. 0 is not an indicator of whether or not the most-derived object
  221. /// is an array, however, because 0-length arrays are allowed.
  222. ///
  223. /// If the current array is an unsized array, the value of this is
  224. /// undefined.
  225. uint64_t MostDerivedArraySize;
  226. /// The type of the most derived object referred to by this address.
  227. QualType MostDerivedType;
  228. typedef APValue::LValuePathEntry PathEntry;
  229. /// The entries on the path from the glvalue to the designated subobject.
  230. SmallVector<PathEntry, 8> Entries;
  231. SubobjectDesignator() : Invalid(true) {}
  232. explicit SubobjectDesignator(QualType T)
  233. : Invalid(false), IsOnePastTheEnd(false),
  234. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  235. MostDerivedPathLength(0), MostDerivedArraySize(0),
  236. MostDerivedType(T) {}
  237. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  238. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  239. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  240. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  241. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  242. if (!Invalid) {
  243. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  244. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  245. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  246. if (V.getLValueBase()) {
  247. bool IsArray = false;
  248. bool FirstIsUnsizedArray = false;
  249. MostDerivedPathLength = findMostDerivedSubobject(
  250. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  251. MostDerivedType, IsArray, FirstIsUnsizedArray);
  252. MostDerivedIsArrayElement = IsArray;
  253. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  254. }
  255. }
  256. }
  257. void setInvalid() {
  258. Invalid = true;
  259. Entries.clear();
  260. }
  261. /// Determine whether the most derived subobject is an array without a
  262. /// known bound.
  263. bool isMostDerivedAnUnsizedArray() const {
  264. assert(!Invalid && "Calling this makes no sense on invalid designators");
  265. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  266. }
  267. /// Determine what the most derived array's size is. Results in an assertion
  268. /// failure if the most derived array lacks a size.
  269. uint64_t getMostDerivedArraySize() const {
  270. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  271. return MostDerivedArraySize;
  272. }
  273. /// Determine whether this is a one-past-the-end pointer.
  274. bool isOnePastTheEnd() const {
  275. assert(!Invalid);
  276. if (IsOnePastTheEnd)
  277. return true;
  278. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  279. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  280. return true;
  281. return false;
  282. }
  283. /// Get the range of valid index adjustments in the form
  284. /// {maximum value that can be subtracted from this pointer,
  285. /// maximum value that can be added to this pointer}
  286. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  287. if (Invalid || isMostDerivedAnUnsizedArray())
  288. return {0, 0};
  289. // [expr.add]p4: For the purposes of these operators, a pointer to a
  290. // nonarray object behaves the same as a pointer to the first element of
  291. // an array of length one with the type of the object as its element type.
  292. bool IsArray = MostDerivedPathLength == Entries.size() &&
  293. MostDerivedIsArrayElement;
  294. uint64_t ArrayIndex =
  295. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  296. uint64_t ArraySize =
  297. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  298. return {ArrayIndex, ArraySize - ArrayIndex};
  299. }
  300. /// Check that this refers to a valid subobject.
  301. bool isValidSubobject() const {
  302. if (Invalid)
  303. return false;
  304. return !isOnePastTheEnd();
  305. }
  306. /// Check that this refers to a valid subobject, and if not, produce a
  307. /// relevant diagnostic and set the designator as invalid.
  308. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  309. /// Get the type of the designated object.
  310. QualType getType(ASTContext &Ctx) const {
  311. assert(!Invalid && "invalid designator has no subobject type");
  312. return MostDerivedPathLength == Entries.size()
  313. ? MostDerivedType
  314. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  315. }
  316. /// Update this designator to refer to the first element within this array.
  317. void addArrayUnchecked(const ConstantArrayType *CAT) {
  318. PathEntry Entry;
  319. Entry.ArrayIndex = 0;
  320. Entries.push_back(Entry);
  321. // This is a most-derived object.
  322. MostDerivedType = CAT->getElementType();
  323. MostDerivedIsArrayElement = true;
  324. MostDerivedArraySize = CAT->getSize().getZExtValue();
  325. MostDerivedPathLength = Entries.size();
  326. }
  327. /// Update this designator to refer to the first element within the array of
  328. /// elements of type T. This is an array of unknown size.
  329. void addUnsizedArrayUnchecked(QualType ElemTy) {
  330. PathEntry Entry;
  331. Entry.ArrayIndex = 0;
  332. Entries.push_back(Entry);
  333. MostDerivedType = ElemTy;
  334. MostDerivedIsArrayElement = true;
  335. // The value in MostDerivedArraySize is undefined in this case. So, set it
  336. // to an arbitrary value that's likely to loudly break things if it's
  337. // used.
  338. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  339. MostDerivedPathLength = Entries.size();
  340. }
  341. /// Update this designator to refer to the given base or member of this
  342. /// object.
  343. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  344. PathEntry Entry;
  345. APValue::BaseOrMemberType Value(D, Virtual);
  346. Entry.BaseOrMember = Value.getOpaqueValue();
  347. Entries.push_back(Entry);
  348. // If this isn't a base class, it's a new most-derived object.
  349. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  350. MostDerivedType = FD->getType();
  351. MostDerivedIsArrayElement = false;
  352. MostDerivedArraySize = 0;
  353. MostDerivedPathLength = Entries.size();
  354. }
  355. }
  356. /// Update this designator to refer to the given complex component.
  357. void addComplexUnchecked(QualType EltTy, bool Imag) {
  358. PathEntry Entry;
  359. Entry.ArrayIndex = Imag;
  360. Entries.push_back(Entry);
  361. // This is technically a most-derived object, though in practice this
  362. // is unlikely to matter.
  363. MostDerivedType = EltTy;
  364. MostDerivedIsArrayElement = true;
  365. MostDerivedArraySize = 2;
  366. MostDerivedPathLength = Entries.size();
  367. }
  368. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  369. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  370. const APSInt &N);
  371. /// Add N to the address of this subobject.
  372. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  373. if (Invalid || !N) return;
  374. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  375. if (isMostDerivedAnUnsizedArray()) {
  376. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  377. // Can't verify -- trust that the user is doing the right thing (or if
  378. // not, trust that the caller will catch the bad behavior).
  379. // FIXME: Should we reject if this overflows, at least?
  380. Entries.back().ArrayIndex += TruncatedN;
  381. return;
  382. }
  383. // [expr.add]p4: For the purposes of these operators, a pointer to a
  384. // nonarray object behaves the same as a pointer to the first element of
  385. // an array of length one with the type of the object as its element type.
  386. bool IsArray = MostDerivedPathLength == Entries.size() &&
  387. MostDerivedIsArrayElement;
  388. uint64_t ArrayIndex =
  389. IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
  390. uint64_t ArraySize =
  391. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  392. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  393. // Calculate the actual index in a wide enough type, so we can include
  394. // it in the note.
  395. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  396. (llvm::APInt&)N += ArrayIndex;
  397. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  398. diagnosePointerArithmetic(Info, E, N);
  399. setInvalid();
  400. return;
  401. }
  402. ArrayIndex += TruncatedN;
  403. assert(ArrayIndex <= ArraySize &&
  404. "bounds check succeeded for out-of-bounds index");
  405. if (IsArray)
  406. Entries.back().ArrayIndex = ArrayIndex;
  407. else
  408. IsOnePastTheEnd = (ArrayIndex != 0);
  409. }
  410. };
  411. /// A stack frame in the constexpr call stack.
  412. struct CallStackFrame {
  413. EvalInfo &Info;
  414. /// Parent - The caller of this stack frame.
  415. CallStackFrame *Caller;
  416. /// Callee - The function which was called.
  417. const FunctionDecl *Callee;
  418. /// This - The binding for the this pointer in this call, if any.
  419. const LValue *This;
  420. /// Arguments - Parameter bindings for this function call, indexed by
  421. /// parameters' function scope indices.
  422. APValue *Arguments;
  423. // Note that we intentionally use std::map here so that references to
  424. // values are stable.
  425. typedef std::pair<const void *, unsigned> MapKeyTy;
  426. typedef std::map<MapKeyTy, APValue> MapTy;
  427. /// Temporaries - Temporary lvalues materialized within this stack frame.
  428. MapTy Temporaries;
  429. /// CallLoc - The location of the call expression for this call.
  430. SourceLocation CallLoc;
  431. /// Index - The call index of this call.
  432. unsigned Index;
  433. /// The stack of integers for tracking version numbers for temporaries.
  434. SmallVector<unsigned, 2> TempVersionStack = {1};
  435. unsigned CurTempVersion = TempVersionStack.back();
  436. unsigned getTempVersion() const { return TempVersionStack.back(); }
  437. void pushTempVersion() {
  438. TempVersionStack.push_back(++CurTempVersion);
  439. }
  440. void popTempVersion() {
  441. TempVersionStack.pop_back();
  442. }
  443. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  444. // on the overall stack usage of deeply-recursing constexpr evaluataions.
  445. // (We should cache this map rather than recomputing it repeatedly.)
  446. // But let's try this and see how it goes; we can look into caching the map
  447. // as a later change.
  448. /// LambdaCaptureFields - Mapping from captured variables/this to
  449. /// corresponding data members in the closure class.
  450. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  451. FieldDecl *LambdaThisCaptureField;
  452. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  453. const FunctionDecl *Callee, const LValue *This,
  454. APValue *Arguments);
  455. ~CallStackFrame();
  456. // Return the temporary for Key whose version number is Version.
  457. APValue *getTemporary(const void *Key, unsigned Version) {
  458. MapKeyTy KV(Key, Version);
  459. auto LB = Temporaries.lower_bound(KV);
  460. if (LB != Temporaries.end() && LB->first == KV)
  461. return &LB->second;
  462. // Pair (Key,Version) wasn't found in the map. Check that no elements
  463. // in the map have 'Key' as their key.
  464. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  465. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  466. "Element with key 'Key' found in map");
  467. return nullptr;
  468. }
  469. // Return the current temporary for Key in the map.
  470. APValue *getCurrentTemporary(const void *Key) {
  471. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  472. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  473. return &std::prev(UB)->second;
  474. return nullptr;
  475. }
  476. // Return the version number of the current temporary for Key.
  477. unsigned getCurrentTemporaryVersion(const void *Key) const {
  478. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  479. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  480. return std::prev(UB)->first.second;
  481. return 0;
  482. }
  483. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  484. };
  485. /// Temporarily override 'this'.
  486. class ThisOverrideRAII {
  487. public:
  488. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  489. : Frame(Frame), OldThis(Frame.This) {
  490. if (Enable)
  491. Frame.This = NewThis;
  492. }
  493. ~ThisOverrideRAII() {
  494. Frame.This = OldThis;
  495. }
  496. private:
  497. CallStackFrame &Frame;
  498. const LValue *OldThis;
  499. };
  500. /// A partial diagnostic which we might know in advance that we are not going
  501. /// to emit.
  502. class OptionalDiagnostic {
  503. PartialDiagnostic *Diag;
  504. public:
  505. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  506. : Diag(Diag) {}
  507. template<typename T>
  508. OptionalDiagnostic &operator<<(const T &v) {
  509. if (Diag)
  510. *Diag << v;
  511. return *this;
  512. }
  513. OptionalDiagnostic &operator<<(const APSInt &I) {
  514. if (Diag) {
  515. SmallVector<char, 32> Buffer;
  516. I.toString(Buffer);
  517. *Diag << StringRef(Buffer.data(), Buffer.size());
  518. }
  519. return *this;
  520. }
  521. OptionalDiagnostic &operator<<(const APFloat &F) {
  522. if (Diag) {
  523. // FIXME: Force the precision of the source value down so we don't
  524. // print digits which are usually useless (we don't really care here if
  525. // we truncate a digit by accident in edge cases). Ideally,
  526. // APFloat::toString would automatically print the shortest
  527. // representation which rounds to the correct value, but it's a bit
  528. // tricky to implement.
  529. unsigned precision =
  530. llvm::APFloat::semanticsPrecision(F.getSemantics());
  531. precision = (precision * 59 + 195) / 196;
  532. SmallVector<char, 32> Buffer;
  533. F.toString(Buffer, precision);
  534. *Diag << StringRef(Buffer.data(), Buffer.size());
  535. }
  536. return *this;
  537. }
  538. };
  539. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  540. class Cleanup {
  541. llvm::PointerIntPair<APValue*, 1, bool> Value;
  542. public:
  543. Cleanup(APValue *Val, bool IsLifetimeExtended)
  544. : Value(Val, IsLifetimeExtended) {}
  545. bool isLifetimeExtended() const { return Value.getInt(); }
  546. void endLifetime() {
  547. *Value.getPointer() = APValue();
  548. }
  549. };
  550. /// EvalInfo - This is a private struct used by the evaluator to capture
  551. /// information about a subexpression as it is folded. It retains information
  552. /// about the AST context, but also maintains information about the folded
  553. /// expression.
  554. ///
  555. /// If an expression could be evaluated, it is still possible it is not a C
  556. /// "integer constant expression" or constant expression. If not, this struct
  557. /// captures information about how and why not.
  558. ///
  559. /// One bit of information passed *into* the request for constant folding
  560. /// indicates whether the subexpression is "evaluated" or not according to C
  561. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  562. /// evaluate the expression regardless of what the RHS is, but C only allows
  563. /// certain things in certain situations.
  564. struct EvalInfo {
  565. ASTContext &Ctx;
  566. /// EvalStatus - Contains information about the evaluation.
  567. Expr::EvalStatus &EvalStatus;
  568. /// CurrentCall - The top of the constexpr call stack.
  569. CallStackFrame *CurrentCall;
  570. /// CallStackDepth - The number of calls in the call stack right now.
  571. unsigned CallStackDepth;
  572. /// NextCallIndex - The next call index to assign.
  573. unsigned NextCallIndex;
  574. /// StepsLeft - The remaining number of evaluation steps we're permitted
  575. /// to perform. This is essentially a limit for the number of statements
  576. /// we will evaluate.
  577. unsigned StepsLeft;
  578. /// BottomFrame - The frame in which evaluation started. This must be
  579. /// initialized after CurrentCall and CallStackDepth.
  580. CallStackFrame BottomFrame;
  581. /// A stack of values whose lifetimes end at the end of some surrounding
  582. /// evaluation frame.
  583. llvm::SmallVector<Cleanup, 16> CleanupStack;
  584. /// EvaluatingDecl - This is the declaration whose initializer is being
  585. /// evaluated, if any.
  586. APValue::LValueBase EvaluatingDecl;
  587. /// EvaluatingDeclValue - This is the value being constructed for the
  588. /// declaration whose initializer is being evaluated, if any.
  589. APValue *EvaluatingDeclValue;
  590. /// EvaluatingObject - Pair of the AST node that an lvalue represents and
  591. /// the call index that that lvalue was allocated in.
  592. typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
  593. EvaluatingObject;
  594. /// EvaluatingConstructors - Set of objects that are currently being
  595. /// constructed.
  596. llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
  597. struct EvaluatingConstructorRAII {
  598. EvalInfo &EI;
  599. EvaluatingObject Object;
  600. bool DidInsert;
  601. EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
  602. : EI(EI), Object(Object) {
  603. DidInsert = EI.EvaluatingConstructors.insert(Object).second;
  604. }
  605. ~EvaluatingConstructorRAII() {
  606. if (DidInsert) EI.EvaluatingConstructors.erase(Object);
  607. }
  608. };
  609. bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
  610. unsigned Version) {
  611. return EvaluatingConstructors.count(
  612. EvaluatingObject(Decl, {CallIndex, Version}));
  613. }
  614. /// The current array initialization index, if we're performing array
  615. /// initialization.
  616. uint64_t ArrayInitIndex = -1;
  617. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  618. /// notes attached to it will also be stored, otherwise they will not be.
  619. bool HasActiveDiagnostic;
  620. /// Have we emitted a diagnostic explaining why we couldn't constant
  621. /// fold (not just why it's not strictly a constant expression)?
  622. bool HasFoldFailureDiagnostic;
  623. /// Whether or not we're currently speculatively evaluating.
  624. bool IsSpeculativelyEvaluating;
  625. enum EvaluationMode {
  626. /// Evaluate as a constant expression. Stop if we find that the expression
  627. /// is not a constant expression.
  628. EM_ConstantExpression,
  629. /// Evaluate as a potential constant expression. Keep going if we hit a
  630. /// construct that we can't evaluate yet (because we don't yet know the
  631. /// value of something) but stop if we hit something that could never be
  632. /// a constant expression.
  633. EM_PotentialConstantExpression,
  634. /// Fold the expression to a constant. Stop if we hit a side-effect that
  635. /// we can't model.
  636. EM_ConstantFold,
  637. /// Evaluate the expression looking for integer overflow and similar
  638. /// issues. Don't worry about side-effects, and try to visit all
  639. /// subexpressions.
  640. EM_EvaluateForOverflow,
  641. /// Evaluate in any way we know how. Don't worry about side-effects that
  642. /// can't be modeled.
  643. EM_IgnoreSideEffects,
  644. /// Evaluate as a constant expression. Stop if we find that the expression
  645. /// is not a constant expression. Some expressions can be retried in the
  646. /// optimizer if we don't constant fold them here, but in an unevaluated
  647. /// context we try to fold them immediately since the optimizer never
  648. /// gets a chance to look at it.
  649. EM_ConstantExpressionUnevaluated,
  650. /// Evaluate as a potential constant expression. Keep going if we hit a
  651. /// construct that we can't evaluate yet (because we don't yet know the
  652. /// value of something) but stop if we hit something that could never be
  653. /// a constant expression. Some expressions can be retried in the
  654. /// optimizer if we don't constant fold them here, but in an unevaluated
  655. /// context we try to fold them immediately since the optimizer never
  656. /// gets a chance to look at it.
  657. EM_PotentialConstantExpressionUnevaluated,
  658. /// Evaluate as a constant expression. In certain scenarios, if:
  659. /// - we find a MemberExpr with a base that can't be evaluated, or
  660. /// - we find a variable initialized with a call to a function that has
  661. /// the alloc_size attribute on it
  662. /// then we may consider evaluation to have succeeded.
  663. ///
  664. /// In either case, the LValue returned shall have an invalid base; in the
  665. /// former, the base will be the invalid MemberExpr, in the latter, the
  666. /// base will be either the alloc_size CallExpr or a CastExpr wrapping
  667. /// said CallExpr.
  668. EM_OffsetFold,
  669. } EvalMode;
  670. /// Are we checking whether the expression is a potential constant
  671. /// expression?
  672. bool checkingPotentialConstantExpression() const {
  673. return EvalMode == EM_PotentialConstantExpression ||
  674. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  675. }
  676. /// Are we checking an expression for overflow?
  677. // FIXME: We should check for any kind of undefined or suspicious behavior
  678. // in such constructs, not just overflow.
  679. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  680. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  681. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  682. CallStackDepth(0), NextCallIndex(1),
  683. StepsLeft(getLangOpts().ConstexprStepLimit),
  684. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  685. EvaluatingDecl((const ValueDecl *)nullptr),
  686. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  687. HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
  688. EvalMode(Mode) {}
  689. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  690. EvaluatingDecl = Base;
  691. EvaluatingDeclValue = &Value;
  692. EvaluatingConstructors.insert({Base, {0, 0}});
  693. }
  694. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  695. bool CheckCallLimit(SourceLocation Loc) {
  696. // Don't perform any constexpr calls (other than the call we're checking)
  697. // when checking a potential constant expression.
  698. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  699. return false;
  700. if (NextCallIndex == 0) {
  701. // NextCallIndex has wrapped around.
  702. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  703. return false;
  704. }
  705. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  706. return true;
  707. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  708. << getLangOpts().ConstexprCallDepth;
  709. return false;
  710. }
  711. CallStackFrame *getCallFrame(unsigned CallIndex) {
  712. assert(CallIndex && "no call index in getCallFrame");
  713. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  714. // be null in this loop.
  715. CallStackFrame *Frame = CurrentCall;
  716. while (Frame->Index > CallIndex)
  717. Frame = Frame->Caller;
  718. return (Frame->Index == CallIndex) ? Frame : nullptr;
  719. }
  720. bool nextStep(const Stmt *S) {
  721. if (!StepsLeft) {
  722. FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
  723. return false;
  724. }
  725. --StepsLeft;
  726. return true;
  727. }
  728. private:
  729. /// Add a diagnostic to the diagnostics list.
  730. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  731. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  732. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  733. return EvalStatus.Diag->back().second;
  734. }
  735. /// Add notes containing a call stack to the current point of evaluation.
  736. void addCallStack(unsigned Limit);
  737. private:
  738. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  739. unsigned ExtraNotes, bool IsCCEDiag) {
  740. if (EvalStatus.Diag) {
  741. // If we have a prior diagnostic, it will be noting that the expression
  742. // isn't a constant expression. This diagnostic is more important,
  743. // unless we require this evaluation to produce a constant expression.
  744. //
  745. // FIXME: We might want to show both diagnostics to the user in
  746. // EM_ConstantFold mode.
  747. if (!EvalStatus.Diag->empty()) {
  748. switch (EvalMode) {
  749. case EM_ConstantFold:
  750. case EM_IgnoreSideEffects:
  751. case EM_EvaluateForOverflow:
  752. if (!HasFoldFailureDiagnostic)
  753. break;
  754. // We've already failed to fold something. Keep that diagnostic.
  755. LLVM_FALLTHROUGH;
  756. case EM_ConstantExpression:
  757. case EM_PotentialConstantExpression:
  758. case EM_ConstantExpressionUnevaluated:
  759. case EM_PotentialConstantExpressionUnevaluated:
  760. case EM_OffsetFold:
  761. HasActiveDiagnostic = false;
  762. return OptionalDiagnostic();
  763. }
  764. }
  765. unsigned CallStackNotes = CallStackDepth - 1;
  766. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  767. if (Limit)
  768. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  769. if (checkingPotentialConstantExpression())
  770. CallStackNotes = 0;
  771. HasActiveDiagnostic = true;
  772. HasFoldFailureDiagnostic = !IsCCEDiag;
  773. EvalStatus.Diag->clear();
  774. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  775. addDiag(Loc, DiagId);
  776. if (!checkingPotentialConstantExpression())
  777. addCallStack(Limit);
  778. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  779. }
  780. HasActiveDiagnostic = false;
  781. return OptionalDiagnostic();
  782. }
  783. public:
  784. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  785. OptionalDiagnostic
  786. FFDiag(SourceLocation Loc,
  787. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  788. unsigned ExtraNotes = 0) {
  789. return Diag(Loc, DiagId, ExtraNotes, false);
  790. }
  791. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  792. = diag::note_invalid_subexpr_in_const_expr,
  793. unsigned ExtraNotes = 0) {
  794. if (EvalStatus.Diag)
  795. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  796. HasActiveDiagnostic = false;
  797. return OptionalDiagnostic();
  798. }
  799. /// Diagnose that the evaluation does not produce a C++11 core constant
  800. /// expression.
  801. ///
  802. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  803. /// EM_PotentialConstantExpression mode and we produce one of these.
  804. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  805. = diag::note_invalid_subexpr_in_const_expr,
  806. unsigned ExtraNotes = 0) {
  807. // Don't override a previous diagnostic. Don't bother collecting
  808. // diagnostics if we're evaluating for overflow.
  809. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  810. HasActiveDiagnostic = false;
  811. return OptionalDiagnostic();
  812. }
  813. return Diag(Loc, DiagId, ExtraNotes, true);
  814. }
  815. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  816. = diag::note_invalid_subexpr_in_const_expr,
  817. unsigned ExtraNotes = 0) {
  818. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  819. }
  820. /// Add a note to a prior diagnostic.
  821. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  822. if (!HasActiveDiagnostic)
  823. return OptionalDiagnostic();
  824. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  825. }
  826. /// Add a stack of notes to a prior diagnostic.
  827. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  828. if (HasActiveDiagnostic) {
  829. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  830. Diags.begin(), Diags.end());
  831. }
  832. }
  833. /// Should we continue evaluation after encountering a side-effect that we
  834. /// couldn't model?
  835. bool keepEvaluatingAfterSideEffect() {
  836. switch (EvalMode) {
  837. case EM_PotentialConstantExpression:
  838. case EM_PotentialConstantExpressionUnevaluated:
  839. case EM_EvaluateForOverflow:
  840. case EM_IgnoreSideEffects:
  841. return true;
  842. case EM_ConstantExpression:
  843. case EM_ConstantExpressionUnevaluated:
  844. case EM_ConstantFold:
  845. case EM_OffsetFold:
  846. return false;
  847. }
  848. llvm_unreachable("Missed EvalMode case");
  849. }
  850. /// Note that we have had a side-effect, and determine whether we should
  851. /// keep evaluating.
  852. bool noteSideEffect() {
  853. EvalStatus.HasSideEffects = true;
  854. return keepEvaluatingAfterSideEffect();
  855. }
  856. /// Should we continue evaluation after encountering undefined behavior?
  857. bool keepEvaluatingAfterUndefinedBehavior() {
  858. switch (EvalMode) {
  859. case EM_EvaluateForOverflow:
  860. case EM_IgnoreSideEffects:
  861. case EM_ConstantFold:
  862. case EM_OffsetFold:
  863. return true;
  864. case EM_PotentialConstantExpression:
  865. case EM_PotentialConstantExpressionUnevaluated:
  866. case EM_ConstantExpression:
  867. case EM_ConstantExpressionUnevaluated:
  868. return false;
  869. }
  870. llvm_unreachable("Missed EvalMode case");
  871. }
  872. /// Note that we hit something that was technically undefined behavior, but
  873. /// that we can evaluate past it (such as signed overflow or floating-point
  874. /// division by zero.)
  875. bool noteUndefinedBehavior() {
  876. EvalStatus.HasUndefinedBehavior = true;
  877. return keepEvaluatingAfterUndefinedBehavior();
  878. }
  879. /// Should we continue evaluation as much as possible after encountering a
  880. /// construct which can't be reduced to a value?
  881. bool keepEvaluatingAfterFailure() {
  882. if (!StepsLeft)
  883. return false;
  884. switch (EvalMode) {
  885. case EM_PotentialConstantExpression:
  886. case EM_PotentialConstantExpressionUnevaluated:
  887. case EM_EvaluateForOverflow:
  888. return true;
  889. case EM_ConstantExpression:
  890. case EM_ConstantExpressionUnevaluated:
  891. case EM_ConstantFold:
  892. case EM_IgnoreSideEffects:
  893. case EM_OffsetFold:
  894. return false;
  895. }
  896. llvm_unreachable("Missed EvalMode case");
  897. }
  898. /// Notes that we failed to evaluate an expression that other expressions
  899. /// directly depend on, and determine if we should keep evaluating. This
  900. /// should only be called if we actually intend to keep evaluating.
  901. ///
  902. /// Call noteSideEffect() instead if we may be able to ignore the value that
  903. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  904. ///
  905. /// (Foo(), 1) // use noteSideEffect
  906. /// (Foo() || true) // use noteSideEffect
  907. /// Foo() + 1 // use noteFailure
  908. LLVM_NODISCARD bool noteFailure() {
  909. // Failure when evaluating some expression often means there is some
  910. // subexpression whose evaluation was skipped. Therefore, (because we
  911. // don't track whether we skipped an expression when unwinding after an
  912. // evaluation failure) every evaluation failure that bubbles up from a
  913. // subexpression implies that a side-effect has potentially happened. We
  914. // skip setting the HasSideEffects flag to true until we decide to
  915. // continue evaluating after that point, which happens here.
  916. bool KeepGoing = keepEvaluatingAfterFailure();
  917. EvalStatus.HasSideEffects |= KeepGoing;
  918. return KeepGoing;
  919. }
  920. class ArrayInitLoopIndex {
  921. EvalInfo &Info;
  922. uint64_t OuterIndex;
  923. public:
  924. ArrayInitLoopIndex(EvalInfo &Info)
  925. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  926. Info.ArrayInitIndex = 0;
  927. }
  928. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  929. operator uint64_t&() { return Info.ArrayInitIndex; }
  930. };
  931. };
  932. /// Object used to treat all foldable expressions as constant expressions.
  933. struct FoldConstant {
  934. EvalInfo &Info;
  935. bool Enabled;
  936. bool HadNoPriorDiags;
  937. EvalInfo::EvaluationMode OldMode;
  938. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  939. : Info(Info),
  940. Enabled(Enabled),
  941. HadNoPriorDiags(Info.EvalStatus.Diag &&
  942. Info.EvalStatus.Diag->empty() &&
  943. !Info.EvalStatus.HasSideEffects),
  944. OldMode(Info.EvalMode) {
  945. if (Enabled &&
  946. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  947. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  948. Info.EvalMode = EvalInfo::EM_ConstantFold;
  949. }
  950. void keepDiagnostics() { Enabled = false; }
  951. ~FoldConstant() {
  952. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  953. !Info.EvalStatus.HasSideEffects)
  954. Info.EvalStatus.Diag->clear();
  955. Info.EvalMode = OldMode;
  956. }
  957. };
  958. /// RAII object used to treat the current evaluation as the correct pointer
  959. /// offset fold for the current EvalMode
  960. struct FoldOffsetRAII {
  961. EvalInfo &Info;
  962. EvalInfo::EvaluationMode OldMode;
  963. explicit FoldOffsetRAII(EvalInfo &Info)
  964. : Info(Info), OldMode(Info.EvalMode) {
  965. if (!Info.checkingPotentialConstantExpression())
  966. Info.EvalMode = EvalInfo::EM_OffsetFold;
  967. }
  968. ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
  969. };
  970. /// RAII object used to optionally suppress diagnostics and side-effects from
  971. /// a speculative evaluation.
  972. class SpeculativeEvaluationRAII {
  973. EvalInfo *Info = nullptr;
  974. Expr::EvalStatus OldStatus;
  975. bool OldIsSpeculativelyEvaluating;
  976. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  977. Info = Other.Info;
  978. OldStatus = Other.OldStatus;
  979. OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
  980. Other.Info = nullptr;
  981. }
  982. void maybeRestoreState() {
  983. if (!Info)
  984. return;
  985. Info->EvalStatus = OldStatus;
  986. Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
  987. }
  988. public:
  989. SpeculativeEvaluationRAII() = default;
  990. SpeculativeEvaluationRAII(
  991. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  992. : Info(&Info), OldStatus(Info.EvalStatus),
  993. OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
  994. Info.EvalStatus.Diag = NewDiag;
  995. Info.IsSpeculativelyEvaluating = true;
  996. }
  997. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  998. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  999. moveFromAndCancel(std::move(Other));
  1000. }
  1001. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1002. maybeRestoreState();
  1003. moveFromAndCancel(std::move(Other));
  1004. return *this;
  1005. }
  1006. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1007. };
  1008. /// RAII object wrapping a full-expression or block scope, and handling
  1009. /// the ending of the lifetime of temporaries created within it.
  1010. template<bool IsFullExpression>
  1011. class ScopeRAII {
  1012. EvalInfo &Info;
  1013. unsigned OldStackSize;
  1014. public:
  1015. ScopeRAII(EvalInfo &Info)
  1016. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1017. // Push a new temporary version. This is needed to distinguish between
  1018. // temporaries created in different iterations of a loop.
  1019. Info.CurrentCall->pushTempVersion();
  1020. }
  1021. ~ScopeRAII() {
  1022. // Body moved to a static method to encourage the compiler to inline away
  1023. // instances of this class.
  1024. cleanup(Info, OldStackSize);
  1025. Info.CurrentCall->popTempVersion();
  1026. }
  1027. private:
  1028. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1029. unsigned NewEnd = OldStackSize;
  1030. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1031. I != N; ++I) {
  1032. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1033. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1034. // to do, just move this cleanup to the right place in the stack.
  1035. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1036. ++NewEnd;
  1037. } else {
  1038. // End the lifetime of the object.
  1039. Info.CleanupStack[I].endLifetime();
  1040. }
  1041. }
  1042. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1043. Info.CleanupStack.end());
  1044. }
  1045. };
  1046. typedef ScopeRAII<false> BlockScopeRAII;
  1047. typedef ScopeRAII<true> FullExpressionRAII;
  1048. }
  1049. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1050. CheckSubobjectKind CSK) {
  1051. if (Invalid)
  1052. return false;
  1053. if (isOnePastTheEnd()) {
  1054. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1055. << CSK;
  1056. setInvalid();
  1057. return false;
  1058. }
  1059. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1060. // must actually be at least one array element; even a VLA cannot have a
  1061. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1062. return true;
  1063. }
  1064. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1065. const Expr *E) {
  1066. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1067. // Do not set the designator as invalid: we can represent this situation,
  1068. // and correct handling of __builtin_object_size requires us to do so.
  1069. }
  1070. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1071. const Expr *E,
  1072. const APSInt &N) {
  1073. // If we're complaining, we must be able to statically determine the size of
  1074. // the most derived array.
  1075. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1076. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1077. << N << /*array*/ 0
  1078. << static_cast<unsigned>(getMostDerivedArraySize());
  1079. else
  1080. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1081. << N << /*non-array*/ 1;
  1082. setInvalid();
  1083. }
  1084. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1085. const FunctionDecl *Callee, const LValue *This,
  1086. APValue *Arguments)
  1087. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1088. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1089. Info.CurrentCall = this;
  1090. ++Info.CallStackDepth;
  1091. }
  1092. CallStackFrame::~CallStackFrame() {
  1093. assert(Info.CurrentCall == this && "calls retired out of order");
  1094. --Info.CallStackDepth;
  1095. Info.CurrentCall = Caller;
  1096. }
  1097. APValue &CallStackFrame::createTemporary(const void *Key,
  1098. bool IsLifetimeExtended) {
  1099. unsigned Version = Info.CurrentCall->getTempVersion();
  1100. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1101. assert(Result.isUninit() && "temporary created multiple times");
  1102. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1103. return Result;
  1104. }
  1105. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1106. void EvalInfo::addCallStack(unsigned Limit) {
  1107. // Determine which calls to skip, if any.
  1108. unsigned ActiveCalls = CallStackDepth - 1;
  1109. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1110. if (Limit && Limit < ActiveCalls) {
  1111. SkipStart = Limit / 2 + Limit % 2;
  1112. SkipEnd = ActiveCalls - Limit / 2;
  1113. }
  1114. // Walk the call stack and add the diagnostics.
  1115. unsigned CallIdx = 0;
  1116. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1117. Frame = Frame->Caller, ++CallIdx) {
  1118. // Skip this call?
  1119. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1120. if (CallIdx == SkipStart) {
  1121. // Note that we're skipping calls.
  1122. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1123. << unsigned(ActiveCalls - Limit);
  1124. }
  1125. continue;
  1126. }
  1127. // Use a different note for an inheriting constructor, because from the
  1128. // user's perspective it's not really a function at all.
  1129. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1130. if (CD->isInheritingConstructor()) {
  1131. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1132. << CD->getParent();
  1133. continue;
  1134. }
  1135. }
  1136. SmallVector<char, 128> Buffer;
  1137. llvm::raw_svector_ostream Out(Buffer);
  1138. describeCall(Frame, Out);
  1139. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1140. }
  1141. }
  1142. namespace {
  1143. struct ComplexValue {
  1144. private:
  1145. bool IsInt;
  1146. public:
  1147. APSInt IntReal, IntImag;
  1148. APFloat FloatReal, FloatImag;
  1149. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1150. void makeComplexFloat() { IsInt = false; }
  1151. bool isComplexFloat() const { return !IsInt; }
  1152. APFloat &getComplexFloatReal() { return FloatReal; }
  1153. APFloat &getComplexFloatImag() { return FloatImag; }
  1154. void makeComplexInt() { IsInt = true; }
  1155. bool isComplexInt() const { return IsInt; }
  1156. APSInt &getComplexIntReal() { return IntReal; }
  1157. APSInt &getComplexIntImag() { return IntImag; }
  1158. void moveInto(APValue &v) const {
  1159. if (isComplexFloat())
  1160. v = APValue(FloatReal, FloatImag);
  1161. else
  1162. v = APValue(IntReal, IntImag);
  1163. }
  1164. void setFrom(const APValue &v) {
  1165. assert(v.isComplexFloat() || v.isComplexInt());
  1166. if (v.isComplexFloat()) {
  1167. makeComplexFloat();
  1168. FloatReal = v.getComplexFloatReal();
  1169. FloatImag = v.getComplexFloatImag();
  1170. } else {
  1171. makeComplexInt();
  1172. IntReal = v.getComplexIntReal();
  1173. IntImag = v.getComplexIntImag();
  1174. }
  1175. }
  1176. };
  1177. struct LValue {
  1178. APValue::LValueBase Base;
  1179. CharUnits Offset;
  1180. SubobjectDesignator Designator;
  1181. bool IsNullPtr : 1;
  1182. bool InvalidBase : 1;
  1183. const APValue::LValueBase getLValueBase() const { return Base; }
  1184. CharUnits &getLValueOffset() { return Offset; }
  1185. const CharUnits &getLValueOffset() const { return Offset; }
  1186. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1187. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1188. bool isNullPointer() const { return IsNullPtr;}
  1189. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1190. unsigned getLValueVersion() const { return Base.getVersion(); }
  1191. void moveInto(APValue &V) const {
  1192. if (Designator.Invalid)
  1193. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1194. else {
  1195. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1196. V = APValue(Base, Offset, Designator.Entries,
  1197. Designator.IsOnePastTheEnd, IsNullPtr);
  1198. }
  1199. }
  1200. void setFrom(ASTContext &Ctx, const APValue &V) {
  1201. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1202. Base = V.getLValueBase();
  1203. Offset = V.getLValueOffset();
  1204. InvalidBase = false;
  1205. Designator = SubobjectDesignator(Ctx, V);
  1206. IsNullPtr = V.isNullPointer();
  1207. }
  1208. void set(APValue::LValueBase B, bool BInvalid = false) {
  1209. #ifndef NDEBUG
  1210. // We only allow a few types of invalid bases. Enforce that here.
  1211. if (BInvalid) {
  1212. const auto *E = B.get<const Expr *>();
  1213. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1214. "Unexpected type of invalid base");
  1215. }
  1216. #endif
  1217. Base = B;
  1218. Offset = CharUnits::fromQuantity(0);
  1219. InvalidBase = BInvalid;
  1220. Designator = SubobjectDesignator(getType(B));
  1221. IsNullPtr = false;
  1222. }
  1223. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1224. Base = (Expr *)nullptr;
  1225. Offset = CharUnits::fromQuantity(TargetVal);
  1226. InvalidBase = false;
  1227. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1228. IsNullPtr = true;
  1229. }
  1230. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1231. set(B, true);
  1232. }
  1233. // Check that this LValue is not based on a null pointer. If it is, produce
  1234. // a diagnostic and mark the designator as invalid.
  1235. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1236. CheckSubobjectKind CSK) {
  1237. if (Designator.Invalid)
  1238. return false;
  1239. if (IsNullPtr) {
  1240. Info.CCEDiag(E, diag::note_constexpr_null_subobject)
  1241. << CSK;
  1242. Designator.setInvalid();
  1243. return false;
  1244. }
  1245. return true;
  1246. }
  1247. // Check this LValue refers to an object. If not, set the designator to be
  1248. // invalid and emit a diagnostic.
  1249. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1250. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1251. Designator.checkSubobject(Info, E, CSK);
  1252. }
  1253. void addDecl(EvalInfo &Info, const Expr *E,
  1254. const Decl *D, bool Virtual = false) {
  1255. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1256. Designator.addDeclUnchecked(D, Virtual);
  1257. }
  1258. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1259. if (!Designator.Entries.empty()) {
  1260. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1261. Designator.setInvalid();
  1262. return;
  1263. }
  1264. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1265. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1266. Designator.FirstEntryIsAnUnsizedArray = true;
  1267. Designator.addUnsizedArrayUnchecked(ElemTy);
  1268. }
  1269. }
  1270. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1271. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1272. Designator.addArrayUnchecked(CAT);
  1273. }
  1274. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1275. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1276. Designator.addComplexUnchecked(EltTy, Imag);
  1277. }
  1278. void clearIsNullPointer() {
  1279. IsNullPtr = false;
  1280. }
  1281. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1282. const APSInt &Index, CharUnits ElementSize) {
  1283. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1284. // but we're not required to diagnose it and it's valid in C++.)
  1285. if (!Index)
  1286. return;
  1287. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1288. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1289. // offsets.
  1290. uint64_t Offset64 = Offset.getQuantity();
  1291. uint64_t ElemSize64 = ElementSize.getQuantity();
  1292. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1293. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1294. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1295. Designator.adjustIndex(Info, E, Index);
  1296. clearIsNullPointer();
  1297. }
  1298. void adjustOffset(CharUnits N) {
  1299. Offset += N;
  1300. if (N.getQuantity())
  1301. clearIsNullPointer();
  1302. }
  1303. };
  1304. struct MemberPtr {
  1305. MemberPtr() {}
  1306. explicit MemberPtr(const ValueDecl *Decl) :
  1307. DeclAndIsDerivedMember(Decl, false), Path() {}
  1308. /// The member or (direct or indirect) field referred to by this member
  1309. /// pointer, or 0 if this is a null member pointer.
  1310. const ValueDecl *getDecl() const {
  1311. return DeclAndIsDerivedMember.getPointer();
  1312. }
  1313. /// Is this actually a member of some type derived from the relevant class?
  1314. bool isDerivedMember() const {
  1315. return DeclAndIsDerivedMember.getInt();
  1316. }
  1317. /// Get the class which the declaration actually lives in.
  1318. const CXXRecordDecl *getContainingRecord() const {
  1319. return cast<CXXRecordDecl>(
  1320. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1321. }
  1322. void moveInto(APValue &V) const {
  1323. V = APValue(getDecl(), isDerivedMember(), Path);
  1324. }
  1325. void setFrom(const APValue &V) {
  1326. assert(V.isMemberPointer());
  1327. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1328. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1329. Path.clear();
  1330. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1331. Path.insert(Path.end(), P.begin(), P.end());
  1332. }
  1333. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1334. /// whether the member is a member of some class derived from the class type
  1335. /// of the member pointer.
  1336. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1337. /// Path - The path of base/derived classes from the member declaration's
  1338. /// class (exclusive) to the class type of the member pointer (inclusive).
  1339. SmallVector<const CXXRecordDecl*, 4> Path;
  1340. /// Perform a cast towards the class of the Decl (either up or down the
  1341. /// hierarchy).
  1342. bool castBack(const CXXRecordDecl *Class) {
  1343. assert(!Path.empty());
  1344. const CXXRecordDecl *Expected;
  1345. if (Path.size() >= 2)
  1346. Expected = Path[Path.size() - 2];
  1347. else
  1348. Expected = getContainingRecord();
  1349. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1350. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1351. // if B does not contain the original member and is not a base or
  1352. // derived class of the class containing the original member, the result
  1353. // of the cast is undefined.
  1354. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1355. // (D::*). We consider that to be a language defect.
  1356. return false;
  1357. }
  1358. Path.pop_back();
  1359. return true;
  1360. }
  1361. /// Perform a base-to-derived member pointer cast.
  1362. bool castToDerived(const CXXRecordDecl *Derived) {
  1363. if (!getDecl())
  1364. return true;
  1365. if (!isDerivedMember()) {
  1366. Path.push_back(Derived);
  1367. return true;
  1368. }
  1369. if (!castBack(Derived))
  1370. return false;
  1371. if (Path.empty())
  1372. DeclAndIsDerivedMember.setInt(false);
  1373. return true;
  1374. }
  1375. /// Perform a derived-to-base member pointer cast.
  1376. bool castToBase(const CXXRecordDecl *Base) {
  1377. if (!getDecl())
  1378. return true;
  1379. if (Path.empty())
  1380. DeclAndIsDerivedMember.setInt(true);
  1381. if (isDerivedMember()) {
  1382. Path.push_back(Base);
  1383. return true;
  1384. }
  1385. return castBack(Base);
  1386. }
  1387. };
  1388. /// Compare two member pointers, which are assumed to be of the same type.
  1389. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1390. if (!LHS.getDecl() || !RHS.getDecl())
  1391. return !LHS.getDecl() && !RHS.getDecl();
  1392. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1393. return false;
  1394. return LHS.Path == RHS.Path;
  1395. }
  1396. }
  1397. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1398. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1399. const LValue &This, const Expr *E,
  1400. bool AllowNonLiteralTypes = false);
  1401. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1402. bool InvalidBaseOK = false);
  1403. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1404. bool InvalidBaseOK = false);
  1405. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1406. EvalInfo &Info);
  1407. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1408. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1409. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1410. EvalInfo &Info);
  1411. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1412. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1413. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1414. EvalInfo &Info);
  1415. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1416. //===----------------------------------------------------------------------===//
  1417. // Misc utilities
  1418. //===----------------------------------------------------------------------===//
  1419. /// A helper function to create a temporary and set an LValue.
  1420. template <class KeyTy>
  1421. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1422. LValue &LV, CallStackFrame &Frame) {
  1423. LV.set({Key, Frame.Info.CurrentCall->Index,
  1424. Frame.Info.CurrentCall->getTempVersion()});
  1425. return Frame.createTemporary(Key, IsLifetimeExtended);
  1426. }
  1427. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1428. /// preserving its value (by extending by up to one bit as needed).
  1429. static void negateAsSigned(APSInt &Int) {
  1430. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1431. Int = Int.extend(Int.getBitWidth() + 1);
  1432. Int.setIsSigned(true);
  1433. }
  1434. Int = -Int;
  1435. }
  1436. /// Produce a string describing the given constexpr call.
  1437. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1438. unsigned ArgIndex = 0;
  1439. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1440. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1441. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1442. if (!IsMemberCall)
  1443. Out << *Frame->Callee << '(';
  1444. if (Frame->This && IsMemberCall) {
  1445. APValue Val;
  1446. Frame->This->moveInto(Val);
  1447. Val.printPretty(Out, Frame->Info.Ctx,
  1448. Frame->This->Designator.MostDerivedType);
  1449. // FIXME: Add parens around Val if needed.
  1450. Out << "->" << *Frame->Callee << '(';
  1451. IsMemberCall = false;
  1452. }
  1453. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1454. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1455. if (ArgIndex > (unsigned)IsMemberCall)
  1456. Out << ", ";
  1457. const ParmVarDecl *Param = *I;
  1458. const APValue &Arg = Frame->Arguments[ArgIndex];
  1459. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1460. if (ArgIndex == 0 && IsMemberCall)
  1461. Out << "->" << *Frame->Callee << '(';
  1462. }
  1463. Out << ')';
  1464. }
  1465. /// Evaluate an expression to see if it had side-effects, and discard its
  1466. /// result.
  1467. /// \return \c true if the caller should keep evaluating.
  1468. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1469. APValue Scratch;
  1470. if (!Evaluate(Scratch, Info, E))
  1471. // We don't need the value, but we might have skipped a side effect here.
  1472. return Info.noteSideEffect();
  1473. return true;
  1474. }
  1475. /// Should this call expression be treated as a string literal?
  1476. static bool IsStringLiteralCall(const CallExpr *E) {
  1477. unsigned Builtin = E->getBuiltinCallee();
  1478. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1479. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1480. }
  1481. static bool IsGlobalLValue(APValue::LValueBase B) {
  1482. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1483. // constant expression of pointer type that evaluates to...
  1484. // ... a null pointer value, or a prvalue core constant expression of type
  1485. // std::nullptr_t.
  1486. if (!B) return true;
  1487. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1488. // ... the address of an object with static storage duration,
  1489. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1490. return VD->hasGlobalStorage();
  1491. // ... the address of a function,
  1492. return isa<FunctionDecl>(D);
  1493. }
  1494. const Expr *E = B.get<const Expr*>();
  1495. switch (E->getStmtClass()) {
  1496. default:
  1497. return false;
  1498. case Expr::CompoundLiteralExprClass: {
  1499. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1500. return CLE->isFileScope() && CLE->isLValue();
  1501. }
  1502. case Expr::MaterializeTemporaryExprClass:
  1503. // A materialized temporary might have been lifetime-extended to static
  1504. // storage duration.
  1505. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1506. // A string literal has static storage duration.
  1507. case Expr::StringLiteralClass:
  1508. case Expr::PredefinedExprClass:
  1509. case Expr::ObjCStringLiteralClass:
  1510. case Expr::ObjCEncodeExprClass:
  1511. case Expr::CXXTypeidExprClass:
  1512. case Expr::CXXUuidofExprClass:
  1513. return true;
  1514. case Expr::CallExprClass:
  1515. return IsStringLiteralCall(cast<CallExpr>(E));
  1516. // For GCC compatibility, &&label has static storage duration.
  1517. case Expr::AddrLabelExprClass:
  1518. return true;
  1519. // A Block literal expression may be used as the initialization value for
  1520. // Block variables at global or local static scope.
  1521. case Expr::BlockExprClass:
  1522. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1523. case Expr::ImplicitValueInitExprClass:
  1524. // FIXME:
  1525. // We can never form an lvalue with an implicit value initialization as its
  1526. // base through expression evaluation, so these only appear in one case: the
  1527. // implicit variable declaration we invent when checking whether a constexpr
  1528. // constructor can produce a constant expression. We must assume that such
  1529. // an expression might be a global lvalue.
  1530. return true;
  1531. }
  1532. }
  1533. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1534. return LVal.Base.dyn_cast<const ValueDecl*>();
  1535. }
  1536. static bool IsLiteralLValue(const LValue &Value) {
  1537. if (Value.getLValueCallIndex())
  1538. return false;
  1539. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1540. return E && !isa<MaterializeTemporaryExpr>(E);
  1541. }
  1542. static bool IsWeakLValue(const LValue &Value) {
  1543. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1544. return Decl && Decl->isWeak();
  1545. }
  1546. static bool isZeroSized(const LValue &Value) {
  1547. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1548. if (Decl && isa<VarDecl>(Decl)) {
  1549. QualType Ty = Decl->getType();
  1550. if (Ty->isArrayType())
  1551. return Ty->isIncompleteType() ||
  1552. Decl->getASTContext().getTypeSize(Ty) == 0;
  1553. }
  1554. return false;
  1555. }
  1556. static bool HasSameBase(const LValue &A, const LValue &B) {
  1557. if (!A.getLValueBase())
  1558. return !B.getLValueBase();
  1559. if (!B.getLValueBase())
  1560. return false;
  1561. if (A.getLValueBase().getOpaqueValue() !=
  1562. B.getLValueBase().getOpaqueValue()) {
  1563. const Decl *ADecl = GetLValueBaseDecl(A);
  1564. if (!ADecl)
  1565. return false;
  1566. const Decl *BDecl = GetLValueBaseDecl(B);
  1567. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1568. return false;
  1569. }
  1570. return IsGlobalLValue(A.getLValueBase()) ||
  1571. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1572. A.getLValueVersion() == B.getLValueVersion());
  1573. }
  1574. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1575. assert(Base && "no location for a null lvalue");
  1576. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1577. if (VD)
  1578. Info.Note(VD->getLocation(), diag::note_declared_at);
  1579. else
  1580. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1581. diag::note_constexpr_temporary_here);
  1582. }
  1583. /// Check that this reference or pointer core constant expression is a valid
  1584. /// value for an address or reference constant expression. Return true if we
  1585. /// can fold this expression, whether or not it's a constant expression.
  1586. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1587. QualType Type, const LValue &LVal,
  1588. Expr::ConstExprUsage Usage) {
  1589. bool IsReferenceType = Type->isReferenceType();
  1590. APValue::LValueBase Base = LVal.getLValueBase();
  1591. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1592. // Check that the object is a global. Note that the fake 'this' object we
  1593. // manufacture when checking potential constant expressions is conservatively
  1594. // assumed to be global here.
  1595. if (!IsGlobalLValue(Base)) {
  1596. if (Info.getLangOpts().CPlusPlus11) {
  1597. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1598. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1599. << IsReferenceType << !Designator.Entries.empty()
  1600. << !!VD << VD;
  1601. NoteLValueLocation(Info, Base);
  1602. } else {
  1603. Info.FFDiag(Loc);
  1604. }
  1605. // Don't allow references to temporaries to escape.
  1606. return false;
  1607. }
  1608. assert((Info.checkingPotentialConstantExpression() ||
  1609. LVal.getLValueCallIndex() == 0) &&
  1610. "have call index for global lvalue");
  1611. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1612. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1613. // Check if this is a thread-local variable.
  1614. if (Var->getTLSKind())
  1615. return false;
  1616. // A dllimport variable never acts like a constant.
  1617. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1618. return false;
  1619. }
  1620. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1621. // __declspec(dllimport) must be handled very carefully:
  1622. // We must never initialize an expression with the thunk in C++.
  1623. // Doing otherwise would allow the same id-expression to yield
  1624. // different addresses for the same function in different translation
  1625. // units. However, this means that we must dynamically initialize the
  1626. // expression with the contents of the import address table at runtime.
  1627. //
  1628. // The C language has no notion of ODR; furthermore, it has no notion of
  1629. // dynamic initialization. This means that we are permitted to
  1630. // perform initialization with the address of the thunk.
  1631. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1632. FD->hasAttr<DLLImportAttr>())
  1633. return false;
  1634. }
  1635. }
  1636. // Allow address constant expressions to be past-the-end pointers. This is
  1637. // an extension: the standard requires them to point to an object.
  1638. if (!IsReferenceType)
  1639. return true;
  1640. // A reference constant expression must refer to an object.
  1641. if (!Base) {
  1642. // FIXME: diagnostic
  1643. Info.CCEDiag(Loc);
  1644. return true;
  1645. }
  1646. // Does this refer one past the end of some object?
  1647. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1648. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1649. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1650. << !Designator.Entries.empty() << !!VD << VD;
  1651. NoteLValueLocation(Info, Base);
  1652. }
  1653. return true;
  1654. }
  1655. /// Member pointers are constant expressions unless they point to a
  1656. /// non-virtual dllimport member function.
  1657. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1658. SourceLocation Loc,
  1659. QualType Type,
  1660. const APValue &Value,
  1661. Expr::ConstExprUsage Usage) {
  1662. const ValueDecl *Member = Value.getMemberPointerDecl();
  1663. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1664. if (!FD)
  1665. return true;
  1666. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1667. !FD->hasAttr<DLLImportAttr>();
  1668. }
  1669. /// Check that this core constant expression is of literal type, and if not,
  1670. /// produce an appropriate diagnostic.
  1671. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1672. const LValue *This = nullptr) {
  1673. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1674. return true;
  1675. // C++1y: A constant initializer for an object o [...] may also invoke
  1676. // constexpr constructors for o and its subobjects even if those objects
  1677. // are of non-literal class types.
  1678. //
  1679. // C++11 missed this detail for aggregates, so classes like this:
  1680. // struct foo_t { union { int i; volatile int j; } u; };
  1681. // are not (obviously) initializable like so:
  1682. // __attribute__((__require_constant_initialization__))
  1683. // static const foo_t x = {{0}};
  1684. // because "i" is a subobject with non-literal initialization (due to the
  1685. // volatile member of the union). See:
  1686. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1687. // Therefore, we use the C++1y behavior.
  1688. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1689. return true;
  1690. // Prvalue constant expressions must be of literal types.
  1691. if (Info.getLangOpts().CPlusPlus11)
  1692. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1693. << E->getType();
  1694. else
  1695. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1696. return false;
  1697. }
  1698. /// Check that this core constant expression value is a valid value for a
  1699. /// constant expression. If not, report an appropriate diagnostic. Does not
  1700. /// check that the expression is of literal type.
  1701. static bool
  1702. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1703. const APValue &Value,
  1704. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1705. if (Value.isUninit()) {
  1706. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1707. << true << Type;
  1708. return false;
  1709. }
  1710. // We allow _Atomic(T) to be initialized from anything that T can be
  1711. // initialized from.
  1712. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1713. Type = AT->getValueType();
  1714. // Core issue 1454: For a literal constant expression of array or class type,
  1715. // each subobject of its value shall have been initialized by a constant
  1716. // expression.
  1717. if (Value.isArray()) {
  1718. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1719. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1720. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1721. Value.getArrayInitializedElt(I), Usage))
  1722. return false;
  1723. }
  1724. if (!Value.hasArrayFiller())
  1725. return true;
  1726. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1727. Usage);
  1728. }
  1729. if (Value.isUnion() && Value.getUnionField()) {
  1730. return CheckConstantExpression(Info, DiagLoc,
  1731. Value.getUnionField()->getType(),
  1732. Value.getUnionValue(), Usage);
  1733. }
  1734. if (Value.isStruct()) {
  1735. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1736. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1737. unsigned BaseIndex = 0;
  1738. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1739. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1740. Value.getStructBase(BaseIndex), Usage))
  1741. return false;
  1742. ++BaseIndex;
  1743. }
  1744. }
  1745. for (const auto *I : RD->fields()) {
  1746. if (I->isUnnamedBitfield())
  1747. continue;
  1748. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1749. Value.getStructField(I->getFieldIndex()),
  1750. Usage))
  1751. return false;
  1752. }
  1753. }
  1754. if (Value.isLValue()) {
  1755. LValue LVal;
  1756. LVal.setFrom(Info.Ctx, Value);
  1757. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1758. }
  1759. if (Value.isMemberPointer())
  1760. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1761. // Everything else is fine.
  1762. return true;
  1763. }
  1764. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1765. // A null base expression indicates a null pointer. These are always
  1766. // evaluatable, and they are false unless the offset is zero.
  1767. if (!Value.getLValueBase()) {
  1768. Result = !Value.getLValueOffset().isZero();
  1769. return true;
  1770. }
  1771. // We have a non-null base. These are generally known to be true, but if it's
  1772. // a weak declaration it can be null at runtime.
  1773. Result = true;
  1774. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1775. return !Decl || !Decl->isWeak();
  1776. }
  1777. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1778. switch (Val.getKind()) {
  1779. case APValue::Uninitialized:
  1780. return false;
  1781. case APValue::Int:
  1782. Result = Val.getInt().getBoolValue();
  1783. return true;
  1784. case APValue::Float:
  1785. Result = !Val.getFloat().isZero();
  1786. return true;
  1787. case APValue::ComplexInt:
  1788. Result = Val.getComplexIntReal().getBoolValue() ||
  1789. Val.getComplexIntImag().getBoolValue();
  1790. return true;
  1791. case APValue::ComplexFloat:
  1792. Result = !Val.getComplexFloatReal().isZero() ||
  1793. !Val.getComplexFloatImag().isZero();
  1794. return true;
  1795. case APValue::LValue:
  1796. return EvalPointerValueAsBool(Val, Result);
  1797. case APValue::MemberPointer:
  1798. Result = Val.getMemberPointerDecl();
  1799. return true;
  1800. case APValue::Vector:
  1801. case APValue::Array:
  1802. case APValue::Struct:
  1803. case APValue::Union:
  1804. case APValue::AddrLabelDiff:
  1805. return false;
  1806. }
  1807. llvm_unreachable("unknown APValue kind");
  1808. }
  1809. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1810. EvalInfo &Info) {
  1811. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1812. APValue Val;
  1813. if (!Evaluate(Val, Info, E))
  1814. return false;
  1815. return HandleConversionToBool(Val, Result);
  1816. }
  1817. template<typename T>
  1818. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1819. const T &SrcValue, QualType DestType) {
  1820. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1821. << SrcValue << DestType;
  1822. return Info.noteUndefinedBehavior();
  1823. }
  1824. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1825. QualType SrcType, const APFloat &Value,
  1826. QualType DestType, APSInt &Result) {
  1827. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1828. // Determine whether we are converting to unsigned or signed.
  1829. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1830. Result = APSInt(DestWidth, !DestSigned);
  1831. bool ignored;
  1832. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1833. & APFloat::opInvalidOp)
  1834. return HandleOverflow(Info, E, Value, DestType);
  1835. return true;
  1836. }
  1837. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1838. QualType SrcType, QualType DestType,
  1839. APFloat &Result) {
  1840. APFloat Value = Result;
  1841. bool ignored;
  1842. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1843. APFloat::rmNearestTiesToEven, &ignored)
  1844. & APFloat::opOverflow)
  1845. return HandleOverflow(Info, E, Value, DestType);
  1846. return true;
  1847. }
  1848. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1849. QualType DestType, QualType SrcType,
  1850. const APSInt &Value) {
  1851. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1852. APSInt Result = Value;
  1853. // Figure out if this is a truncate, extend or noop cast.
  1854. // If the input is signed, do a sign extend, noop, or truncate.
  1855. Result = Result.extOrTrunc(DestWidth);
  1856. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1857. return Result;
  1858. }
  1859. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1860. QualType SrcType, const APSInt &Value,
  1861. QualType DestType, APFloat &Result) {
  1862. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1863. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1864. APFloat::rmNearestTiesToEven)
  1865. & APFloat::opOverflow)
  1866. return HandleOverflow(Info, E, Value, DestType);
  1867. return true;
  1868. }
  1869. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1870. APValue &Value, const FieldDecl *FD) {
  1871. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1872. if (!Value.isInt()) {
  1873. // Trying to store a pointer-cast-to-integer into a bitfield.
  1874. // FIXME: In this case, we should provide the diagnostic for casting
  1875. // a pointer to an integer.
  1876. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1877. Info.FFDiag(E);
  1878. return false;
  1879. }
  1880. APSInt &Int = Value.getInt();
  1881. unsigned OldBitWidth = Int.getBitWidth();
  1882. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1883. if (NewBitWidth < OldBitWidth)
  1884. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1885. return true;
  1886. }
  1887. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1888. llvm::APInt &Res) {
  1889. APValue SVal;
  1890. if (!Evaluate(SVal, Info, E))
  1891. return false;
  1892. if (SVal.isInt()) {
  1893. Res = SVal.getInt();
  1894. return true;
  1895. }
  1896. if (SVal.isFloat()) {
  1897. Res = SVal.getFloat().bitcastToAPInt();
  1898. return true;
  1899. }
  1900. if (SVal.isVector()) {
  1901. QualType VecTy = E->getType();
  1902. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1903. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1904. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1905. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1906. Res = llvm::APInt::getNullValue(VecSize);
  1907. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1908. APValue &Elt = SVal.getVectorElt(i);
  1909. llvm::APInt EltAsInt;
  1910. if (Elt.isInt()) {
  1911. EltAsInt = Elt.getInt();
  1912. } else if (Elt.isFloat()) {
  1913. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1914. } else {
  1915. // Don't try to handle vectors of anything other than int or float
  1916. // (not sure if it's possible to hit this case).
  1917. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1918. return false;
  1919. }
  1920. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1921. if (BigEndian)
  1922. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1923. else
  1924. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1925. }
  1926. return true;
  1927. }
  1928. // Give up if the input isn't an int, float, or vector. For example, we
  1929. // reject "(v4i16)(intptr_t)&a".
  1930. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1931. return false;
  1932. }
  1933. /// Perform the given integer operation, which is known to need at most BitWidth
  1934. /// bits, and check for overflow in the original type (if that type was not an
  1935. /// unsigned type).
  1936. template<typename Operation>
  1937. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  1938. const APSInt &LHS, const APSInt &RHS,
  1939. unsigned BitWidth, Operation Op,
  1940. APSInt &Result) {
  1941. if (LHS.isUnsigned()) {
  1942. Result = Op(LHS, RHS);
  1943. return true;
  1944. }
  1945. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  1946. Result = Value.trunc(LHS.getBitWidth());
  1947. if (Result.extend(BitWidth) != Value) {
  1948. if (Info.checkingForOverflow())
  1949. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  1950. diag::warn_integer_constant_overflow)
  1951. << Result.toString(10) << E->getType();
  1952. else
  1953. return HandleOverflow(Info, E, Value, E->getType());
  1954. }
  1955. return true;
  1956. }
  1957. /// Perform the given binary integer operation.
  1958. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  1959. BinaryOperatorKind Opcode, APSInt RHS,
  1960. APSInt &Result) {
  1961. switch (Opcode) {
  1962. default:
  1963. Info.FFDiag(E);
  1964. return false;
  1965. case BO_Mul:
  1966. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  1967. std::multiplies<APSInt>(), Result);
  1968. case BO_Add:
  1969. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1970. std::plus<APSInt>(), Result);
  1971. case BO_Sub:
  1972. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  1973. std::minus<APSInt>(), Result);
  1974. case BO_And: Result = LHS & RHS; return true;
  1975. case BO_Xor: Result = LHS ^ RHS; return true;
  1976. case BO_Or: Result = LHS | RHS; return true;
  1977. case BO_Div:
  1978. case BO_Rem:
  1979. if (RHS == 0) {
  1980. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  1981. return false;
  1982. }
  1983. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  1984. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  1985. // this operation and gives the two's complement result.
  1986. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  1987. LHS.isSigned() && LHS.isMinSignedValue())
  1988. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  1989. E->getType());
  1990. return true;
  1991. case BO_Shl: {
  1992. if (Info.getLangOpts().OpenCL)
  1993. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  1994. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  1995. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  1996. RHS.isUnsigned());
  1997. else if (RHS.isSigned() && RHS.isNegative()) {
  1998. // During constant-folding, a negative shift is an opposite shift. Such
  1999. // a shift is not a constant expression.
  2000. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2001. RHS = -RHS;
  2002. goto shift_right;
  2003. }
  2004. shift_left:
  2005. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2006. // the shifted type.
  2007. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2008. if (SA != RHS) {
  2009. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2010. << RHS << E->getType() << LHS.getBitWidth();
  2011. } else if (LHS.isSigned()) {
  2012. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2013. // operand, and must not overflow the corresponding unsigned type.
  2014. if (LHS.isNegative())
  2015. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2016. else if (LHS.countLeadingZeros() < SA)
  2017. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2018. }
  2019. Result = LHS << SA;
  2020. return true;
  2021. }
  2022. case BO_Shr: {
  2023. if (Info.getLangOpts().OpenCL)
  2024. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2025. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2026. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2027. RHS.isUnsigned());
  2028. else if (RHS.isSigned() && RHS.isNegative()) {
  2029. // During constant-folding, a negative shift is an opposite shift. Such a
  2030. // shift is not a constant expression.
  2031. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2032. RHS = -RHS;
  2033. goto shift_left;
  2034. }
  2035. shift_right:
  2036. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2037. // shifted type.
  2038. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2039. if (SA != RHS)
  2040. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2041. << RHS << E->getType() << LHS.getBitWidth();
  2042. Result = LHS >> SA;
  2043. return true;
  2044. }
  2045. case BO_LT: Result = LHS < RHS; return true;
  2046. case BO_GT: Result = LHS > RHS; return true;
  2047. case BO_LE: Result = LHS <= RHS; return true;
  2048. case BO_GE: Result = LHS >= RHS; return true;
  2049. case BO_EQ: Result = LHS == RHS; return true;
  2050. case BO_NE: Result = LHS != RHS; return true;
  2051. case BO_Cmp:
  2052. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2053. }
  2054. }
  2055. /// Perform the given binary floating-point operation, in-place, on LHS.
  2056. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2057. APFloat &LHS, BinaryOperatorKind Opcode,
  2058. const APFloat &RHS) {
  2059. switch (Opcode) {
  2060. default:
  2061. Info.FFDiag(E);
  2062. return false;
  2063. case BO_Mul:
  2064. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2065. break;
  2066. case BO_Add:
  2067. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2068. break;
  2069. case BO_Sub:
  2070. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2071. break;
  2072. case BO_Div:
  2073. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2074. break;
  2075. }
  2076. if (LHS.isInfinity() || LHS.isNaN()) {
  2077. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2078. return Info.noteUndefinedBehavior();
  2079. }
  2080. return true;
  2081. }
  2082. /// Cast an lvalue referring to a base subobject to a derived class, by
  2083. /// truncating the lvalue's path to the given length.
  2084. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2085. const RecordDecl *TruncatedType,
  2086. unsigned TruncatedElements) {
  2087. SubobjectDesignator &D = Result.Designator;
  2088. // Check we actually point to a derived class object.
  2089. if (TruncatedElements == D.Entries.size())
  2090. return true;
  2091. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2092. "not casting to a derived class");
  2093. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2094. return false;
  2095. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2096. const RecordDecl *RD = TruncatedType;
  2097. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2098. if (RD->isInvalidDecl()) return false;
  2099. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2100. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2101. if (isVirtualBaseClass(D.Entries[I]))
  2102. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2103. else
  2104. Result.Offset -= Layout.getBaseClassOffset(Base);
  2105. RD = Base;
  2106. }
  2107. D.Entries.resize(TruncatedElements);
  2108. return true;
  2109. }
  2110. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2111. const CXXRecordDecl *Derived,
  2112. const CXXRecordDecl *Base,
  2113. const ASTRecordLayout *RL = nullptr) {
  2114. if (!RL) {
  2115. if (Derived->isInvalidDecl()) return false;
  2116. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2117. }
  2118. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2119. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2120. return true;
  2121. }
  2122. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2123. const CXXRecordDecl *DerivedDecl,
  2124. const CXXBaseSpecifier *Base) {
  2125. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2126. if (!Base->isVirtual())
  2127. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2128. SubobjectDesignator &D = Obj.Designator;
  2129. if (D.Invalid)
  2130. return false;
  2131. // Extract most-derived object and corresponding type.
  2132. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2133. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2134. return false;
  2135. // Find the virtual base class.
  2136. if (DerivedDecl->isInvalidDecl()) return false;
  2137. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2138. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2139. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2140. return true;
  2141. }
  2142. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2143. QualType Type, LValue &Result) {
  2144. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2145. PathE = E->path_end();
  2146. PathI != PathE; ++PathI) {
  2147. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2148. *PathI))
  2149. return false;
  2150. Type = (*PathI)->getType();
  2151. }
  2152. return true;
  2153. }
  2154. /// Update LVal to refer to the given field, which must be a member of the type
  2155. /// currently described by LVal.
  2156. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2157. const FieldDecl *FD,
  2158. const ASTRecordLayout *RL = nullptr) {
  2159. if (!RL) {
  2160. if (FD->getParent()->isInvalidDecl()) return false;
  2161. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2162. }
  2163. unsigned I = FD->getFieldIndex();
  2164. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2165. LVal.addDecl(Info, E, FD);
  2166. return true;
  2167. }
  2168. /// Update LVal to refer to the given indirect field.
  2169. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2170. LValue &LVal,
  2171. const IndirectFieldDecl *IFD) {
  2172. for (const auto *C : IFD->chain())
  2173. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2174. return false;
  2175. return true;
  2176. }
  2177. /// Get the size of the given type in char units.
  2178. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2179. QualType Type, CharUnits &Size) {
  2180. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2181. // extension.
  2182. if (Type->isVoidType() || Type->isFunctionType()) {
  2183. Size = CharUnits::One();
  2184. return true;
  2185. }
  2186. if (Type->isDependentType()) {
  2187. Info.FFDiag(Loc);
  2188. return false;
  2189. }
  2190. if (!Type->isConstantSizeType()) {
  2191. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2192. // FIXME: Better diagnostic.
  2193. Info.FFDiag(Loc);
  2194. return false;
  2195. }
  2196. Size = Info.Ctx.getTypeSizeInChars(Type);
  2197. return true;
  2198. }
  2199. /// Update a pointer value to model pointer arithmetic.
  2200. /// \param Info - Information about the ongoing evaluation.
  2201. /// \param E - The expression being evaluated, for diagnostic purposes.
  2202. /// \param LVal - The pointer value to be updated.
  2203. /// \param EltTy - The pointee type represented by LVal.
  2204. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2205. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2206. LValue &LVal, QualType EltTy,
  2207. APSInt Adjustment) {
  2208. CharUnits SizeOfPointee;
  2209. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2210. return false;
  2211. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2212. return true;
  2213. }
  2214. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2215. LValue &LVal, QualType EltTy,
  2216. int64_t Adjustment) {
  2217. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2218. APSInt::get(Adjustment));
  2219. }
  2220. /// Update an lvalue to refer to a component of a complex number.
  2221. /// \param Info - Information about the ongoing evaluation.
  2222. /// \param LVal - The lvalue to be updated.
  2223. /// \param EltTy - The complex number's component type.
  2224. /// \param Imag - False for the real component, true for the imaginary.
  2225. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2226. LValue &LVal, QualType EltTy,
  2227. bool Imag) {
  2228. if (Imag) {
  2229. CharUnits SizeOfComponent;
  2230. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2231. return false;
  2232. LVal.Offset += SizeOfComponent;
  2233. }
  2234. LVal.addComplex(Info, E, EltTy, Imag);
  2235. return true;
  2236. }
  2237. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2238. QualType Type, const LValue &LVal,
  2239. APValue &RVal);
  2240. /// Try to evaluate the initializer for a variable declaration.
  2241. ///
  2242. /// \param Info Information about the ongoing evaluation.
  2243. /// \param E An expression to be used when printing diagnostics.
  2244. /// \param VD The variable whose initializer should be obtained.
  2245. /// \param Frame The frame in which the variable was created. Must be null
  2246. /// if this variable is not local to the evaluation.
  2247. /// \param Result Filled in with a pointer to the value of the variable.
  2248. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2249. const VarDecl *VD, CallStackFrame *Frame,
  2250. APValue *&Result, const LValue *LVal) {
  2251. // If this is a parameter to an active constexpr function call, perform
  2252. // argument substitution.
  2253. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2254. // Assume arguments of a potential constant expression are unknown
  2255. // constant expressions.
  2256. if (Info.checkingPotentialConstantExpression())
  2257. return false;
  2258. if (!Frame || !Frame->Arguments) {
  2259. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2260. return false;
  2261. }
  2262. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2263. return true;
  2264. }
  2265. // If this is a local variable, dig out its value.
  2266. if (Frame) {
  2267. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2268. : Frame->getCurrentTemporary(VD);
  2269. if (!Result) {
  2270. // Assume variables referenced within a lambda's call operator that were
  2271. // not declared within the call operator are captures and during checking
  2272. // of a potential constant expression, assume they are unknown constant
  2273. // expressions.
  2274. assert(isLambdaCallOperator(Frame->Callee) &&
  2275. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2276. "missing value for local variable");
  2277. if (Info.checkingPotentialConstantExpression())
  2278. return false;
  2279. // FIXME: implement capture evaluation during constant expr evaluation.
  2280. Info.FFDiag(E->getLocStart(),
  2281. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2282. << "captures not currently allowed";
  2283. return false;
  2284. }
  2285. return true;
  2286. }
  2287. // Dig out the initializer, and use the declaration which it's attached to.
  2288. const Expr *Init = VD->getAnyInitializer(VD);
  2289. if (!Init || Init->isValueDependent()) {
  2290. // If we're checking a potential constant expression, the variable could be
  2291. // initialized later.
  2292. if (!Info.checkingPotentialConstantExpression())
  2293. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2294. return false;
  2295. }
  2296. // If we're currently evaluating the initializer of this declaration, use that
  2297. // in-flight value.
  2298. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2299. Result = Info.EvaluatingDeclValue;
  2300. return true;
  2301. }
  2302. // Never evaluate the initializer of a weak variable. We can't be sure that
  2303. // this is the definition which will be used.
  2304. if (VD->isWeak()) {
  2305. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2306. return false;
  2307. }
  2308. // Check that we can fold the initializer. In C++, we will have already done
  2309. // this in the cases where it matters for conformance.
  2310. SmallVector<PartialDiagnosticAt, 8> Notes;
  2311. if (!VD->evaluateValue(Notes)) {
  2312. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2313. Notes.size() + 1) << VD;
  2314. Info.Note(VD->getLocation(), diag::note_declared_at);
  2315. Info.addNotes(Notes);
  2316. return false;
  2317. } else if (!VD->checkInitIsICE()) {
  2318. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2319. Notes.size() + 1) << VD;
  2320. Info.Note(VD->getLocation(), diag::note_declared_at);
  2321. Info.addNotes(Notes);
  2322. }
  2323. Result = VD->getEvaluatedValue();
  2324. return true;
  2325. }
  2326. static bool IsConstNonVolatile(QualType T) {
  2327. Qualifiers Quals = T.getQualifiers();
  2328. return Quals.hasConst() && !Quals.hasVolatile();
  2329. }
  2330. /// Get the base index of the given base class within an APValue representing
  2331. /// the given derived class.
  2332. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2333. const CXXRecordDecl *Base) {
  2334. Base = Base->getCanonicalDecl();
  2335. unsigned Index = 0;
  2336. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2337. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2338. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2339. return Index;
  2340. }
  2341. llvm_unreachable("base class missing from derived class's bases list");
  2342. }
  2343. /// Extract the value of a character from a string literal.
  2344. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2345. uint64_t Index) {
  2346. // FIXME: Support MakeStringConstant
  2347. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2348. std::string Str;
  2349. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2350. assert(Index <= Str.size() && "Index too large");
  2351. return APSInt::getUnsigned(Str.c_str()[Index]);
  2352. }
  2353. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2354. Lit = PE->getFunctionName();
  2355. const StringLiteral *S = cast<StringLiteral>(Lit);
  2356. const ConstantArrayType *CAT =
  2357. Info.Ctx.getAsConstantArrayType(S->getType());
  2358. assert(CAT && "string literal isn't an array");
  2359. QualType CharType = CAT->getElementType();
  2360. assert(CharType->isIntegerType() && "unexpected character type");
  2361. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2362. CharType->isUnsignedIntegerType());
  2363. if (Index < S->getLength())
  2364. Value = S->getCodeUnit(Index);
  2365. return Value;
  2366. }
  2367. // Expand a string literal into an array of characters.
  2368. static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
  2369. APValue &Result) {
  2370. const StringLiteral *S = cast<StringLiteral>(Lit);
  2371. const ConstantArrayType *CAT =
  2372. Info.Ctx.getAsConstantArrayType(S->getType());
  2373. assert(CAT && "string literal isn't an array");
  2374. QualType CharType = CAT->getElementType();
  2375. assert(CharType->isIntegerType() && "unexpected character type");
  2376. unsigned Elts = CAT->getSize().getZExtValue();
  2377. Result = APValue(APValue::UninitArray(),
  2378. std::min(S->getLength(), Elts), Elts);
  2379. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2380. CharType->isUnsignedIntegerType());
  2381. if (Result.hasArrayFiller())
  2382. Result.getArrayFiller() = APValue(Value);
  2383. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2384. Value = S->getCodeUnit(I);
  2385. Result.getArrayInitializedElt(I) = APValue(Value);
  2386. }
  2387. }
  2388. // Expand an array so that it has more than Index filled elements.
  2389. static void expandArray(APValue &Array, unsigned Index) {
  2390. unsigned Size = Array.getArraySize();
  2391. assert(Index < Size);
  2392. // Always at least double the number of elements for which we store a value.
  2393. unsigned OldElts = Array.getArrayInitializedElts();
  2394. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2395. NewElts = std::min(Size, std::max(NewElts, 8u));
  2396. // Copy the data across.
  2397. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2398. for (unsigned I = 0; I != OldElts; ++I)
  2399. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2400. for (unsigned I = OldElts; I != NewElts; ++I)
  2401. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2402. if (NewValue.hasArrayFiller())
  2403. NewValue.getArrayFiller() = Array.getArrayFiller();
  2404. Array.swap(NewValue);
  2405. }
  2406. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2407. /// conversion. If it's of class type, we may assume that the copy operation
  2408. /// is trivial. Note that this is never true for a union type with fields
  2409. /// (because the copy always "reads" the active member) and always true for
  2410. /// a non-class type.
  2411. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2412. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2413. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2414. return true;
  2415. if (RD->isEmpty())
  2416. return false;
  2417. for (auto *Field : RD->fields())
  2418. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2419. return true;
  2420. for (auto &BaseSpec : RD->bases())
  2421. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2422. return true;
  2423. return false;
  2424. }
  2425. /// Diagnose an attempt to read from any unreadable field within the specified
  2426. /// type, which might be a class type.
  2427. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2428. QualType T) {
  2429. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2430. if (!RD)
  2431. return false;
  2432. if (!RD->hasMutableFields())
  2433. return false;
  2434. for (auto *Field : RD->fields()) {
  2435. // If we're actually going to read this field in some way, then it can't
  2436. // be mutable. If we're in a union, then assigning to a mutable field
  2437. // (even an empty one) can change the active member, so that's not OK.
  2438. // FIXME: Add core issue number for the union case.
  2439. if (Field->isMutable() &&
  2440. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2441. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2442. Info.Note(Field->getLocation(), diag::note_declared_at);
  2443. return true;
  2444. }
  2445. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2446. return true;
  2447. }
  2448. for (auto &BaseSpec : RD->bases())
  2449. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2450. return true;
  2451. // All mutable fields were empty, and thus not actually read.
  2452. return false;
  2453. }
  2454. /// Kinds of access we can perform on an object, for diagnostics.
  2455. enum AccessKinds {
  2456. AK_Read,
  2457. AK_Assign,
  2458. AK_Increment,
  2459. AK_Decrement
  2460. };
  2461. namespace {
  2462. /// A handle to a complete object (an object that is not a subobject of
  2463. /// another object).
  2464. struct CompleteObject {
  2465. /// The value of the complete object.
  2466. APValue *Value;
  2467. /// The type of the complete object.
  2468. QualType Type;
  2469. bool LifetimeStartedInEvaluation;
  2470. CompleteObject() : Value(nullptr) {}
  2471. CompleteObject(APValue *Value, QualType Type,
  2472. bool LifetimeStartedInEvaluation)
  2473. : Value(Value), Type(Type),
  2474. LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
  2475. assert(Value && "missing value for complete object");
  2476. }
  2477. explicit operator bool() const { return Value; }
  2478. };
  2479. } // end anonymous namespace
  2480. /// Find the designated sub-object of an rvalue.
  2481. template<typename SubobjectHandler>
  2482. typename SubobjectHandler::result_type
  2483. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2484. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2485. if (Sub.Invalid)
  2486. // A diagnostic will have already been produced.
  2487. return handler.failed();
  2488. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2489. if (Info.getLangOpts().CPlusPlus11)
  2490. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2491. ? diag::note_constexpr_access_past_end
  2492. : diag::note_constexpr_access_unsized_array)
  2493. << handler.AccessKind;
  2494. else
  2495. Info.FFDiag(E);
  2496. return handler.failed();
  2497. }
  2498. APValue *O = Obj.Value;
  2499. QualType ObjType = Obj.Type;
  2500. const FieldDecl *LastField = nullptr;
  2501. const bool MayReadMutableMembers =
  2502. Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
  2503. // Walk the designator's path to find the subobject.
  2504. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2505. if (O->isUninit()) {
  2506. if (!Info.checkingPotentialConstantExpression())
  2507. Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
  2508. return handler.failed();
  2509. }
  2510. if (I == N) {
  2511. // If we are reading an object of class type, there may still be more
  2512. // things we need to check: if there are any mutable subobjects, we
  2513. // cannot perform this read. (This only happens when performing a trivial
  2514. // copy or assignment.)
  2515. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2516. !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
  2517. return handler.failed();
  2518. if (!handler.found(*O, ObjType))
  2519. return false;
  2520. // If we modified a bit-field, truncate it to the right width.
  2521. if (handler.AccessKind != AK_Read &&
  2522. LastField && LastField->isBitField() &&
  2523. !truncateBitfieldValue(Info, E, *O, LastField))
  2524. return false;
  2525. return true;
  2526. }
  2527. LastField = nullptr;
  2528. if (ObjType->isArrayType()) {
  2529. // Next subobject is an array element.
  2530. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2531. assert(CAT && "vla in literal type?");
  2532. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2533. if (CAT->getSize().ule(Index)) {
  2534. // Note, it should not be possible to form a pointer with a valid
  2535. // designator which points more than one past the end of the array.
  2536. if (Info.getLangOpts().CPlusPlus11)
  2537. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2538. << handler.AccessKind;
  2539. else
  2540. Info.FFDiag(E);
  2541. return handler.failed();
  2542. }
  2543. ObjType = CAT->getElementType();
  2544. // An array object is represented as either an Array APValue or as an
  2545. // LValue which refers to a string literal.
  2546. if (O->isLValue()) {
  2547. assert(I == N - 1 && "extracting subobject of character?");
  2548. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  2549. if (handler.AccessKind != AK_Read)
  2550. expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
  2551. *O);
  2552. else
  2553. return handler.foundString(*O, ObjType, Index);
  2554. }
  2555. if (O->getArrayInitializedElts() > Index)
  2556. O = &O->getArrayInitializedElt(Index);
  2557. else if (handler.AccessKind != AK_Read) {
  2558. expandArray(*O, Index);
  2559. O = &O->getArrayInitializedElt(Index);
  2560. } else
  2561. O = &O->getArrayFiller();
  2562. } else if (ObjType->isAnyComplexType()) {
  2563. // Next subobject is a complex number.
  2564. uint64_t Index = Sub.Entries[I].ArrayIndex;
  2565. if (Index > 1) {
  2566. if (Info.getLangOpts().CPlusPlus11)
  2567. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2568. << handler.AccessKind;
  2569. else
  2570. Info.FFDiag(E);
  2571. return handler.failed();
  2572. }
  2573. bool WasConstQualified = ObjType.isConstQualified();
  2574. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2575. if (WasConstQualified)
  2576. ObjType.addConst();
  2577. assert(I == N - 1 && "extracting subobject of scalar?");
  2578. if (O->isComplexInt()) {
  2579. return handler.found(Index ? O->getComplexIntImag()
  2580. : O->getComplexIntReal(), ObjType);
  2581. } else {
  2582. assert(O->isComplexFloat());
  2583. return handler.found(Index ? O->getComplexFloatImag()
  2584. : O->getComplexFloatReal(), ObjType);
  2585. }
  2586. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2587. // In C++14 onwards, it is permitted to read a mutable member whose
  2588. // lifetime began within the evaluation.
  2589. // FIXME: Should we also allow this in C++11?
  2590. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2591. !MayReadMutableMembers) {
  2592. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2593. << Field;
  2594. Info.Note(Field->getLocation(), diag::note_declared_at);
  2595. return handler.failed();
  2596. }
  2597. // Next subobject is a class, struct or union field.
  2598. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2599. if (RD->isUnion()) {
  2600. const FieldDecl *UnionField = O->getUnionField();
  2601. if (!UnionField ||
  2602. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2603. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2604. << handler.AccessKind << Field << !UnionField << UnionField;
  2605. return handler.failed();
  2606. }
  2607. O = &O->getUnionValue();
  2608. } else
  2609. O = &O->getStructField(Field->getFieldIndex());
  2610. bool WasConstQualified = ObjType.isConstQualified();
  2611. ObjType = Field->getType();
  2612. if (WasConstQualified && !Field->isMutable())
  2613. ObjType.addConst();
  2614. if (ObjType.isVolatileQualified()) {
  2615. if (Info.getLangOpts().CPlusPlus) {
  2616. // FIXME: Include a description of the path to the volatile subobject.
  2617. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2618. << handler.AccessKind << 2 << Field;
  2619. Info.Note(Field->getLocation(), diag::note_declared_at);
  2620. } else {
  2621. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2622. }
  2623. return handler.failed();
  2624. }
  2625. LastField = Field;
  2626. } else {
  2627. // Next subobject is a base class.
  2628. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2629. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2630. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2631. bool WasConstQualified = ObjType.isConstQualified();
  2632. ObjType = Info.Ctx.getRecordType(Base);
  2633. if (WasConstQualified)
  2634. ObjType.addConst();
  2635. }
  2636. }
  2637. }
  2638. namespace {
  2639. struct ExtractSubobjectHandler {
  2640. EvalInfo &Info;
  2641. APValue &Result;
  2642. static const AccessKinds AccessKind = AK_Read;
  2643. typedef bool result_type;
  2644. bool failed() { return false; }
  2645. bool found(APValue &Subobj, QualType SubobjType) {
  2646. Result = Subobj;
  2647. return true;
  2648. }
  2649. bool found(APSInt &Value, QualType SubobjType) {
  2650. Result = APValue(Value);
  2651. return true;
  2652. }
  2653. bool found(APFloat &Value, QualType SubobjType) {
  2654. Result = APValue(Value);
  2655. return true;
  2656. }
  2657. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2658. Result = APValue(extractStringLiteralCharacter(
  2659. Info, Subobj.getLValueBase().get<const Expr *>(), Character));
  2660. return true;
  2661. }
  2662. };
  2663. } // end anonymous namespace
  2664. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2665. /// Extract the designated sub-object of an rvalue.
  2666. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2667. const CompleteObject &Obj,
  2668. const SubobjectDesignator &Sub,
  2669. APValue &Result) {
  2670. ExtractSubobjectHandler Handler = { Info, Result };
  2671. return findSubobject(Info, E, Obj, Sub, Handler);
  2672. }
  2673. namespace {
  2674. struct ModifySubobjectHandler {
  2675. EvalInfo &Info;
  2676. APValue &NewVal;
  2677. const Expr *E;
  2678. typedef bool result_type;
  2679. static const AccessKinds AccessKind = AK_Assign;
  2680. bool checkConst(QualType QT) {
  2681. // Assigning to a const object has undefined behavior.
  2682. if (QT.isConstQualified()) {
  2683. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2684. return false;
  2685. }
  2686. return true;
  2687. }
  2688. bool failed() { return false; }
  2689. bool found(APValue &Subobj, QualType SubobjType) {
  2690. if (!checkConst(SubobjType))
  2691. return false;
  2692. // We've been given ownership of NewVal, so just swap it in.
  2693. Subobj.swap(NewVal);
  2694. return true;
  2695. }
  2696. bool found(APSInt &Value, QualType SubobjType) {
  2697. if (!checkConst(SubobjType))
  2698. return false;
  2699. if (!NewVal.isInt()) {
  2700. // Maybe trying to write a cast pointer value into a complex?
  2701. Info.FFDiag(E);
  2702. return false;
  2703. }
  2704. Value = NewVal.getInt();
  2705. return true;
  2706. }
  2707. bool found(APFloat &Value, QualType SubobjType) {
  2708. if (!checkConst(SubobjType))
  2709. return false;
  2710. Value = NewVal.getFloat();
  2711. return true;
  2712. }
  2713. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  2714. llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
  2715. }
  2716. };
  2717. } // end anonymous namespace
  2718. const AccessKinds ModifySubobjectHandler::AccessKind;
  2719. /// Update the designated sub-object of an rvalue to the given value.
  2720. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2721. const CompleteObject &Obj,
  2722. const SubobjectDesignator &Sub,
  2723. APValue &NewVal) {
  2724. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2725. return findSubobject(Info, E, Obj, Sub, Handler);
  2726. }
  2727. /// Find the position where two subobject designators diverge, or equivalently
  2728. /// the length of the common initial subsequence.
  2729. static unsigned FindDesignatorMismatch(QualType ObjType,
  2730. const SubobjectDesignator &A,
  2731. const SubobjectDesignator &B,
  2732. bool &WasArrayIndex) {
  2733. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2734. for (/**/; I != N; ++I) {
  2735. if (!ObjType.isNull() &&
  2736. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2737. // Next subobject is an array element.
  2738. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  2739. WasArrayIndex = true;
  2740. return I;
  2741. }
  2742. if (ObjType->isAnyComplexType())
  2743. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2744. else
  2745. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2746. } else {
  2747. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  2748. WasArrayIndex = false;
  2749. return I;
  2750. }
  2751. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2752. // Next subobject is a field.
  2753. ObjType = FD->getType();
  2754. else
  2755. // Next subobject is a base class.
  2756. ObjType = QualType();
  2757. }
  2758. }
  2759. WasArrayIndex = false;
  2760. return I;
  2761. }
  2762. /// Determine whether the given subobject designators refer to elements of the
  2763. /// same array object.
  2764. static bool AreElementsOfSameArray(QualType ObjType,
  2765. const SubobjectDesignator &A,
  2766. const SubobjectDesignator &B) {
  2767. if (A.Entries.size() != B.Entries.size())
  2768. return false;
  2769. bool IsArray = A.MostDerivedIsArrayElement;
  2770. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2771. // A is a subobject of the array element.
  2772. return false;
  2773. // If A (and B) designates an array element, the last entry will be the array
  2774. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2775. // of length 1' case, and the entire path must match.
  2776. bool WasArrayIndex;
  2777. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2778. return CommonLength >= A.Entries.size() - IsArray;
  2779. }
  2780. /// Find the complete object to which an LValue refers.
  2781. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2782. AccessKinds AK, const LValue &LVal,
  2783. QualType LValType) {
  2784. if (!LVal.Base) {
  2785. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2786. return CompleteObject();
  2787. }
  2788. CallStackFrame *Frame = nullptr;
  2789. if (LVal.getLValueCallIndex()) {
  2790. Frame = Info.getCallFrame(LVal.getLValueCallIndex());
  2791. if (!Frame) {
  2792. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2793. << AK << LVal.Base.is<const ValueDecl*>();
  2794. NoteLValueLocation(Info, LVal.Base);
  2795. return CompleteObject();
  2796. }
  2797. }
  2798. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2799. // is not a constant expression (even if the object is non-volatile). We also
  2800. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2801. // semantics.
  2802. if (LValType.isVolatileQualified()) {
  2803. if (Info.getLangOpts().CPlusPlus)
  2804. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2805. << AK << LValType;
  2806. else
  2807. Info.FFDiag(E);
  2808. return CompleteObject();
  2809. }
  2810. // Compute value storage location and type of base object.
  2811. APValue *BaseVal = nullptr;
  2812. QualType BaseType = getType(LVal.Base);
  2813. bool LifetimeStartedInEvaluation = Frame;
  2814. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2815. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2816. // In C++11, constexpr, non-volatile variables initialized with constant
  2817. // expressions are constant expressions too. Inside constexpr functions,
  2818. // parameters are constant expressions even if they're non-const.
  2819. // In C++1y, objects local to a constant expression (those with a Frame) are
  2820. // both readable and writable inside constant expressions.
  2821. // In C, such things can also be folded, although they are not ICEs.
  2822. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2823. if (VD) {
  2824. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2825. VD = VDef;
  2826. }
  2827. if (!VD || VD->isInvalidDecl()) {
  2828. Info.FFDiag(E);
  2829. return CompleteObject();
  2830. }
  2831. // Accesses of volatile-qualified objects are not allowed.
  2832. if (BaseType.isVolatileQualified()) {
  2833. if (Info.getLangOpts().CPlusPlus) {
  2834. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2835. << AK << 1 << VD;
  2836. Info.Note(VD->getLocation(), diag::note_declared_at);
  2837. } else {
  2838. Info.FFDiag(E);
  2839. }
  2840. return CompleteObject();
  2841. }
  2842. // Unless we're looking at a local variable or argument in a constexpr call,
  2843. // the variable we're reading must be const.
  2844. if (!Frame) {
  2845. if (Info.getLangOpts().CPlusPlus14 &&
  2846. VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
  2847. // OK, we can read and modify an object if we're in the process of
  2848. // evaluating its initializer, because its lifetime began in this
  2849. // evaluation.
  2850. } else if (AK != AK_Read) {
  2851. // All the remaining cases only permit reading.
  2852. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2853. return CompleteObject();
  2854. } else if (VD->isConstexpr()) {
  2855. // OK, we can read this variable.
  2856. } else if (BaseType->isIntegralOrEnumerationType()) {
  2857. // In OpenCL if a variable is in constant address space it is a const value.
  2858. if (!(BaseType.isConstQualified() ||
  2859. (Info.getLangOpts().OpenCL &&
  2860. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2861. if (Info.getLangOpts().CPlusPlus) {
  2862. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2863. Info.Note(VD->getLocation(), diag::note_declared_at);
  2864. } else {
  2865. Info.FFDiag(E);
  2866. }
  2867. return CompleteObject();
  2868. }
  2869. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2870. // We support folding of const floating-point types, in order to make
  2871. // static const data members of such types (supported as an extension)
  2872. // more useful.
  2873. if (Info.getLangOpts().CPlusPlus11) {
  2874. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2875. Info.Note(VD->getLocation(), diag::note_declared_at);
  2876. } else {
  2877. Info.CCEDiag(E);
  2878. }
  2879. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  2880. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  2881. // Keep evaluating to see what we can do.
  2882. } else {
  2883. // FIXME: Allow folding of values of any literal type in all languages.
  2884. if (Info.checkingPotentialConstantExpression() &&
  2885. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  2886. // The definition of this variable could be constexpr. We can't
  2887. // access it right now, but may be able to in future.
  2888. } else if (Info.getLangOpts().CPlusPlus11) {
  2889. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  2890. Info.Note(VD->getLocation(), diag::note_declared_at);
  2891. } else {
  2892. Info.FFDiag(E);
  2893. }
  2894. return CompleteObject();
  2895. }
  2896. }
  2897. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  2898. return CompleteObject();
  2899. } else {
  2900. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2901. if (!Frame) {
  2902. if (const MaterializeTemporaryExpr *MTE =
  2903. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  2904. assert(MTE->getStorageDuration() == SD_Static &&
  2905. "should have a frame for a non-global materialized temporary");
  2906. // Per C++1y [expr.const]p2:
  2907. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  2908. // - a [...] glvalue of integral or enumeration type that refers to
  2909. // a non-volatile const object [...]
  2910. // [...]
  2911. // - a [...] glvalue of literal type that refers to a non-volatile
  2912. // object whose lifetime began within the evaluation of e.
  2913. //
  2914. // C++11 misses the 'began within the evaluation of e' check and
  2915. // instead allows all temporaries, including things like:
  2916. // int &&r = 1;
  2917. // int x = ++r;
  2918. // constexpr int k = r;
  2919. // Therefore we use the C++14 rules in C++11 too.
  2920. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2921. const ValueDecl *ED = MTE->getExtendingDecl();
  2922. if (!(BaseType.isConstQualified() &&
  2923. BaseType->isIntegralOrEnumerationType()) &&
  2924. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  2925. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  2926. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  2927. return CompleteObject();
  2928. }
  2929. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  2930. assert(BaseVal && "got reference to unevaluated temporary");
  2931. LifetimeStartedInEvaluation = true;
  2932. } else {
  2933. Info.FFDiag(E);
  2934. return CompleteObject();
  2935. }
  2936. } else {
  2937. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  2938. assert(BaseVal && "missing value for temporary");
  2939. }
  2940. // Volatile temporary objects cannot be accessed in constant expressions.
  2941. if (BaseType.isVolatileQualified()) {
  2942. if (Info.getLangOpts().CPlusPlus) {
  2943. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2944. << AK << 0;
  2945. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  2946. } else {
  2947. Info.FFDiag(E);
  2948. }
  2949. return CompleteObject();
  2950. }
  2951. }
  2952. // During the construction of an object, it is not yet 'const'.
  2953. // FIXME: This doesn't do quite the right thing for const subobjects of the
  2954. // object under construction.
  2955. if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
  2956. LVal.getLValueCallIndex(),
  2957. LVal.getLValueVersion())) {
  2958. BaseType = Info.Ctx.getCanonicalType(BaseType);
  2959. BaseType.removeLocalConst();
  2960. LifetimeStartedInEvaluation = true;
  2961. }
  2962. // In C++14, we can't safely access any mutable state when we might be
  2963. // evaluating after an unmodeled side effect.
  2964. //
  2965. // FIXME: Not all local state is mutable. Allow local constant subobjects
  2966. // to be read here (but take care with 'mutable' fields).
  2967. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  2968. Info.EvalStatus.HasSideEffects) ||
  2969. (AK != AK_Read && Info.IsSpeculativelyEvaluating))
  2970. return CompleteObject();
  2971. return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
  2972. }
  2973. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  2974. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  2975. /// glvalue referred to by an entity of reference type.
  2976. ///
  2977. /// \param Info - Information about the ongoing evaluation.
  2978. /// \param Conv - The expression for which we are performing the conversion.
  2979. /// Used for diagnostics.
  2980. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  2981. /// case of a non-class type).
  2982. /// \param LVal - The glvalue on which we are attempting to perform this action.
  2983. /// \param RVal - The produced value will be placed here.
  2984. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2985. QualType Type,
  2986. const LValue &LVal, APValue &RVal) {
  2987. if (LVal.Designator.Invalid)
  2988. return false;
  2989. // Check for special cases where there is no existing APValue to look at.
  2990. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  2991. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  2992. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  2993. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  2994. // initializer until now for such expressions. Such an expression can't be
  2995. // an ICE in C, so this only matters for fold.
  2996. if (Type.isVolatileQualified()) {
  2997. Info.FFDiag(Conv);
  2998. return false;
  2999. }
  3000. APValue Lit;
  3001. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3002. return false;
  3003. CompleteObject LitObj(&Lit, Base->getType(), false);
  3004. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  3005. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3006. // We represent a string literal array as an lvalue pointing at the
  3007. // corresponding expression, rather than building an array of chars.
  3008. // FIXME: Support ObjCEncodeExpr, MakeStringConstant
  3009. APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  3010. CompleteObject StrObj(&Str, Base->getType(), false);
  3011. return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
  3012. }
  3013. }
  3014. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3015. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3016. }
  3017. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3018. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3019. QualType LValType, APValue &Val) {
  3020. if (LVal.Designator.Invalid)
  3021. return false;
  3022. if (!Info.getLangOpts().CPlusPlus14) {
  3023. Info.FFDiag(E);
  3024. return false;
  3025. }
  3026. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3027. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3028. }
  3029. namespace {
  3030. struct CompoundAssignSubobjectHandler {
  3031. EvalInfo &Info;
  3032. const Expr *E;
  3033. QualType PromotedLHSType;
  3034. BinaryOperatorKind Opcode;
  3035. const APValue &RHS;
  3036. static const AccessKinds AccessKind = AK_Assign;
  3037. typedef bool result_type;
  3038. bool checkConst(QualType QT) {
  3039. // Assigning to a const object has undefined behavior.
  3040. if (QT.isConstQualified()) {
  3041. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3042. return false;
  3043. }
  3044. return true;
  3045. }
  3046. bool failed() { return false; }
  3047. bool found(APValue &Subobj, QualType SubobjType) {
  3048. switch (Subobj.getKind()) {
  3049. case APValue::Int:
  3050. return found(Subobj.getInt(), SubobjType);
  3051. case APValue::Float:
  3052. return found(Subobj.getFloat(), SubobjType);
  3053. case APValue::ComplexInt:
  3054. case APValue::ComplexFloat:
  3055. // FIXME: Implement complex compound assignment.
  3056. Info.FFDiag(E);
  3057. return false;
  3058. case APValue::LValue:
  3059. return foundPointer(Subobj, SubobjType);
  3060. default:
  3061. // FIXME: can this happen?
  3062. Info.FFDiag(E);
  3063. return false;
  3064. }
  3065. }
  3066. bool found(APSInt &Value, QualType SubobjType) {
  3067. if (!checkConst(SubobjType))
  3068. return false;
  3069. if (!SubobjType->isIntegerType() || !RHS.isInt()) {
  3070. // We don't support compound assignment on integer-cast-to-pointer
  3071. // values.
  3072. Info.FFDiag(E);
  3073. return false;
  3074. }
  3075. APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
  3076. SubobjType, Value);
  3077. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3078. return false;
  3079. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3080. return true;
  3081. }
  3082. bool found(APFloat &Value, QualType SubobjType) {
  3083. return checkConst(SubobjType) &&
  3084. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3085. Value) &&
  3086. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3087. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3088. }
  3089. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3090. if (!checkConst(SubobjType))
  3091. return false;
  3092. QualType PointeeType;
  3093. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3094. PointeeType = PT->getPointeeType();
  3095. if (PointeeType.isNull() || !RHS.isInt() ||
  3096. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3097. Info.FFDiag(E);
  3098. return false;
  3099. }
  3100. APSInt Offset = RHS.getInt();
  3101. if (Opcode == BO_Sub)
  3102. negateAsSigned(Offset);
  3103. LValue LVal;
  3104. LVal.setFrom(Info.Ctx, Subobj);
  3105. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3106. return false;
  3107. LVal.moveInto(Subobj);
  3108. return true;
  3109. }
  3110. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3111. llvm_unreachable("shouldn't encounter string elements here");
  3112. }
  3113. };
  3114. } // end anonymous namespace
  3115. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3116. /// Perform a compound assignment of LVal <op>= RVal.
  3117. static bool handleCompoundAssignment(
  3118. EvalInfo &Info, const Expr *E,
  3119. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3120. BinaryOperatorKind Opcode, const APValue &RVal) {
  3121. if (LVal.Designator.Invalid)
  3122. return false;
  3123. if (!Info.getLangOpts().CPlusPlus14) {
  3124. Info.FFDiag(E);
  3125. return false;
  3126. }
  3127. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3128. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3129. RVal };
  3130. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3131. }
  3132. namespace {
  3133. struct IncDecSubobjectHandler {
  3134. EvalInfo &Info;
  3135. const UnaryOperator *E;
  3136. AccessKinds AccessKind;
  3137. APValue *Old;
  3138. typedef bool result_type;
  3139. bool checkConst(QualType QT) {
  3140. // Assigning to a const object has undefined behavior.
  3141. if (QT.isConstQualified()) {
  3142. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3143. return false;
  3144. }
  3145. return true;
  3146. }
  3147. bool failed() { return false; }
  3148. bool found(APValue &Subobj, QualType SubobjType) {
  3149. // Stash the old value. Also clear Old, so we don't clobber it later
  3150. // if we're post-incrementing a complex.
  3151. if (Old) {
  3152. *Old = Subobj;
  3153. Old = nullptr;
  3154. }
  3155. switch (Subobj.getKind()) {
  3156. case APValue::Int:
  3157. return found(Subobj.getInt(), SubobjType);
  3158. case APValue::Float:
  3159. return found(Subobj.getFloat(), SubobjType);
  3160. case APValue::ComplexInt:
  3161. return found(Subobj.getComplexIntReal(),
  3162. SubobjType->castAs<ComplexType>()->getElementType()
  3163. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3164. case APValue::ComplexFloat:
  3165. return found(Subobj.getComplexFloatReal(),
  3166. SubobjType->castAs<ComplexType>()->getElementType()
  3167. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3168. case APValue::LValue:
  3169. return foundPointer(Subobj, SubobjType);
  3170. default:
  3171. // FIXME: can this happen?
  3172. Info.FFDiag(E);
  3173. return false;
  3174. }
  3175. }
  3176. bool found(APSInt &Value, QualType SubobjType) {
  3177. if (!checkConst(SubobjType))
  3178. return false;
  3179. if (!SubobjType->isIntegerType()) {
  3180. // We don't support increment / decrement on integer-cast-to-pointer
  3181. // values.
  3182. Info.FFDiag(E);
  3183. return false;
  3184. }
  3185. if (Old) *Old = APValue(Value);
  3186. // bool arithmetic promotes to int, and the conversion back to bool
  3187. // doesn't reduce mod 2^n, so special-case it.
  3188. if (SubobjType->isBooleanType()) {
  3189. if (AccessKind == AK_Increment)
  3190. Value = 1;
  3191. else
  3192. Value = !Value;
  3193. return true;
  3194. }
  3195. bool WasNegative = Value.isNegative();
  3196. if (AccessKind == AK_Increment) {
  3197. ++Value;
  3198. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3199. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3200. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3201. }
  3202. } else {
  3203. --Value;
  3204. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3205. unsigned BitWidth = Value.getBitWidth();
  3206. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3207. ActualValue.setBit(BitWidth);
  3208. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3209. }
  3210. }
  3211. return true;
  3212. }
  3213. bool found(APFloat &Value, QualType SubobjType) {
  3214. if (!checkConst(SubobjType))
  3215. return false;
  3216. if (Old) *Old = APValue(Value);
  3217. APFloat One(Value.getSemantics(), 1);
  3218. if (AccessKind == AK_Increment)
  3219. Value.add(One, APFloat::rmNearestTiesToEven);
  3220. else
  3221. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3222. return true;
  3223. }
  3224. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3225. if (!checkConst(SubobjType))
  3226. return false;
  3227. QualType PointeeType;
  3228. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3229. PointeeType = PT->getPointeeType();
  3230. else {
  3231. Info.FFDiag(E);
  3232. return false;
  3233. }
  3234. LValue LVal;
  3235. LVal.setFrom(Info.Ctx, Subobj);
  3236. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3237. AccessKind == AK_Increment ? 1 : -1))
  3238. return false;
  3239. LVal.moveInto(Subobj);
  3240. return true;
  3241. }
  3242. bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
  3243. llvm_unreachable("shouldn't encounter string elements here");
  3244. }
  3245. };
  3246. } // end anonymous namespace
  3247. /// Perform an increment or decrement on LVal.
  3248. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3249. QualType LValType, bool IsIncrement, APValue *Old) {
  3250. if (LVal.Designator.Invalid)
  3251. return false;
  3252. if (!Info.getLangOpts().CPlusPlus14) {
  3253. Info.FFDiag(E);
  3254. return false;
  3255. }
  3256. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3257. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3258. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3259. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3260. }
  3261. /// Build an lvalue for the object argument of a member function call.
  3262. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3263. LValue &This) {
  3264. if (Object->getType()->isPointerType())
  3265. return EvaluatePointer(Object, This, Info);
  3266. if (Object->isGLValue())
  3267. return EvaluateLValue(Object, This, Info);
  3268. if (Object->getType()->isLiteralType(Info.Ctx))
  3269. return EvaluateTemporary(Object, This, Info);
  3270. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3271. return false;
  3272. }
  3273. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3274. /// lvalue referring to the result.
  3275. ///
  3276. /// \param Info - Information about the ongoing evaluation.
  3277. /// \param LV - An lvalue referring to the base of the member pointer.
  3278. /// \param RHS - The member pointer expression.
  3279. /// \param IncludeMember - Specifies whether the member itself is included in
  3280. /// the resulting LValue subobject designator. This is not possible when
  3281. /// creating a bound member function.
  3282. /// \return The field or method declaration to which the member pointer refers,
  3283. /// or 0 if evaluation fails.
  3284. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3285. QualType LVType,
  3286. LValue &LV,
  3287. const Expr *RHS,
  3288. bool IncludeMember = true) {
  3289. MemberPtr MemPtr;
  3290. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3291. return nullptr;
  3292. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3293. // member value, the behavior is undefined.
  3294. if (!MemPtr.getDecl()) {
  3295. // FIXME: Specific diagnostic.
  3296. Info.FFDiag(RHS);
  3297. return nullptr;
  3298. }
  3299. if (MemPtr.isDerivedMember()) {
  3300. // This is a member of some derived class. Truncate LV appropriately.
  3301. // The end of the derived-to-base path for the base object must match the
  3302. // derived-to-base path for the member pointer.
  3303. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3304. LV.Designator.Entries.size()) {
  3305. Info.FFDiag(RHS);
  3306. return nullptr;
  3307. }
  3308. unsigned PathLengthToMember =
  3309. LV.Designator.Entries.size() - MemPtr.Path.size();
  3310. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3311. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3312. LV.Designator.Entries[PathLengthToMember + I]);
  3313. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3314. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3315. Info.FFDiag(RHS);
  3316. return nullptr;
  3317. }
  3318. }
  3319. // Truncate the lvalue to the appropriate derived class.
  3320. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3321. PathLengthToMember))
  3322. return nullptr;
  3323. } else if (!MemPtr.Path.empty()) {
  3324. // Extend the LValue path with the member pointer's path.
  3325. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3326. MemPtr.Path.size() + IncludeMember);
  3327. // Walk down to the appropriate base class.
  3328. if (const PointerType *PT = LVType->getAs<PointerType>())
  3329. LVType = PT->getPointeeType();
  3330. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3331. assert(RD && "member pointer access on non-class-type expression");
  3332. // The first class in the path is that of the lvalue.
  3333. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3334. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3335. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3336. return nullptr;
  3337. RD = Base;
  3338. }
  3339. // Finally cast to the class containing the member.
  3340. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3341. MemPtr.getContainingRecord()))
  3342. return nullptr;
  3343. }
  3344. // Add the member. Note that we cannot build bound member functions here.
  3345. if (IncludeMember) {
  3346. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3347. if (!HandleLValueMember(Info, RHS, LV, FD))
  3348. return nullptr;
  3349. } else if (const IndirectFieldDecl *IFD =
  3350. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3351. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3352. return nullptr;
  3353. } else {
  3354. llvm_unreachable("can't construct reference to bound member function");
  3355. }
  3356. }
  3357. return MemPtr.getDecl();
  3358. }
  3359. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3360. const BinaryOperator *BO,
  3361. LValue &LV,
  3362. bool IncludeMember = true) {
  3363. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3364. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3365. if (Info.noteFailure()) {
  3366. MemberPtr MemPtr;
  3367. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3368. }
  3369. return nullptr;
  3370. }
  3371. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3372. BO->getRHS(), IncludeMember);
  3373. }
  3374. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3375. /// the provided lvalue, which currently refers to the base object.
  3376. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3377. LValue &Result) {
  3378. SubobjectDesignator &D = Result.Designator;
  3379. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3380. return false;
  3381. QualType TargetQT = E->getType();
  3382. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3383. TargetQT = PT->getPointeeType();
  3384. // Check this cast lands within the final derived-to-base subobject path.
  3385. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3386. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3387. << D.MostDerivedType << TargetQT;
  3388. return false;
  3389. }
  3390. // Check the type of the final cast. We don't need to check the path,
  3391. // since a cast can only be formed if the path is unique.
  3392. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3393. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3394. const CXXRecordDecl *FinalType;
  3395. if (NewEntriesSize == D.MostDerivedPathLength)
  3396. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3397. else
  3398. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3399. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3400. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3401. << D.MostDerivedType << TargetQT;
  3402. return false;
  3403. }
  3404. // Truncate the lvalue to the appropriate derived class.
  3405. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3406. }
  3407. namespace {
  3408. enum EvalStmtResult {
  3409. /// Evaluation failed.
  3410. ESR_Failed,
  3411. /// Hit a 'return' statement.
  3412. ESR_Returned,
  3413. /// Evaluation succeeded.
  3414. ESR_Succeeded,
  3415. /// Hit a 'continue' statement.
  3416. ESR_Continue,
  3417. /// Hit a 'break' statement.
  3418. ESR_Break,
  3419. /// Still scanning for 'case' or 'default' statement.
  3420. ESR_CaseNotFound
  3421. };
  3422. }
  3423. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3424. // We don't need to evaluate the initializer for a static local.
  3425. if (!VD->hasLocalStorage())
  3426. return true;
  3427. LValue Result;
  3428. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3429. const Expr *InitE = VD->getInit();
  3430. if (!InitE) {
  3431. Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
  3432. << false << VD->getType();
  3433. Val = APValue();
  3434. return false;
  3435. }
  3436. if (InitE->isValueDependent())
  3437. return false;
  3438. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3439. // Wipe out any partially-computed value, to allow tracking that this
  3440. // evaluation failed.
  3441. Val = APValue();
  3442. return false;
  3443. }
  3444. return true;
  3445. }
  3446. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3447. bool OK = true;
  3448. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3449. OK &= EvaluateVarDecl(Info, VD);
  3450. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3451. for (auto *BD : DD->bindings())
  3452. if (auto *VD = BD->getHoldingVar())
  3453. OK &= EvaluateDecl(Info, VD);
  3454. return OK;
  3455. }
  3456. /// Evaluate a condition (either a variable declaration or an expression).
  3457. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3458. const Expr *Cond, bool &Result) {
  3459. FullExpressionRAII Scope(Info);
  3460. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3461. return false;
  3462. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3463. }
  3464. namespace {
  3465. /// A location where the result (returned value) of evaluating a
  3466. /// statement should be stored.
  3467. struct StmtResult {
  3468. /// The APValue that should be filled in with the returned value.
  3469. APValue &Value;
  3470. /// The location containing the result, if any (used to support RVO).
  3471. const LValue *Slot;
  3472. };
  3473. struct TempVersionRAII {
  3474. CallStackFrame &Frame;
  3475. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3476. Frame.pushTempVersion();
  3477. }
  3478. ~TempVersionRAII() {
  3479. Frame.popTempVersion();
  3480. }
  3481. };
  3482. }
  3483. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3484. const Stmt *S,
  3485. const SwitchCase *SC = nullptr);
  3486. /// Evaluate the body of a loop, and translate the result as appropriate.
  3487. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3488. const Stmt *Body,
  3489. const SwitchCase *Case = nullptr) {
  3490. BlockScopeRAII Scope(Info);
  3491. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3492. case ESR_Break:
  3493. return ESR_Succeeded;
  3494. case ESR_Succeeded:
  3495. case ESR_Continue:
  3496. return ESR_Continue;
  3497. case ESR_Failed:
  3498. case ESR_Returned:
  3499. case ESR_CaseNotFound:
  3500. return ESR;
  3501. }
  3502. llvm_unreachable("Invalid EvalStmtResult!");
  3503. }
  3504. /// Evaluate a switch statement.
  3505. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3506. const SwitchStmt *SS) {
  3507. BlockScopeRAII Scope(Info);
  3508. // Evaluate the switch condition.
  3509. APSInt Value;
  3510. {
  3511. FullExpressionRAII Scope(Info);
  3512. if (const Stmt *Init = SS->getInit()) {
  3513. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3514. if (ESR != ESR_Succeeded)
  3515. return ESR;
  3516. }
  3517. if (SS->getConditionVariable() &&
  3518. !EvaluateDecl(Info, SS->getConditionVariable()))
  3519. return ESR_Failed;
  3520. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3521. return ESR_Failed;
  3522. }
  3523. // Find the switch case corresponding to the value of the condition.
  3524. // FIXME: Cache this lookup.
  3525. const SwitchCase *Found = nullptr;
  3526. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3527. SC = SC->getNextSwitchCase()) {
  3528. if (isa<DefaultStmt>(SC)) {
  3529. Found = SC;
  3530. continue;
  3531. }
  3532. const CaseStmt *CS = cast<CaseStmt>(SC);
  3533. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3534. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3535. : LHS;
  3536. if (LHS <= Value && Value <= RHS) {
  3537. Found = SC;
  3538. break;
  3539. }
  3540. }
  3541. if (!Found)
  3542. return ESR_Succeeded;
  3543. // Search the switch body for the switch case and evaluate it from there.
  3544. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3545. case ESR_Break:
  3546. return ESR_Succeeded;
  3547. case ESR_Succeeded:
  3548. case ESR_Continue:
  3549. case ESR_Failed:
  3550. case ESR_Returned:
  3551. return ESR;
  3552. case ESR_CaseNotFound:
  3553. // This can only happen if the switch case is nested within a statement
  3554. // expression. We have no intention of supporting that.
  3555. Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
  3556. return ESR_Failed;
  3557. }
  3558. llvm_unreachable("Invalid EvalStmtResult!");
  3559. }
  3560. // Evaluate a statement.
  3561. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3562. const Stmt *S, const SwitchCase *Case) {
  3563. if (!Info.nextStep(S))
  3564. return ESR_Failed;
  3565. // If we're hunting down a 'case' or 'default' label, recurse through
  3566. // substatements until we hit the label.
  3567. if (Case) {
  3568. // FIXME: We don't start the lifetime of objects whose initialization we
  3569. // jump over. However, such objects must be of class type with a trivial
  3570. // default constructor that initialize all subobjects, so must be empty,
  3571. // so this almost never matters.
  3572. switch (S->getStmtClass()) {
  3573. case Stmt::CompoundStmtClass:
  3574. // FIXME: Precompute which substatement of a compound statement we
  3575. // would jump to, and go straight there rather than performing a
  3576. // linear scan each time.
  3577. case Stmt::LabelStmtClass:
  3578. case Stmt::AttributedStmtClass:
  3579. case Stmt::DoStmtClass:
  3580. break;
  3581. case Stmt::CaseStmtClass:
  3582. case Stmt::DefaultStmtClass:
  3583. if (Case == S)
  3584. Case = nullptr;
  3585. break;
  3586. case Stmt::IfStmtClass: {
  3587. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3588. // straight there rather than scanning both sides.
  3589. const IfStmt *IS = cast<IfStmt>(S);
  3590. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3591. // preceded by our switch label.
  3592. BlockScopeRAII Scope(Info);
  3593. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3594. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3595. return ESR;
  3596. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3597. }
  3598. case Stmt::WhileStmtClass: {
  3599. EvalStmtResult ESR =
  3600. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3601. if (ESR != ESR_Continue)
  3602. return ESR;
  3603. break;
  3604. }
  3605. case Stmt::ForStmtClass: {
  3606. const ForStmt *FS = cast<ForStmt>(S);
  3607. EvalStmtResult ESR =
  3608. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3609. if (ESR != ESR_Continue)
  3610. return ESR;
  3611. if (FS->getInc()) {
  3612. FullExpressionRAII IncScope(Info);
  3613. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3614. return ESR_Failed;
  3615. }
  3616. break;
  3617. }
  3618. case Stmt::DeclStmtClass:
  3619. // FIXME: If the variable has initialization that can't be jumped over,
  3620. // bail out of any immediately-surrounding compound-statement too.
  3621. default:
  3622. return ESR_CaseNotFound;
  3623. }
  3624. }
  3625. switch (S->getStmtClass()) {
  3626. default:
  3627. if (const Expr *E = dyn_cast<Expr>(S)) {
  3628. // Don't bother evaluating beyond an expression-statement which couldn't
  3629. // be evaluated.
  3630. FullExpressionRAII Scope(Info);
  3631. if (!EvaluateIgnoredValue(Info, E))
  3632. return ESR_Failed;
  3633. return ESR_Succeeded;
  3634. }
  3635. Info.FFDiag(S->getLocStart());
  3636. return ESR_Failed;
  3637. case Stmt::NullStmtClass:
  3638. return ESR_Succeeded;
  3639. case Stmt::DeclStmtClass: {
  3640. const DeclStmt *DS = cast<DeclStmt>(S);
  3641. for (const auto *DclIt : DS->decls()) {
  3642. // Each declaration initialization is its own full-expression.
  3643. // FIXME: This isn't quite right; if we're performing aggregate
  3644. // initialization, each braced subexpression is its own full-expression.
  3645. FullExpressionRAII Scope(Info);
  3646. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3647. return ESR_Failed;
  3648. }
  3649. return ESR_Succeeded;
  3650. }
  3651. case Stmt::ReturnStmtClass: {
  3652. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3653. FullExpressionRAII Scope(Info);
  3654. if (RetExpr &&
  3655. !(Result.Slot
  3656. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3657. : Evaluate(Result.Value, Info, RetExpr)))
  3658. return ESR_Failed;
  3659. return ESR_Returned;
  3660. }
  3661. case Stmt::CompoundStmtClass: {
  3662. BlockScopeRAII Scope(Info);
  3663. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3664. for (const auto *BI : CS->body()) {
  3665. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3666. if (ESR == ESR_Succeeded)
  3667. Case = nullptr;
  3668. else if (ESR != ESR_CaseNotFound)
  3669. return ESR;
  3670. }
  3671. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3672. }
  3673. case Stmt::IfStmtClass: {
  3674. const IfStmt *IS = cast<IfStmt>(S);
  3675. // Evaluate the condition, as either a var decl or as an expression.
  3676. BlockScopeRAII Scope(Info);
  3677. if (const Stmt *Init = IS->getInit()) {
  3678. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3679. if (ESR != ESR_Succeeded)
  3680. return ESR;
  3681. }
  3682. bool Cond;
  3683. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3684. return ESR_Failed;
  3685. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3686. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3687. if (ESR != ESR_Succeeded)
  3688. return ESR;
  3689. }
  3690. return ESR_Succeeded;
  3691. }
  3692. case Stmt::WhileStmtClass: {
  3693. const WhileStmt *WS = cast<WhileStmt>(S);
  3694. while (true) {
  3695. BlockScopeRAII Scope(Info);
  3696. bool Continue;
  3697. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3698. Continue))
  3699. return ESR_Failed;
  3700. if (!Continue)
  3701. break;
  3702. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3703. if (ESR != ESR_Continue)
  3704. return ESR;
  3705. }
  3706. return ESR_Succeeded;
  3707. }
  3708. case Stmt::DoStmtClass: {
  3709. const DoStmt *DS = cast<DoStmt>(S);
  3710. bool Continue;
  3711. do {
  3712. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3713. if (ESR != ESR_Continue)
  3714. return ESR;
  3715. Case = nullptr;
  3716. FullExpressionRAII CondScope(Info);
  3717. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3718. return ESR_Failed;
  3719. } while (Continue);
  3720. return ESR_Succeeded;
  3721. }
  3722. case Stmt::ForStmtClass: {
  3723. const ForStmt *FS = cast<ForStmt>(S);
  3724. BlockScopeRAII Scope(Info);
  3725. if (FS->getInit()) {
  3726. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3727. if (ESR != ESR_Succeeded)
  3728. return ESR;
  3729. }
  3730. while (true) {
  3731. BlockScopeRAII Scope(Info);
  3732. bool Continue = true;
  3733. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3734. FS->getCond(), Continue))
  3735. return ESR_Failed;
  3736. if (!Continue)
  3737. break;
  3738. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3739. if (ESR != ESR_Continue)
  3740. return ESR;
  3741. if (FS->getInc()) {
  3742. FullExpressionRAII IncScope(Info);
  3743. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3744. return ESR_Failed;
  3745. }
  3746. }
  3747. return ESR_Succeeded;
  3748. }
  3749. case Stmt::CXXForRangeStmtClass: {
  3750. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3751. BlockScopeRAII Scope(Info);
  3752. // Initialize the __range variable.
  3753. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3754. if (ESR != ESR_Succeeded)
  3755. return ESR;
  3756. // Create the __begin and __end iterators.
  3757. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3758. if (ESR != ESR_Succeeded)
  3759. return ESR;
  3760. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3761. if (ESR != ESR_Succeeded)
  3762. return ESR;
  3763. while (true) {
  3764. // Condition: __begin != __end.
  3765. {
  3766. bool Continue = true;
  3767. FullExpressionRAII CondExpr(Info);
  3768. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3769. return ESR_Failed;
  3770. if (!Continue)
  3771. break;
  3772. }
  3773. // User's variable declaration, initialized by *__begin.
  3774. BlockScopeRAII InnerScope(Info);
  3775. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3776. if (ESR != ESR_Succeeded)
  3777. return ESR;
  3778. // Loop body.
  3779. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3780. if (ESR != ESR_Continue)
  3781. return ESR;
  3782. // Increment: ++__begin
  3783. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3784. return ESR_Failed;
  3785. }
  3786. return ESR_Succeeded;
  3787. }
  3788. case Stmt::SwitchStmtClass:
  3789. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3790. case Stmt::ContinueStmtClass:
  3791. return ESR_Continue;
  3792. case Stmt::BreakStmtClass:
  3793. return ESR_Break;
  3794. case Stmt::LabelStmtClass:
  3795. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3796. case Stmt::AttributedStmtClass:
  3797. // As a general principle, C++11 attributes can be ignored without
  3798. // any semantic impact.
  3799. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3800. Case);
  3801. case Stmt::CaseStmtClass:
  3802. case Stmt::DefaultStmtClass:
  3803. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3804. }
  3805. }
  3806. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3807. /// default constructor. If so, we'll fold it whether or not it's marked as
  3808. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3809. /// so we need special handling.
  3810. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3811. const CXXConstructorDecl *CD,
  3812. bool IsValueInitialization) {
  3813. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3814. return false;
  3815. // Value-initialization does not call a trivial default constructor, so such a
  3816. // call is a core constant expression whether or not the constructor is
  3817. // constexpr.
  3818. if (!CD->isConstexpr() && !IsValueInitialization) {
  3819. if (Info.getLangOpts().CPlusPlus11) {
  3820. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3821. // we should be much more explicit about why it's not constexpr.
  3822. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3823. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3824. Info.Note(CD->getLocation(), diag::note_declared_at);
  3825. } else {
  3826. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3827. }
  3828. }
  3829. return true;
  3830. }
  3831. /// CheckConstexprFunction - Check that a function can be called in a constant
  3832. /// expression.
  3833. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3834. const FunctionDecl *Declaration,
  3835. const FunctionDecl *Definition,
  3836. const Stmt *Body) {
  3837. // Potential constant expressions can contain calls to declared, but not yet
  3838. // defined, constexpr functions.
  3839. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3840. Declaration->isConstexpr())
  3841. return false;
  3842. // Bail out with no diagnostic if the function declaration itself is invalid.
  3843. // We will have produced a relevant diagnostic while parsing it.
  3844. if (Declaration->isInvalidDecl())
  3845. return false;
  3846. // Can we evaluate this function call?
  3847. if (Definition && Definition->isConstexpr() &&
  3848. !Definition->isInvalidDecl() && Body)
  3849. return true;
  3850. if (Info.getLangOpts().CPlusPlus11) {
  3851. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  3852. // If this function is not constexpr because it is an inherited
  3853. // non-constexpr constructor, diagnose that directly.
  3854. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  3855. if (CD && CD->isInheritingConstructor()) {
  3856. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  3857. if (!Inherited->isConstexpr())
  3858. DiagDecl = CD = Inherited;
  3859. }
  3860. // FIXME: If DiagDecl is an implicitly-declared special member function
  3861. // or an inheriting constructor, we should be much more explicit about why
  3862. // it's not constexpr.
  3863. if (CD && CD->isInheritingConstructor())
  3864. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  3865. << CD->getInheritedConstructor().getConstructor()->getParent();
  3866. else
  3867. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  3868. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  3869. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  3870. } else {
  3871. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3872. }
  3873. return false;
  3874. }
  3875. /// Determine if a class has any fields that might need to be copied by a
  3876. /// trivial copy or move operation.
  3877. static bool hasFields(const CXXRecordDecl *RD) {
  3878. if (!RD || RD->isEmpty())
  3879. return false;
  3880. for (auto *FD : RD->fields()) {
  3881. if (FD->isUnnamedBitfield())
  3882. continue;
  3883. return true;
  3884. }
  3885. for (auto &Base : RD->bases())
  3886. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  3887. return true;
  3888. return false;
  3889. }
  3890. namespace {
  3891. typedef SmallVector<APValue, 8> ArgVector;
  3892. }
  3893. /// EvaluateArgs - Evaluate the arguments to a function call.
  3894. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  3895. EvalInfo &Info) {
  3896. bool Success = true;
  3897. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  3898. I != E; ++I) {
  3899. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  3900. // If we're checking for a potential constant expression, evaluate all
  3901. // initializers even if some of them fail.
  3902. if (!Info.noteFailure())
  3903. return false;
  3904. Success = false;
  3905. }
  3906. }
  3907. return Success;
  3908. }
  3909. /// Evaluate a function call.
  3910. static bool HandleFunctionCall(SourceLocation CallLoc,
  3911. const FunctionDecl *Callee, const LValue *This,
  3912. ArrayRef<const Expr*> Args, const Stmt *Body,
  3913. EvalInfo &Info, APValue &Result,
  3914. const LValue *ResultSlot) {
  3915. ArgVector ArgValues(Args.size());
  3916. if (!EvaluateArgs(Args, ArgValues, Info))
  3917. return false;
  3918. if (!Info.CheckCallLimit(CallLoc))
  3919. return false;
  3920. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  3921. // For a trivial copy or move assignment, perform an APValue copy. This is
  3922. // essential for unions, where the operations performed by the assignment
  3923. // operator cannot be represented as statements.
  3924. //
  3925. // Skip this for non-union classes with no fields; in that case, the defaulted
  3926. // copy/move does not actually read the object.
  3927. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  3928. if (MD && MD->isDefaulted() &&
  3929. (MD->getParent()->isUnion() ||
  3930. (MD->isTrivial() && hasFields(MD->getParent())))) {
  3931. assert(This &&
  3932. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  3933. LValue RHS;
  3934. RHS.setFrom(Info.Ctx, ArgValues[0]);
  3935. APValue RHSValue;
  3936. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  3937. RHS, RHSValue))
  3938. return false;
  3939. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
  3940. RHSValue))
  3941. return false;
  3942. This->moveInto(Result);
  3943. return true;
  3944. } else if (MD && isLambdaCallOperator(MD)) {
  3945. // We're in a lambda; determine the lambda capture field maps unless we're
  3946. // just constexpr checking a lambda's call operator. constexpr checking is
  3947. // done before the captures have been added to the closure object (unless
  3948. // we're inferring constexpr-ness), so we don't have access to them in this
  3949. // case. But since we don't need the captures to constexpr check, we can
  3950. // just ignore them.
  3951. if (!Info.checkingPotentialConstantExpression())
  3952. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  3953. Frame.LambdaThisCaptureField);
  3954. }
  3955. StmtResult Ret = {Result, ResultSlot};
  3956. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  3957. if (ESR == ESR_Succeeded) {
  3958. if (Callee->getReturnType()->isVoidType())
  3959. return true;
  3960. Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
  3961. }
  3962. return ESR == ESR_Returned;
  3963. }
  3964. /// Evaluate a constructor call.
  3965. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  3966. APValue *ArgValues,
  3967. const CXXConstructorDecl *Definition,
  3968. EvalInfo &Info, APValue &Result) {
  3969. SourceLocation CallLoc = E->getExprLoc();
  3970. if (!Info.CheckCallLimit(CallLoc))
  3971. return false;
  3972. const CXXRecordDecl *RD = Definition->getParent();
  3973. if (RD->getNumVBases()) {
  3974. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  3975. return false;
  3976. }
  3977. EvalInfo::EvaluatingConstructorRAII EvalObj(
  3978. Info, {This.getLValueBase(),
  3979. {This.getLValueCallIndex(), This.getLValueVersion()}});
  3980. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  3981. // FIXME: Creating an APValue just to hold a nonexistent return value is
  3982. // wasteful.
  3983. APValue RetVal;
  3984. StmtResult Ret = {RetVal, nullptr};
  3985. // If it's a delegating constructor, delegate.
  3986. if (Definition->isDelegatingConstructor()) {
  3987. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  3988. {
  3989. FullExpressionRAII InitScope(Info);
  3990. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  3991. return false;
  3992. }
  3993. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  3994. }
  3995. // For a trivial copy or move constructor, perform an APValue copy. This is
  3996. // essential for unions (or classes with anonymous union members), where the
  3997. // operations performed by the constructor cannot be represented by
  3998. // ctor-initializers.
  3999. //
  4000. // Skip this for empty non-union classes; we should not perform an
  4001. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4002. // actually read them.
  4003. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4004. (Definition->getParent()->isUnion() ||
  4005. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4006. LValue RHS;
  4007. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4008. return handleLValueToRValueConversion(
  4009. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4010. RHS, Result);
  4011. }
  4012. // Reserve space for the struct members.
  4013. if (!RD->isUnion() && Result.isUninit())
  4014. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4015. std::distance(RD->field_begin(), RD->field_end()));
  4016. if (RD->isInvalidDecl()) return false;
  4017. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4018. // A scope for temporaries lifetime-extended by reference members.
  4019. BlockScopeRAII LifetimeExtendedScope(Info);
  4020. bool Success = true;
  4021. unsigned BasesSeen = 0;
  4022. #ifndef NDEBUG
  4023. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4024. #endif
  4025. for (const auto *I : Definition->inits()) {
  4026. LValue Subobject = This;
  4027. LValue SubobjectParent = This;
  4028. APValue *Value = &Result;
  4029. // Determine the subobject to initialize.
  4030. FieldDecl *FD = nullptr;
  4031. if (I->isBaseInitializer()) {
  4032. QualType BaseType(I->getBaseClass(), 0);
  4033. #ifndef NDEBUG
  4034. // Non-virtual base classes are initialized in the order in the class
  4035. // definition. We have already checked for virtual base classes.
  4036. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4037. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4038. "base class initializers not in expected order");
  4039. ++BaseIt;
  4040. #endif
  4041. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4042. BaseType->getAsCXXRecordDecl(), &Layout))
  4043. return false;
  4044. Value = &Result.getStructBase(BasesSeen++);
  4045. } else if ((FD = I->getMember())) {
  4046. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4047. return false;
  4048. if (RD->isUnion()) {
  4049. Result = APValue(FD);
  4050. Value = &Result.getUnionValue();
  4051. } else {
  4052. Value = &Result.getStructField(FD->getFieldIndex());
  4053. }
  4054. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4055. // Walk the indirect field decl's chain to find the object to initialize,
  4056. // and make sure we've initialized every step along it.
  4057. auto IndirectFieldChain = IFD->chain();
  4058. for (auto *C : IndirectFieldChain) {
  4059. FD = cast<FieldDecl>(C);
  4060. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4061. // Switch the union field if it differs. This happens if we had
  4062. // preceding zero-initialization, and we're now initializing a union
  4063. // subobject other than the first.
  4064. // FIXME: In this case, the values of the other subobjects are
  4065. // specified, since zero-initialization sets all padding bits to zero.
  4066. if (Value->isUninit() ||
  4067. (Value->isUnion() && Value->getUnionField() != FD)) {
  4068. if (CD->isUnion())
  4069. *Value = APValue(FD);
  4070. else
  4071. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4072. std::distance(CD->field_begin(), CD->field_end()));
  4073. }
  4074. // Store Subobject as its parent before updating it for the last element
  4075. // in the chain.
  4076. if (C == IndirectFieldChain.back())
  4077. SubobjectParent = Subobject;
  4078. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4079. return false;
  4080. if (CD->isUnion())
  4081. Value = &Value->getUnionValue();
  4082. else
  4083. Value = &Value->getStructField(FD->getFieldIndex());
  4084. }
  4085. } else {
  4086. llvm_unreachable("unknown base initializer kind");
  4087. }
  4088. // Need to override This for implicit field initializers as in this case
  4089. // This refers to innermost anonymous struct/union containing initializer,
  4090. // not to currently constructed class.
  4091. const Expr *Init = I->getInit();
  4092. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4093. isa<CXXDefaultInitExpr>(Init));
  4094. FullExpressionRAII InitScope(Info);
  4095. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4096. (FD && FD->isBitField() &&
  4097. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4098. // If we're checking for a potential constant expression, evaluate all
  4099. // initializers even if some of them fail.
  4100. if (!Info.noteFailure())
  4101. return false;
  4102. Success = false;
  4103. }
  4104. }
  4105. return Success &&
  4106. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4107. }
  4108. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4109. ArrayRef<const Expr*> Args,
  4110. const CXXConstructorDecl *Definition,
  4111. EvalInfo &Info, APValue &Result) {
  4112. ArgVector ArgValues(Args.size());
  4113. if (!EvaluateArgs(Args, ArgValues, Info))
  4114. return false;
  4115. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4116. Info, Result);
  4117. }
  4118. //===----------------------------------------------------------------------===//
  4119. // Generic Evaluation
  4120. //===----------------------------------------------------------------------===//
  4121. namespace {
  4122. template <class Derived>
  4123. class ExprEvaluatorBase
  4124. : public ConstStmtVisitor<Derived, bool> {
  4125. private:
  4126. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4127. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4128. return getDerived().Success(V, E);
  4129. }
  4130. bool DerivedZeroInitialization(const Expr *E) {
  4131. return getDerived().ZeroInitialization(E);
  4132. }
  4133. // Check whether a conditional operator with a non-constant condition is a
  4134. // potential constant expression. If neither arm is a potential constant
  4135. // expression, then the conditional operator is not either.
  4136. template<typename ConditionalOperator>
  4137. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4138. assert(Info.checkingPotentialConstantExpression());
  4139. // Speculatively evaluate both arms.
  4140. SmallVector<PartialDiagnosticAt, 8> Diag;
  4141. {
  4142. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4143. StmtVisitorTy::Visit(E->getFalseExpr());
  4144. if (Diag.empty())
  4145. return;
  4146. }
  4147. {
  4148. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4149. Diag.clear();
  4150. StmtVisitorTy::Visit(E->getTrueExpr());
  4151. if (Diag.empty())
  4152. return;
  4153. }
  4154. Error(E, diag::note_constexpr_conditional_never_const);
  4155. }
  4156. template<typename ConditionalOperator>
  4157. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4158. bool BoolResult;
  4159. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4160. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4161. CheckPotentialConstantConditional(E);
  4162. return false;
  4163. }
  4164. if (Info.noteFailure()) {
  4165. StmtVisitorTy::Visit(E->getTrueExpr());
  4166. StmtVisitorTy::Visit(E->getFalseExpr());
  4167. }
  4168. return false;
  4169. }
  4170. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4171. return StmtVisitorTy::Visit(EvalExpr);
  4172. }
  4173. protected:
  4174. EvalInfo &Info;
  4175. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4176. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4177. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4178. return Info.CCEDiag(E, D);
  4179. }
  4180. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4181. public:
  4182. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4183. EvalInfo &getEvalInfo() { return Info; }
  4184. /// Report an evaluation error. This should only be called when an error is
  4185. /// first discovered. When propagating an error, just return false.
  4186. bool Error(const Expr *E, diag::kind D) {
  4187. Info.FFDiag(E, D);
  4188. return false;
  4189. }
  4190. bool Error(const Expr *E) {
  4191. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4192. }
  4193. bool VisitStmt(const Stmt *) {
  4194. llvm_unreachable("Expression evaluator should not be called on stmts");
  4195. }
  4196. bool VisitExpr(const Expr *E) {
  4197. return Error(E);
  4198. }
  4199. bool VisitParenExpr(const ParenExpr *E)
  4200. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4201. bool VisitUnaryExtension(const UnaryOperator *E)
  4202. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4203. bool VisitUnaryPlus(const UnaryOperator *E)
  4204. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4205. bool VisitChooseExpr(const ChooseExpr *E)
  4206. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4207. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4208. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4209. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4210. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4211. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4212. TempVersionRAII RAII(*Info.CurrentCall);
  4213. return StmtVisitorTy::Visit(E->getExpr());
  4214. }
  4215. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4216. TempVersionRAII RAII(*Info.CurrentCall);
  4217. // The initializer may not have been parsed yet, or might be erroneous.
  4218. if (!E->getExpr())
  4219. return Error(E);
  4220. return StmtVisitorTy::Visit(E->getExpr());
  4221. }
  4222. // We cannot create any objects for which cleanups are required, so there is
  4223. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4224. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4225. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4226. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4227. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4228. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4229. }
  4230. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4231. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4232. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4233. }
  4234. bool VisitBinaryOperator(const BinaryOperator *E) {
  4235. switch (E->getOpcode()) {
  4236. default:
  4237. return Error(E);
  4238. case BO_Comma:
  4239. VisitIgnoredValue(E->getLHS());
  4240. return StmtVisitorTy::Visit(E->getRHS());
  4241. case BO_PtrMemD:
  4242. case BO_PtrMemI: {
  4243. LValue Obj;
  4244. if (!HandleMemberPointerAccess(Info, E, Obj))
  4245. return false;
  4246. APValue Result;
  4247. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4248. return false;
  4249. return DerivedSuccess(Result, E);
  4250. }
  4251. }
  4252. }
  4253. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4254. // Evaluate and cache the common expression. We treat it as a temporary,
  4255. // even though it's not quite the same thing.
  4256. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4257. Info, E->getCommon()))
  4258. return false;
  4259. return HandleConditionalOperator(E);
  4260. }
  4261. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4262. bool IsBcpCall = false;
  4263. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4264. // the result is a constant expression if it can be folded without
  4265. // side-effects. This is an important GNU extension. See GCC PR38377
  4266. // for discussion.
  4267. if (const CallExpr *CallCE =
  4268. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4269. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4270. IsBcpCall = true;
  4271. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4272. // constant expression; we can't check whether it's potentially foldable.
  4273. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4274. return false;
  4275. FoldConstant Fold(Info, IsBcpCall);
  4276. if (!HandleConditionalOperator(E)) {
  4277. Fold.keepDiagnostics();
  4278. return false;
  4279. }
  4280. return true;
  4281. }
  4282. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4283. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4284. return DerivedSuccess(*Value, E);
  4285. const Expr *Source = E->getSourceExpr();
  4286. if (!Source)
  4287. return Error(E);
  4288. if (Source == E) { // sanity checking.
  4289. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4290. return Error(E);
  4291. }
  4292. return StmtVisitorTy::Visit(Source);
  4293. }
  4294. bool VisitCallExpr(const CallExpr *E) {
  4295. APValue Result;
  4296. if (!handleCallExpr(E, Result, nullptr))
  4297. return false;
  4298. return DerivedSuccess(Result, E);
  4299. }
  4300. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4301. const LValue *ResultSlot) {
  4302. const Expr *Callee = E->getCallee()->IgnoreParens();
  4303. QualType CalleeType = Callee->getType();
  4304. const FunctionDecl *FD = nullptr;
  4305. LValue *This = nullptr, ThisVal;
  4306. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4307. bool HasQualifier = false;
  4308. // Extract function decl and 'this' pointer from the callee.
  4309. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4310. const ValueDecl *Member = nullptr;
  4311. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4312. // Explicit bound member calls, such as x.f() or p->g();
  4313. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4314. return false;
  4315. Member = ME->getMemberDecl();
  4316. This = &ThisVal;
  4317. HasQualifier = ME->hasQualifier();
  4318. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4319. // Indirect bound member calls ('.*' or '->*').
  4320. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  4321. if (!Member) return false;
  4322. This = &ThisVal;
  4323. } else
  4324. return Error(Callee);
  4325. FD = dyn_cast<FunctionDecl>(Member);
  4326. if (!FD)
  4327. return Error(Callee);
  4328. } else if (CalleeType->isFunctionPointerType()) {
  4329. LValue Call;
  4330. if (!EvaluatePointer(Callee, Call, Info))
  4331. return false;
  4332. if (!Call.getLValueOffset().isZero())
  4333. return Error(Callee);
  4334. FD = dyn_cast_or_null<FunctionDecl>(
  4335. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4336. if (!FD)
  4337. return Error(Callee);
  4338. // Don't call function pointers which have been cast to some other type.
  4339. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4340. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4341. CalleeType->getPointeeType(), FD->getType())) {
  4342. return Error(E);
  4343. }
  4344. // Overloaded operator calls to member functions are represented as normal
  4345. // calls with '*this' as the first argument.
  4346. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4347. if (MD && !MD->isStatic()) {
  4348. // FIXME: When selecting an implicit conversion for an overloaded
  4349. // operator delete, we sometimes try to evaluate calls to conversion
  4350. // operators without a 'this' parameter!
  4351. if (Args.empty())
  4352. return Error(E);
  4353. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4354. return false;
  4355. This = &ThisVal;
  4356. Args = Args.slice(1);
  4357. } else if (MD && MD->isLambdaStaticInvoker()) {
  4358. // Map the static invoker for the lambda back to the call operator.
  4359. // Conveniently, we don't have to slice out the 'this' argument (as is
  4360. // being done for the non-static case), since a static member function
  4361. // doesn't have an implicit argument passed in.
  4362. const CXXRecordDecl *ClosureClass = MD->getParent();
  4363. assert(
  4364. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  4365. "Number of captures must be zero for conversion to function-ptr");
  4366. const CXXMethodDecl *LambdaCallOp =
  4367. ClosureClass->getLambdaCallOperator();
  4368. // Set 'FD', the function that will be called below, to the call
  4369. // operator. If the closure object represents a generic lambda, find
  4370. // the corresponding specialization of the call operator.
  4371. if (ClosureClass->isGenericLambda()) {
  4372. assert(MD->isFunctionTemplateSpecialization() &&
  4373. "A generic lambda's static-invoker function must be a "
  4374. "template specialization");
  4375. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  4376. FunctionTemplateDecl *CallOpTemplate =
  4377. LambdaCallOp->getDescribedFunctionTemplate();
  4378. void *InsertPos = nullptr;
  4379. FunctionDecl *CorrespondingCallOpSpecialization =
  4380. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  4381. assert(CorrespondingCallOpSpecialization &&
  4382. "We must always have a function call operator specialization "
  4383. "that corresponds to our static invoker specialization");
  4384. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  4385. } else
  4386. FD = LambdaCallOp;
  4387. }
  4388. } else
  4389. return Error(E);
  4390. if (This && !This->checkSubobject(Info, E, CSK_This))
  4391. return false;
  4392. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  4393. // calls to such functions in constant expressions.
  4394. if (This && !HasQualifier &&
  4395. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  4396. return Error(E, diag::note_constexpr_virtual_call);
  4397. const FunctionDecl *Definition = nullptr;
  4398. Stmt *Body = FD->getBody(Definition);
  4399. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  4400. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  4401. Result, ResultSlot))
  4402. return false;
  4403. return true;
  4404. }
  4405. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4406. return StmtVisitorTy::Visit(E->getInitializer());
  4407. }
  4408. bool VisitInitListExpr(const InitListExpr *E) {
  4409. if (E->getNumInits() == 0)
  4410. return DerivedZeroInitialization(E);
  4411. if (E->getNumInits() == 1)
  4412. return StmtVisitorTy::Visit(E->getInit(0));
  4413. return Error(E);
  4414. }
  4415. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  4416. return DerivedZeroInitialization(E);
  4417. }
  4418. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  4419. return DerivedZeroInitialization(E);
  4420. }
  4421. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  4422. return DerivedZeroInitialization(E);
  4423. }
  4424. /// A member expression where the object is a prvalue is itself a prvalue.
  4425. bool VisitMemberExpr(const MemberExpr *E) {
  4426. assert(!E->isArrow() && "missing call to bound member function?");
  4427. APValue Val;
  4428. if (!Evaluate(Val, Info, E->getBase()))
  4429. return false;
  4430. QualType BaseTy = E->getBase()->getType();
  4431. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4432. if (!FD) return Error(E);
  4433. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4434. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4435. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4436. CompleteObject Obj(&Val, BaseTy, true);
  4437. SubobjectDesignator Designator(BaseTy);
  4438. Designator.addDeclUnchecked(FD);
  4439. APValue Result;
  4440. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4441. DerivedSuccess(Result, E);
  4442. }
  4443. bool VisitCastExpr(const CastExpr *E) {
  4444. switch (E->getCastKind()) {
  4445. default:
  4446. break;
  4447. case CK_AtomicToNonAtomic: {
  4448. APValue AtomicVal;
  4449. // This does not need to be done in place even for class/array types:
  4450. // atomic-to-non-atomic conversion implies copying the object
  4451. // representation.
  4452. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  4453. return false;
  4454. return DerivedSuccess(AtomicVal, E);
  4455. }
  4456. case CK_NoOp:
  4457. case CK_UserDefinedConversion:
  4458. return StmtVisitorTy::Visit(E->getSubExpr());
  4459. case CK_LValueToRValue: {
  4460. LValue LVal;
  4461. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4462. return false;
  4463. APValue RVal;
  4464. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4465. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4466. LVal, RVal))
  4467. return false;
  4468. return DerivedSuccess(RVal, E);
  4469. }
  4470. }
  4471. return Error(E);
  4472. }
  4473. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4474. return VisitUnaryPostIncDec(UO);
  4475. }
  4476. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4477. return VisitUnaryPostIncDec(UO);
  4478. }
  4479. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4480. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4481. return Error(UO);
  4482. LValue LVal;
  4483. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4484. return false;
  4485. APValue RVal;
  4486. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4487. UO->isIncrementOp(), &RVal))
  4488. return false;
  4489. return DerivedSuccess(RVal, UO);
  4490. }
  4491. bool VisitStmtExpr(const StmtExpr *E) {
  4492. // We will have checked the full-expressions inside the statement expression
  4493. // when they were completed, and don't need to check them again now.
  4494. if (Info.checkingForOverflow())
  4495. return Error(E);
  4496. BlockScopeRAII Scope(Info);
  4497. const CompoundStmt *CS = E->getSubStmt();
  4498. if (CS->body_empty())
  4499. return true;
  4500. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4501. BE = CS->body_end();
  4502. /**/; ++BI) {
  4503. if (BI + 1 == BE) {
  4504. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4505. if (!FinalExpr) {
  4506. Info.FFDiag((*BI)->getLocStart(),
  4507. diag::note_constexpr_stmt_expr_unsupported);
  4508. return false;
  4509. }
  4510. return this->Visit(FinalExpr);
  4511. }
  4512. APValue ReturnValue;
  4513. StmtResult Result = { ReturnValue, nullptr };
  4514. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4515. if (ESR != ESR_Succeeded) {
  4516. // FIXME: If the statement-expression terminated due to 'return',
  4517. // 'break', or 'continue', it would be nice to propagate that to
  4518. // the outer statement evaluation rather than bailing out.
  4519. if (ESR != ESR_Failed)
  4520. Info.FFDiag((*BI)->getLocStart(),
  4521. diag::note_constexpr_stmt_expr_unsupported);
  4522. return false;
  4523. }
  4524. }
  4525. llvm_unreachable("Return from function from the loop above.");
  4526. }
  4527. /// Visit a value which is evaluated, but whose value is ignored.
  4528. void VisitIgnoredValue(const Expr *E) {
  4529. EvaluateIgnoredValue(Info, E);
  4530. }
  4531. /// Potentially visit a MemberExpr's base expression.
  4532. void VisitIgnoredBaseExpression(const Expr *E) {
  4533. // While MSVC doesn't evaluate the base expression, it does diagnose the
  4534. // presence of side-effecting behavior.
  4535. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  4536. return;
  4537. VisitIgnoredValue(E);
  4538. }
  4539. };
  4540. } // namespace
  4541. //===----------------------------------------------------------------------===//
  4542. // Common base class for lvalue and temporary evaluation.
  4543. //===----------------------------------------------------------------------===//
  4544. namespace {
  4545. template<class Derived>
  4546. class LValueExprEvaluatorBase
  4547. : public ExprEvaluatorBase<Derived> {
  4548. protected:
  4549. LValue &Result;
  4550. bool InvalidBaseOK;
  4551. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  4552. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  4553. bool Success(APValue::LValueBase B) {
  4554. Result.set(B);
  4555. return true;
  4556. }
  4557. bool evaluatePointer(const Expr *E, LValue &Result) {
  4558. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  4559. }
  4560. public:
  4561. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  4562. : ExprEvaluatorBaseTy(Info), Result(Result),
  4563. InvalidBaseOK(InvalidBaseOK) {}
  4564. bool Success(const APValue &V, const Expr *E) {
  4565. Result.setFrom(this->Info.Ctx, V);
  4566. return true;
  4567. }
  4568. bool VisitMemberExpr(const MemberExpr *E) {
  4569. // Handle non-static data members.
  4570. QualType BaseTy;
  4571. bool EvalOK;
  4572. if (E->isArrow()) {
  4573. EvalOK = evaluatePointer(E->getBase(), Result);
  4574. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  4575. } else if (E->getBase()->isRValue()) {
  4576. assert(E->getBase()->getType()->isRecordType());
  4577. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  4578. BaseTy = E->getBase()->getType();
  4579. } else {
  4580. EvalOK = this->Visit(E->getBase());
  4581. BaseTy = E->getBase()->getType();
  4582. }
  4583. if (!EvalOK) {
  4584. if (!InvalidBaseOK)
  4585. return false;
  4586. Result.setInvalid(E);
  4587. return true;
  4588. }
  4589. const ValueDecl *MD = E->getMemberDecl();
  4590. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  4591. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4592. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4593. (void)BaseTy;
  4594. if (!HandleLValueMember(this->Info, E, Result, FD))
  4595. return false;
  4596. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  4597. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  4598. return false;
  4599. } else
  4600. return this->Error(E);
  4601. if (MD->getType()->isReferenceType()) {
  4602. APValue RefValue;
  4603. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  4604. RefValue))
  4605. return false;
  4606. return Success(RefValue, E);
  4607. }
  4608. return true;
  4609. }
  4610. bool VisitBinaryOperator(const BinaryOperator *E) {
  4611. switch (E->getOpcode()) {
  4612. default:
  4613. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4614. case BO_PtrMemD:
  4615. case BO_PtrMemI:
  4616. return HandleMemberPointerAccess(this->Info, E, Result);
  4617. }
  4618. }
  4619. bool VisitCastExpr(const CastExpr *E) {
  4620. switch (E->getCastKind()) {
  4621. default:
  4622. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4623. case CK_DerivedToBase:
  4624. case CK_UncheckedDerivedToBase:
  4625. if (!this->Visit(E->getSubExpr()))
  4626. return false;
  4627. // Now figure out the necessary offset to add to the base LV to get from
  4628. // the derived class to the base class.
  4629. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  4630. Result);
  4631. }
  4632. }
  4633. };
  4634. }
  4635. //===----------------------------------------------------------------------===//
  4636. // LValue Evaluation
  4637. //
  4638. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  4639. // function designators (in C), decl references to void objects (in C), and
  4640. // temporaries (if building with -Wno-address-of-temporary).
  4641. //
  4642. // LValue evaluation produces values comprising a base expression of one of the
  4643. // following types:
  4644. // - Declarations
  4645. // * VarDecl
  4646. // * FunctionDecl
  4647. // - Literals
  4648. // * CompoundLiteralExpr in C (and in global scope in C++)
  4649. // * StringLiteral
  4650. // * CXXTypeidExpr
  4651. // * PredefinedExpr
  4652. // * ObjCStringLiteralExpr
  4653. // * ObjCEncodeExpr
  4654. // * AddrLabelExpr
  4655. // * BlockExpr
  4656. // * CallExpr for a MakeStringConstant builtin
  4657. // - Locals and temporaries
  4658. // * MaterializeTemporaryExpr
  4659. // * Any Expr, with a CallIndex indicating the function in which the temporary
  4660. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  4661. // from the AST (FIXME).
  4662. // * A MaterializeTemporaryExpr that has static storage duration, with no
  4663. // CallIndex, for a lifetime-extended temporary.
  4664. // plus an offset in bytes.
  4665. //===----------------------------------------------------------------------===//
  4666. namespace {
  4667. class LValueExprEvaluator
  4668. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  4669. public:
  4670. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  4671. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  4672. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  4673. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  4674. bool VisitDeclRefExpr(const DeclRefExpr *E);
  4675. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  4676. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  4677. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  4678. bool VisitMemberExpr(const MemberExpr *E);
  4679. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  4680. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  4681. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  4682. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  4683. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  4684. bool VisitUnaryDeref(const UnaryOperator *E);
  4685. bool VisitUnaryReal(const UnaryOperator *E);
  4686. bool VisitUnaryImag(const UnaryOperator *E);
  4687. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  4688. return VisitUnaryPreIncDec(UO);
  4689. }
  4690. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  4691. return VisitUnaryPreIncDec(UO);
  4692. }
  4693. bool VisitBinAssign(const BinaryOperator *BO);
  4694. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  4695. bool VisitCastExpr(const CastExpr *E) {
  4696. switch (E->getCastKind()) {
  4697. default:
  4698. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  4699. case CK_LValueBitCast:
  4700. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4701. if (!Visit(E->getSubExpr()))
  4702. return false;
  4703. Result.Designator.setInvalid();
  4704. return true;
  4705. case CK_BaseToDerived:
  4706. if (!Visit(E->getSubExpr()))
  4707. return false;
  4708. return HandleBaseToDerivedCast(Info, E, Result);
  4709. }
  4710. }
  4711. };
  4712. } // end anonymous namespace
  4713. /// Evaluate an expression as an lvalue. This can be legitimately called on
  4714. /// expressions which are not glvalues, in three cases:
  4715. /// * function designators in C, and
  4716. /// * "extern void" objects
  4717. /// * @selector() expressions in Objective-C
  4718. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  4719. bool InvalidBaseOK) {
  4720. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  4721. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  4722. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  4723. }
  4724. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  4725. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  4726. return Success(FD);
  4727. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  4728. return VisitVarDecl(E, VD);
  4729. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  4730. return Visit(BD->getBinding());
  4731. return Error(E);
  4732. }
  4733. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  4734. // If we are within a lambda's call operator, check whether the 'VD' referred
  4735. // to within 'E' actually represents a lambda-capture that maps to a
  4736. // data-member/field within the closure object, and if so, evaluate to the
  4737. // field or what the field refers to.
  4738. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  4739. isa<DeclRefExpr>(E) &&
  4740. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  4741. // We don't always have a complete capture-map when checking or inferring if
  4742. // the function call operator meets the requirements of a constexpr function
  4743. // - but we don't need to evaluate the captures to determine constexprness
  4744. // (dcl.constexpr C++17).
  4745. if (Info.checkingPotentialConstantExpression())
  4746. return false;
  4747. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  4748. // Start with 'Result' referring to the complete closure object...
  4749. Result = *Info.CurrentCall->This;
  4750. // ... then update it to refer to the field of the closure object
  4751. // that represents the capture.
  4752. if (!HandleLValueMember(Info, E, Result, FD))
  4753. return false;
  4754. // And if the field is of reference type, update 'Result' to refer to what
  4755. // the field refers to.
  4756. if (FD->getType()->isReferenceType()) {
  4757. APValue RVal;
  4758. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  4759. RVal))
  4760. return false;
  4761. Result.setFrom(Info.Ctx, RVal);
  4762. }
  4763. return true;
  4764. }
  4765. }
  4766. CallStackFrame *Frame = nullptr;
  4767. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  4768. // Only if a local variable was declared in the function currently being
  4769. // evaluated, do we expect to be able to find its value in the current
  4770. // frame. (Otherwise it was likely declared in an enclosing context and
  4771. // could either have a valid evaluatable value (for e.g. a constexpr
  4772. // variable) or be ill-formed (and trigger an appropriate evaluation
  4773. // diagnostic)).
  4774. if (Info.CurrentCall->Callee &&
  4775. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  4776. Frame = Info.CurrentCall;
  4777. }
  4778. }
  4779. if (!VD->getType()->isReferenceType()) {
  4780. if (Frame) {
  4781. Result.set({VD, Frame->Index,
  4782. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  4783. return true;
  4784. }
  4785. return Success(VD);
  4786. }
  4787. APValue *V;
  4788. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  4789. return false;
  4790. if (V->isUninit()) {
  4791. if (!Info.checkingPotentialConstantExpression())
  4792. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  4793. return false;
  4794. }
  4795. return Success(*V, E);
  4796. }
  4797. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  4798. const MaterializeTemporaryExpr *E) {
  4799. // Walk through the expression to find the materialized temporary itself.
  4800. SmallVector<const Expr *, 2> CommaLHSs;
  4801. SmallVector<SubobjectAdjustment, 2> Adjustments;
  4802. const Expr *Inner = E->GetTemporaryExpr()->
  4803. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  4804. // If we passed any comma operators, evaluate their LHSs.
  4805. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  4806. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  4807. return false;
  4808. // A materialized temporary with static storage duration can appear within the
  4809. // result of a constant expression evaluation, so we need to preserve its
  4810. // value for use outside this evaluation.
  4811. APValue *Value;
  4812. if (E->getStorageDuration() == SD_Static) {
  4813. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  4814. *Value = APValue();
  4815. Result.set(E);
  4816. } else {
  4817. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  4818. *Info.CurrentCall);
  4819. }
  4820. QualType Type = Inner->getType();
  4821. // Materialize the temporary itself.
  4822. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  4823. (E->getStorageDuration() == SD_Static &&
  4824. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  4825. *Value = APValue();
  4826. return false;
  4827. }
  4828. // Adjust our lvalue to refer to the desired subobject.
  4829. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  4830. --I;
  4831. switch (Adjustments[I].Kind) {
  4832. case SubobjectAdjustment::DerivedToBaseAdjustment:
  4833. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  4834. Type, Result))
  4835. return false;
  4836. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  4837. break;
  4838. case SubobjectAdjustment::FieldAdjustment:
  4839. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  4840. return false;
  4841. Type = Adjustments[I].Field->getType();
  4842. break;
  4843. case SubobjectAdjustment::MemberPointerAdjustment:
  4844. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  4845. Adjustments[I].Ptr.RHS))
  4846. return false;
  4847. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  4848. break;
  4849. }
  4850. }
  4851. return true;
  4852. }
  4853. bool
  4854. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4855. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  4856. "lvalue compound literal in c++?");
  4857. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  4858. // only see this when folding in C, so there's no standard to follow here.
  4859. return Success(E);
  4860. }
  4861. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  4862. if (!E->isPotentiallyEvaluated())
  4863. return Success(E);
  4864. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  4865. << E->getExprOperand()->getType()
  4866. << E->getExprOperand()->getSourceRange();
  4867. return false;
  4868. }
  4869. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4870. return Success(E);
  4871. }
  4872. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  4873. // Handle static data members.
  4874. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  4875. VisitIgnoredBaseExpression(E->getBase());
  4876. return VisitVarDecl(E, VD);
  4877. }
  4878. // Handle static member functions.
  4879. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  4880. if (MD->isStatic()) {
  4881. VisitIgnoredBaseExpression(E->getBase());
  4882. return Success(MD);
  4883. }
  4884. }
  4885. // Handle non-static data members.
  4886. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  4887. }
  4888. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  4889. // FIXME: Deal with vectors as array subscript bases.
  4890. if (E->getBase()->getType()->isVectorType())
  4891. return Error(E);
  4892. bool Success = true;
  4893. if (!evaluatePointer(E->getBase(), Result)) {
  4894. if (!Info.noteFailure())
  4895. return false;
  4896. Success = false;
  4897. }
  4898. APSInt Index;
  4899. if (!EvaluateInteger(E->getIdx(), Index, Info))
  4900. return false;
  4901. return Success &&
  4902. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  4903. }
  4904. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  4905. return evaluatePointer(E->getSubExpr(), Result);
  4906. }
  4907. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4908. if (!Visit(E->getSubExpr()))
  4909. return false;
  4910. // __real is a no-op on scalar lvalues.
  4911. if (E->getSubExpr()->getType()->isAnyComplexType())
  4912. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  4913. return true;
  4914. }
  4915. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4916. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  4917. "lvalue __imag__ on scalar?");
  4918. if (!Visit(E->getSubExpr()))
  4919. return false;
  4920. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  4921. return true;
  4922. }
  4923. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  4924. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4925. return Error(UO);
  4926. if (!this->Visit(UO->getSubExpr()))
  4927. return false;
  4928. return handleIncDec(
  4929. this->Info, UO, Result, UO->getSubExpr()->getType(),
  4930. UO->isIncrementOp(), nullptr);
  4931. }
  4932. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  4933. const CompoundAssignOperator *CAO) {
  4934. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4935. return Error(CAO);
  4936. APValue RHS;
  4937. // The overall lvalue result is the result of evaluating the LHS.
  4938. if (!this->Visit(CAO->getLHS())) {
  4939. if (Info.noteFailure())
  4940. Evaluate(RHS, this->Info, CAO->getRHS());
  4941. return false;
  4942. }
  4943. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  4944. return false;
  4945. return handleCompoundAssignment(
  4946. this->Info, CAO,
  4947. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  4948. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  4949. }
  4950. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  4951. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4952. return Error(E);
  4953. APValue NewVal;
  4954. if (!this->Visit(E->getLHS())) {
  4955. if (Info.noteFailure())
  4956. Evaluate(NewVal, this->Info, E->getRHS());
  4957. return false;
  4958. }
  4959. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  4960. return false;
  4961. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  4962. NewVal);
  4963. }
  4964. //===----------------------------------------------------------------------===//
  4965. // Pointer Evaluation
  4966. //===----------------------------------------------------------------------===//
  4967. /// Attempts to compute the number of bytes available at the pointer
  4968. /// returned by a function with the alloc_size attribute. Returns true if we
  4969. /// were successful. Places an unsigned number into `Result`.
  4970. ///
  4971. /// This expects the given CallExpr to be a call to a function with an
  4972. /// alloc_size attribute.
  4973. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  4974. const CallExpr *Call,
  4975. llvm::APInt &Result) {
  4976. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  4977. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  4978. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  4979. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  4980. if (Call->getNumArgs() <= SizeArgNo)
  4981. return false;
  4982. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  4983. if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
  4984. return false;
  4985. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  4986. return false;
  4987. Into = Into.zextOrSelf(BitsInSizeT);
  4988. return true;
  4989. };
  4990. APSInt SizeOfElem;
  4991. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  4992. return false;
  4993. if (!AllocSize->getNumElemsParam().isValid()) {
  4994. Result = std::move(SizeOfElem);
  4995. return true;
  4996. }
  4997. APSInt NumberOfElems;
  4998. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  4999. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  5000. return false;
  5001. bool Overflow;
  5002. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  5003. if (Overflow)
  5004. return false;
  5005. Result = std::move(BytesAvailable);
  5006. return true;
  5007. }
  5008. /// Convenience function. LVal's base must be a call to an alloc_size
  5009. /// function.
  5010. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5011. const LValue &LVal,
  5012. llvm::APInt &Result) {
  5013. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  5014. "Can't get the size of a non alloc_size function");
  5015. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  5016. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  5017. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  5018. }
  5019. /// Attempts to evaluate the given LValueBase as the result of a call to
  5020. /// a function with the alloc_size attribute. If it was possible to do so, this
  5021. /// function will return true, make Result's Base point to said function call,
  5022. /// and mark Result's Base as invalid.
  5023. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  5024. LValue &Result) {
  5025. if (Base.isNull())
  5026. return false;
  5027. // Because we do no form of static analysis, we only support const variables.
  5028. //
  5029. // Additionally, we can't support parameters, nor can we support static
  5030. // variables (in the latter case, use-before-assign isn't UB; in the former,
  5031. // we have no clue what they'll be assigned to).
  5032. const auto *VD =
  5033. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  5034. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  5035. return false;
  5036. const Expr *Init = VD->getAnyInitializer();
  5037. if (!Init)
  5038. return false;
  5039. const Expr *E = Init->IgnoreParens();
  5040. if (!tryUnwrapAllocSizeCall(E))
  5041. return false;
  5042. // Store E instead of E unwrapped so that the type of the LValue's base is
  5043. // what the user wanted.
  5044. Result.setInvalid(E);
  5045. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5046. Result.addUnsizedArray(Info, E, Pointee);
  5047. return true;
  5048. }
  5049. namespace {
  5050. class PointerExprEvaluator
  5051. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5052. LValue &Result;
  5053. bool InvalidBaseOK;
  5054. bool Success(const Expr *E) {
  5055. Result.set(E);
  5056. return true;
  5057. }
  5058. bool evaluateLValue(const Expr *E, LValue &Result) {
  5059. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5060. }
  5061. bool evaluatePointer(const Expr *E, LValue &Result) {
  5062. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5063. }
  5064. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5065. public:
  5066. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5067. : ExprEvaluatorBaseTy(info), Result(Result),
  5068. InvalidBaseOK(InvalidBaseOK) {}
  5069. bool Success(const APValue &V, const Expr *E) {
  5070. Result.setFrom(Info.Ctx, V);
  5071. return true;
  5072. }
  5073. bool ZeroInitialization(const Expr *E) {
  5074. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5075. Result.setNull(E->getType(), TargetVal);
  5076. return true;
  5077. }
  5078. bool VisitBinaryOperator(const BinaryOperator *E);
  5079. bool VisitCastExpr(const CastExpr* E);
  5080. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5081. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5082. { return Success(E); }
  5083. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5084. if (Info.noteFailure())
  5085. EvaluateIgnoredValue(Info, E->getSubExpr());
  5086. return Error(E);
  5087. }
  5088. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5089. { return Success(E); }
  5090. bool VisitCallExpr(const CallExpr *E);
  5091. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5092. bool VisitBlockExpr(const BlockExpr *E) {
  5093. if (!E->getBlockDecl()->hasCaptures())
  5094. return Success(E);
  5095. return Error(E);
  5096. }
  5097. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5098. // Can't look at 'this' when checking a potential constant expression.
  5099. if (Info.checkingPotentialConstantExpression())
  5100. return false;
  5101. if (!Info.CurrentCall->This) {
  5102. if (Info.getLangOpts().CPlusPlus11)
  5103. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5104. else
  5105. Info.FFDiag(E);
  5106. return false;
  5107. }
  5108. Result = *Info.CurrentCall->This;
  5109. // If we are inside a lambda's call operator, the 'this' expression refers
  5110. // to the enclosing '*this' object (either by value or reference) which is
  5111. // either copied into the closure object's field that represents the '*this'
  5112. // or refers to '*this'.
  5113. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5114. // Update 'Result' to refer to the data member/field of the closure object
  5115. // that represents the '*this' capture.
  5116. if (!HandleLValueMember(Info, E, Result,
  5117. Info.CurrentCall->LambdaThisCaptureField))
  5118. return false;
  5119. // If we captured '*this' by reference, replace the field with its referent.
  5120. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5121. ->isPointerType()) {
  5122. APValue RVal;
  5123. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5124. RVal))
  5125. return false;
  5126. Result.setFrom(Info.Ctx, RVal);
  5127. }
  5128. }
  5129. return true;
  5130. }
  5131. // FIXME: Missing: @protocol, @selector
  5132. };
  5133. } // end anonymous namespace
  5134. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5135. bool InvalidBaseOK) {
  5136. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5137. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5138. }
  5139. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5140. if (E->getOpcode() != BO_Add &&
  5141. E->getOpcode() != BO_Sub)
  5142. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5143. const Expr *PExp = E->getLHS();
  5144. const Expr *IExp = E->getRHS();
  5145. if (IExp->getType()->isPointerType())
  5146. std::swap(PExp, IExp);
  5147. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5148. if (!EvalPtrOK && !Info.noteFailure())
  5149. return false;
  5150. llvm::APSInt Offset;
  5151. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5152. return false;
  5153. if (E->getOpcode() == BO_Sub)
  5154. negateAsSigned(Offset);
  5155. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5156. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5157. }
  5158. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5159. return evaluateLValue(E->getSubExpr(), Result);
  5160. }
  5161. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5162. const Expr *SubExpr = E->getSubExpr();
  5163. switch (E->getCastKind()) {
  5164. default:
  5165. break;
  5166. case CK_BitCast:
  5167. case CK_CPointerToObjCPointerCast:
  5168. case CK_BlockPointerToObjCPointerCast:
  5169. case CK_AnyPointerToBlockPointerCast:
  5170. case CK_AddressSpaceConversion:
  5171. if (!Visit(SubExpr))
  5172. return false;
  5173. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5174. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5175. // also static_casts, but we disallow them as a resolution to DR1312.
  5176. if (!E->getType()->isVoidPointerType()) {
  5177. // If we changed anything other than cvr-qualifiers, we can't use this
  5178. // value for constant folding. FIXME: Qualification conversions should
  5179. // always be CK_NoOp, but we get this wrong in C.
  5180. if (!Info.Ctx.hasCvrSimilarType(E->getType(), E->getSubExpr()->getType()))
  5181. Result.Designator.setInvalid();
  5182. if (SubExpr->getType()->isVoidPointerType())
  5183. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5184. << 3 << SubExpr->getType();
  5185. else
  5186. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5187. }
  5188. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5189. ZeroInitialization(E);
  5190. return true;
  5191. case CK_DerivedToBase:
  5192. case CK_UncheckedDerivedToBase:
  5193. if (!evaluatePointer(E->getSubExpr(), Result))
  5194. return false;
  5195. if (!Result.Base && Result.Offset.isZero())
  5196. return true;
  5197. // Now figure out the necessary offset to add to the base LV to get from
  5198. // the derived class to the base class.
  5199. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5200. castAs<PointerType>()->getPointeeType(),
  5201. Result);
  5202. case CK_BaseToDerived:
  5203. if (!Visit(E->getSubExpr()))
  5204. return false;
  5205. if (!Result.Base && Result.Offset.isZero())
  5206. return true;
  5207. return HandleBaseToDerivedCast(Info, E, Result);
  5208. case CK_NullToPointer:
  5209. VisitIgnoredValue(E->getSubExpr());
  5210. return ZeroInitialization(E);
  5211. case CK_IntegralToPointer: {
  5212. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5213. APValue Value;
  5214. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5215. break;
  5216. if (Value.isInt()) {
  5217. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5218. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5219. Result.Base = (Expr*)nullptr;
  5220. Result.InvalidBase = false;
  5221. Result.Offset = CharUnits::fromQuantity(N);
  5222. Result.Designator.setInvalid();
  5223. Result.IsNullPtr = false;
  5224. return true;
  5225. } else {
  5226. // Cast is of an lvalue, no need to change value.
  5227. Result.setFrom(Info.Ctx, Value);
  5228. return true;
  5229. }
  5230. }
  5231. case CK_ArrayToPointerDecay: {
  5232. if (SubExpr->isGLValue()) {
  5233. if (!evaluateLValue(SubExpr, Result))
  5234. return false;
  5235. } else {
  5236. APValue &Value = createTemporary(SubExpr, false, Result,
  5237. *Info.CurrentCall);
  5238. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5239. return false;
  5240. }
  5241. // The result is a pointer to the first element of the array.
  5242. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5243. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5244. Result.addArray(Info, E, CAT);
  5245. else
  5246. Result.addUnsizedArray(Info, E, AT->getElementType());
  5247. return true;
  5248. }
  5249. case CK_FunctionToPointerDecay:
  5250. return evaluateLValue(SubExpr, Result);
  5251. case CK_LValueToRValue: {
  5252. LValue LVal;
  5253. if (!evaluateLValue(E->getSubExpr(), LVal))
  5254. return false;
  5255. APValue RVal;
  5256. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5257. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5258. LVal, RVal))
  5259. return InvalidBaseOK &&
  5260. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5261. return Success(RVal, E);
  5262. }
  5263. }
  5264. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5265. }
  5266. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
  5267. // C++ [expr.alignof]p3:
  5268. // When alignof is applied to a reference type, the result is the
  5269. // alignment of the referenced type.
  5270. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5271. T = Ref->getPointeeType();
  5272. // __alignof is defined to return the preferred alignment.
  5273. if (T.getQualifiers().hasUnaligned())
  5274. return CharUnits::One();
  5275. return Info.Ctx.toCharUnitsFromBits(
  5276. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5277. }
  5278. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
  5279. E = E->IgnoreParens();
  5280. // The kinds of expressions that we have special-case logic here for
  5281. // should be kept up to date with the special checks for those
  5282. // expressions in Sema.
  5283. // alignof decl is always accepted, even if it doesn't make sense: we default
  5284. // to 1 in those cases.
  5285. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5286. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5287. /*RefAsPointee*/true);
  5288. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5289. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5290. /*RefAsPointee*/true);
  5291. return GetAlignOfType(Info, E->getType());
  5292. }
  5293. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5294. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  5295. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  5296. return true;
  5297. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  5298. return false;
  5299. Result.setInvalid(E);
  5300. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  5301. Result.addUnsizedArray(Info, E, PointeeTy);
  5302. return true;
  5303. }
  5304. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5305. if (IsStringLiteralCall(E))
  5306. return Success(E);
  5307. if (unsigned BuiltinOp = E->getBuiltinCallee())
  5308. return VisitBuiltinCallExpr(E, BuiltinOp);
  5309. return visitNonBuiltinCallExpr(E);
  5310. }
  5311. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  5312. unsigned BuiltinOp) {
  5313. switch (BuiltinOp) {
  5314. case Builtin::BI__builtin_addressof:
  5315. return evaluateLValue(E->getArg(0), Result);
  5316. case Builtin::BI__builtin_assume_aligned: {
  5317. // We need to be very careful here because: if the pointer does not have the
  5318. // asserted alignment, then the behavior is undefined, and undefined
  5319. // behavior is non-constant.
  5320. if (!evaluatePointer(E->getArg(0), Result))
  5321. return false;
  5322. LValue OffsetResult(Result);
  5323. APSInt Alignment;
  5324. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  5325. return false;
  5326. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  5327. if (E->getNumArgs() > 2) {
  5328. APSInt Offset;
  5329. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  5330. return false;
  5331. int64_t AdditionalOffset = -Offset.getZExtValue();
  5332. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  5333. }
  5334. // If there is a base object, then it must have the correct alignment.
  5335. if (OffsetResult.Base) {
  5336. CharUnits BaseAlignment;
  5337. if (const ValueDecl *VD =
  5338. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  5339. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  5340. } else {
  5341. BaseAlignment =
  5342. GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
  5343. }
  5344. if (BaseAlignment < Align) {
  5345. Result.Designator.setInvalid();
  5346. // FIXME: Add support to Diagnostic for long / long long.
  5347. CCEDiag(E->getArg(0),
  5348. diag::note_constexpr_baa_insufficient_alignment) << 0
  5349. << (unsigned)BaseAlignment.getQuantity()
  5350. << (unsigned)Align.getQuantity();
  5351. return false;
  5352. }
  5353. }
  5354. // The offset must also have the correct alignment.
  5355. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  5356. Result.Designator.setInvalid();
  5357. (OffsetResult.Base
  5358. ? CCEDiag(E->getArg(0),
  5359. diag::note_constexpr_baa_insufficient_alignment) << 1
  5360. : CCEDiag(E->getArg(0),
  5361. diag::note_constexpr_baa_value_insufficient_alignment))
  5362. << (int)OffsetResult.Offset.getQuantity()
  5363. << (unsigned)Align.getQuantity();
  5364. return false;
  5365. }
  5366. return true;
  5367. }
  5368. case Builtin::BIstrchr:
  5369. case Builtin::BIwcschr:
  5370. case Builtin::BImemchr:
  5371. case Builtin::BIwmemchr:
  5372. if (Info.getLangOpts().CPlusPlus11)
  5373. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5374. << /*isConstexpr*/0 << /*isConstructor*/0
  5375. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5376. else
  5377. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5378. LLVM_FALLTHROUGH;
  5379. case Builtin::BI__builtin_strchr:
  5380. case Builtin::BI__builtin_wcschr:
  5381. case Builtin::BI__builtin_memchr:
  5382. case Builtin::BI__builtin_char_memchr:
  5383. case Builtin::BI__builtin_wmemchr: {
  5384. if (!Visit(E->getArg(0)))
  5385. return false;
  5386. APSInt Desired;
  5387. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  5388. return false;
  5389. uint64_t MaxLength = uint64_t(-1);
  5390. if (BuiltinOp != Builtin::BIstrchr &&
  5391. BuiltinOp != Builtin::BIwcschr &&
  5392. BuiltinOp != Builtin::BI__builtin_strchr &&
  5393. BuiltinOp != Builtin::BI__builtin_wcschr) {
  5394. APSInt N;
  5395. if (!EvaluateInteger(E->getArg(2), N, Info))
  5396. return false;
  5397. MaxLength = N.getExtValue();
  5398. }
  5399. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  5400. // Figure out what value we're actually looking for (after converting to
  5401. // the corresponding unsigned type if necessary).
  5402. uint64_t DesiredVal;
  5403. bool StopAtNull = false;
  5404. switch (BuiltinOp) {
  5405. case Builtin::BIstrchr:
  5406. case Builtin::BI__builtin_strchr:
  5407. // strchr compares directly to the passed integer, and therefore
  5408. // always fails if given an int that is not a char.
  5409. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  5410. E->getArg(1)->getType(),
  5411. Desired),
  5412. Desired))
  5413. return ZeroInitialization(E);
  5414. StopAtNull = true;
  5415. LLVM_FALLTHROUGH;
  5416. case Builtin::BImemchr:
  5417. case Builtin::BI__builtin_memchr:
  5418. case Builtin::BI__builtin_char_memchr:
  5419. // memchr compares by converting both sides to unsigned char. That's also
  5420. // correct for strchr if we get this far (to cope with plain char being
  5421. // unsigned in the strchr case).
  5422. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  5423. break;
  5424. case Builtin::BIwcschr:
  5425. case Builtin::BI__builtin_wcschr:
  5426. StopAtNull = true;
  5427. LLVM_FALLTHROUGH;
  5428. case Builtin::BIwmemchr:
  5429. case Builtin::BI__builtin_wmemchr:
  5430. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  5431. DesiredVal = Desired.getZExtValue();
  5432. break;
  5433. }
  5434. for (; MaxLength; --MaxLength) {
  5435. APValue Char;
  5436. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  5437. !Char.isInt())
  5438. return false;
  5439. if (Char.getInt().getZExtValue() == DesiredVal)
  5440. return true;
  5441. if (StopAtNull && !Char.getInt())
  5442. break;
  5443. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  5444. return false;
  5445. }
  5446. // Not found: return nullptr.
  5447. return ZeroInitialization(E);
  5448. }
  5449. case Builtin::BImemcpy:
  5450. case Builtin::BImemmove:
  5451. case Builtin::BIwmemcpy:
  5452. case Builtin::BIwmemmove:
  5453. if (Info.getLangOpts().CPlusPlus11)
  5454. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5455. << /*isConstexpr*/0 << /*isConstructor*/0
  5456. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5457. else
  5458. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5459. LLVM_FALLTHROUGH;
  5460. case Builtin::BI__builtin_memcpy:
  5461. case Builtin::BI__builtin_memmove:
  5462. case Builtin::BI__builtin_wmemcpy:
  5463. case Builtin::BI__builtin_wmemmove: {
  5464. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  5465. BuiltinOp == Builtin::BIwmemmove ||
  5466. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  5467. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5468. bool Move = BuiltinOp == Builtin::BImemmove ||
  5469. BuiltinOp == Builtin::BIwmemmove ||
  5470. BuiltinOp == Builtin::BI__builtin_memmove ||
  5471. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5472. // The result of mem* is the first argument.
  5473. if (!Visit(E->getArg(0)) || Result.Designator.Invalid)
  5474. return false;
  5475. LValue Dest = Result;
  5476. LValue Src;
  5477. if (!EvaluatePointer(E->getArg(1), Src, Info) || Src.Designator.Invalid)
  5478. return false;
  5479. APSInt N;
  5480. if (!EvaluateInteger(E->getArg(2), N, Info))
  5481. return false;
  5482. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  5483. // If the size is zero, we treat this as always being a valid no-op.
  5484. // (Even if one of the src and dest pointers is null.)
  5485. if (!N)
  5486. return true;
  5487. // We require that Src and Dest are both pointers to arrays of
  5488. // trivially-copyable type. (For the wide version, the designator will be
  5489. // invalid if the designated object is not a wchar_t.)
  5490. QualType T = Dest.Designator.getType(Info.Ctx);
  5491. QualType SrcT = Src.Designator.getType(Info.Ctx);
  5492. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  5493. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  5494. return false;
  5495. }
  5496. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  5497. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  5498. return false;
  5499. }
  5500. // Figure out how many T's we're copying.
  5501. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  5502. if (!WChar) {
  5503. uint64_t Remainder;
  5504. llvm::APInt OrigN = N;
  5505. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  5506. if (Remainder) {
  5507. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5508. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  5509. << (unsigned)TSize;
  5510. return false;
  5511. }
  5512. }
  5513. // Check that the copying will remain within the arrays, just so that we
  5514. // can give a more meaningful diagnostic. This implicitly also checks that
  5515. // N fits into 64 bits.
  5516. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  5517. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  5518. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  5519. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  5520. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  5521. << N.toString(10, /*Signed*/false);
  5522. return false;
  5523. }
  5524. uint64_t NElems = N.getZExtValue();
  5525. uint64_t NBytes = NElems * TSize;
  5526. // Check for overlap.
  5527. int Direction = 1;
  5528. if (HasSameBase(Src, Dest)) {
  5529. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  5530. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  5531. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  5532. // Dest is inside the source region.
  5533. if (!Move) {
  5534. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5535. return false;
  5536. }
  5537. // For memmove and friends, copy backwards.
  5538. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  5539. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  5540. return false;
  5541. Direction = -1;
  5542. } else if (!Move && SrcOffset >= DestOffset &&
  5543. SrcOffset - DestOffset < NBytes) {
  5544. // Src is inside the destination region for memcpy: invalid.
  5545. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  5546. return false;
  5547. }
  5548. }
  5549. while (true) {
  5550. APValue Val;
  5551. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  5552. !handleAssignment(Info, E, Dest, T, Val))
  5553. return false;
  5554. // Do not iterate past the last element; if we're copying backwards, that
  5555. // might take us off the start of the array.
  5556. if (--NElems == 0)
  5557. return true;
  5558. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  5559. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  5560. return false;
  5561. }
  5562. }
  5563. default:
  5564. return visitNonBuiltinCallExpr(E);
  5565. }
  5566. }
  5567. //===----------------------------------------------------------------------===//
  5568. // Member Pointer Evaluation
  5569. //===----------------------------------------------------------------------===//
  5570. namespace {
  5571. class MemberPointerExprEvaluator
  5572. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  5573. MemberPtr &Result;
  5574. bool Success(const ValueDecl *D) {
  5575. Result = MemberPtr(D);
  5576. return true;
  5577. }
  5578. public:
  5579. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  5580. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  5581. bool Success(const APValue &V, const Expr *E) {
  5582. Result.setFrom(V);
  5583. return true;
  5584. }
  5585. bool ZeroInitialization(const Expr *E) {
  5586. return Success((const ValueDecl*)nullptr);
  5587. }
  5588. bool VisitCastExpr(const CastExpr *E);
  5589. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5590. };
  5591. } // end anonymous namespace
  5592. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  5593. EvalInfo &Info) {
  5594. assert(E->isRValue() && E->getType()->isMemberPointerType());
  5595. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  5596. }
  5597. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5598. switch (E->getCastKind()) {
  5599. default:
  5600. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5601. case CK_NullToMemberPointer:
  5602. VisitIgnoredValue(E->getSubExpr());
  5603. return ZeroInitialization(E);
  5604. case CK_BaseToDerivedMemberPointer: {
  5605. if (!Visit(E->getSubExpr()))
  5606. return false;
  5607. if (E->path_empty())
  5608. return true;
  5609. // Base-to-derived member pointer casts store the path in derived-to-base
  5610. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  5611. // the wrong end of the derived->base arc, so stagger the path by one class.
  5612. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  5613. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  5614. PathI != PathE; ++PathI) {
  5615. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5616. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  5617. if (!Result.castToDerived(Derived))
  5618. return Error(E);
  5619. }
  5620. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  5621. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  5622. return Error(E);
  5623. return true;
  5624. }
  5625. case CK_DerivedToBaseMemberPointer:
  5626. if (!Visit(E->getSubExpr()))
  5627. return false;
  5628. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5629. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5630. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  5631. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5632. if (!Result.castToBase(Base))
  5633. return Error(E);
  5634. }
  5635. return true;
  5636. }
  5637. }
  5638. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5639. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  5640. // member can be formed.
  5641. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  5642. }
  5643. //===----------------------------------------------------------------------===//
  5644. // Record Evaluation
  5645. //===----------------------------------------------------------------------===//
  5646. namespace {
  5647. class RecordExprEvaluator
  5648. : public ExprEvaluatorBase<RecordExprEvaluator> {
  5649. const LValue &This;
  5650. APValue &Result;
  5651. public:
  5652. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  5653. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  5654. bool Success(const APValue &V, const Expr *E) {
  5655. Result = V;
  5656. return true;
  5657. }
  5658. bool ZeroInitialization(const Expr *E) {
  5659. return ZeroInitialization(E, E->getType());
  5660. }
  5661. bool ZeroInitialization(const Expr *E, QualType T);
  5662. bool VisitCallExpr(const CallExpr *E) {
  5663. return handleCallExpr(E, Result, &This);
  5664. }
  5665. bool VisitCastExpr(const CastExpr *E);
  5666. bool VisitInitListExpr(const InitListExpr *E);
  5667. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  5668. return VisitCXXConstructExpr(E, E->getType());
  5669. }
  5670. bool VisitLambdaExpr(const LambdaExpr *E);
  5671. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  5672. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  5673. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  5674. bool VisitBinCmp(const BinaryOperator *E);
  5675. };
  5676. }
  5677. /// Perform zero-initialization on an object of non-union class type.
  5678. /// C++11 [dcl.init]p5:
  5679. /// To zero-initialize an object or reference of type T means:
  5680. /// [...]
  5681. /// -- if T is a (possibly cv-qualified) non-union class type,
  5682. /// each non-static data member and each base-class subobject is
  5683. /// zero-initialized
  5684. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  5685. const RecordDecl *RD,
  5686. const LValue &This, APValue &Result) {
  5687. assert(!RD->isUnion() && "Expected non-union class type");
  5688. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  5689. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  5690. std::distance(RD->field_begin(), RD->field_end()));
  5691. if (RD->isInvalidDecl()) return false;
  5692. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5693. if (CD) {
  5694. unsigned Index = 0;
  5695. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  5696. End = CD->bases_end(); I != End; ++I, ++Index) {
  5697. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  5698. LValue Subobject = This;
  5699. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  5700. return false;
  5701. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  5702. Result.getStructBase(Index)))
  5703. return false;
  5704. }
  5705. }
  5706. for (const auto *I : RD->fields()) {
  5707. // -- if T is a reference type, no initialization is performed.
  5708. if (I->getType()->isReferenceType())
  5709. continue;
  5710. LValue Subobject = This;
  5711. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  5712. return false;
  5713. ImplicitValueInitExpr VIE(I->getType());
  5714. if (!EvaluateInPlace(
  5715. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  5716. return false;
  5717. }
  5718. return true;
  5719. }
  5720. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  5721. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  5722. if (RD->isInvalidDecl()) return false;
  5723. if (RD->isUnion()) {
  5724. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  5725. // object's first non-static named data member is zero-initialized
  5726. RecordDecl::field_iterator I = RD->field_begin();
  5727. if (I == RD->field_end()) {
  5728. Result = APValue((const FieldDecl*)nullptr);
  5729. return true;
  5730. }
  5731. LValue Subobject = This;
  5732. if (!HandleLValueMember(Info, E, Subobject, *I))
  5733. return false;
  5734. Result = APValue(*I);
  5735. ImplicitValueInitExpr VIE(I->getType());
  5736. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  5737. }
  5738. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  5739. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  5740. return false;
  5741. }
  5742. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  5743. }
  5744. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5745. switch (E->getCastKind()) {
  5746. default:
  5747. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5748. case CK_ConstructorConversion:
  5749. return Visit(E->getSubExpr());
  5750. case CK_DerivedToBase:
  5751. case CK_UncheckedDerivedToBase: {
  5752. APValue DerivedObject;
  5753. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  5754. return false;
  5755. if (!DerivedObject.isStruct())
  5756. return Error(E->getSubExpr());
  5757. // Derived-to-base rvalue conversion: just slice off the derived part.
  5758. APValue *Value = &DerivedObject;
  5759. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  5760. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  5761. PathE = E->path_end(); PathI != PathE; ++PathI) {
  5762. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  5763. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  5764. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  5765. RD = Base;
  5766. }
  5767. Result = *Value;
  5768. return true;
  5769. }
  5770. }
  5771. }
  5772. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5773. if (E->isTransparent())
  5774. return Visit(E->getInit(0));
  5775. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  5776. if (RD->isInvalidDecl()) return false;
  5777. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  5778. if (RD->isUnion()) {
  5779. const FieldDecl *Field = E->getInitializedFieldInUnion();
  5780. Result = APValue(Field);
  5781. if (!Field)
  5782. return true;
  5783. // If the initializer list for a union does not contain any elements, the
  5784. // first element of the union is value-initialized.
  5785. // FIXME: The element should be initialized from an initializer list.
  5786. // Is this difference ever observable for initializer lists which
  5787. // we don't build?
  5788. ImplicitValueInitExpr VIE(Field->getType());
  5789. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  5790. LValue Subobject = This;
  5791. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  5792. return false;
  5793. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5794. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5795. isa<CXXDefaultInitExpr>(InitExpr));
  5796. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  5797. }
  5798. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  5799. if (Result.isUninit())
  5800. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  5801. std::distance(RD->field_begin(), RD->field_end()));
  5802. unsigned ElementNo = 0;
  5803. bool Success = true;
  5804. // Initialize base classes.
  5805. if (CXXRD) {
  5806. for (const auto &Base : CXXRD->bases()) {
  5807. assert(ElementNo < E->getNumInits() && "missing init for base class");
  5808. const Expr *Init = E->getInit(ElementNo);
  5809. LValue Subobject = This;
  5810. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  5811. return false;
  5812. APValue &FieldVal = Result.getStructBase(ElementNo);
  5813. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  5814. if (!Info.noteFailure())
  5815. return false;
  5816. Success = false;
  5817. }
  5818. ++ElementNo;
  5819. }
  5820. }
  5821. // Initialize members.
  5822. for (const auto *Field : RD->fields()) {
  5823. // Anonymous bit-fields are not considered members of the class for
  5824. // purposes of aggregate initialization.
  5825. if (Field->isUnnamedBitfield())
  5826. continue;
  5827. LValue Subobject = This;
  5828. bool HaveInit = ElementNo < E->getNumInits();
  5829. // FIXME: Diagnostics here should point to the end of the initializer
  5830. // list, not the start.
  5831. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  5832. Subobject, Field, &Layout))
  5833. return false;
  5834. // Perform an implicit value-initialization for members beyond the end of
  5835. // the initializer list.
  5836. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  5837. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  5838. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  5839. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  5840. isa<CXXDefaultInitExpr>(Init));
  5841. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5842. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  5843. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  5844. FieldVal, Field))) {
  5845. if (!Info.noteFailure())
  5846. return false;
  5847. Success = false;
  5848. }
  5849. }
  5850. return Success;
  5851. }
  5852. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  5853. QualType T) {
  5854. // Note that E's type is not necessarily the type of our class here; we might
  5855. // be initializing an array element instead.
  5856. const CXXConstructorDecl *FD = E->getConstructor();
  5857. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  5858. bool ZeroInit = E->requiresZeroInitialization();
  5859. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  5860. // If we've already performed zero-initialization, we're already done.
  5861. if (!Result.isUninit())
  5862. return true;
  5863. // We can get here in two different ways:
  5864. // 1) We're performing value-initialization, and should zero-initialize
  5865. // the object, or
  5866. // 2) We're performing default-initialization of an object with a trivial
  5867. // constexpr default constructor, in which case we should start the
  5868. // lifetimes of all the base subobjects (there can be no data member
  5869. // subobjects in this case) per [basic.life]p1.
  5870. // Either way, ZeroInitialization is appropriate.
  5871. return ZeroInitialization(E, T);
  5872. }
  5873. const FunctionDecl *Definition = nullptr;
  5874. auto Body = FD->getBody(Definition);
  5875. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5876. return false;
  5877. // Avoid materializing a temporary for an elidable copy/move constructor.
  5878. if (E->isElidable() && !ZeroInit)
  5879. if (const MaterializeTemporaryExpr *ME
  5880. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  5881. return Visit(ME->GetTemporaryExpr());
  5882. if (ZeroInit && !ZeroInitialization(E, T))
  5883. return false;
  5884. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  5885. return HandleConstructorCall(E, This, Args,
  5886. cast<CXXConstructorDecl>(Definition), Info,
  5887. Result);
  5888. }
  5889. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  5890. const CXXInheritedCtorInitExpr *E) {
  5891. if (!Info.CurrentCall) {
  5892. assert(Info.checkingPotentialConstantExpression());
  5893. return false;
  5894. }
  5895. const CXXConstructorDecl *FD = E->getConstructor();
  5896. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  5897. return false;
  5898. const FunctionDecl *Definition = nullptr;
  5899. auto Body = FD->getBody(Definition);
  5900. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  5901. return false;
  5902. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  5903. cast<CXXConstructorDecl>(Definition), Info,
  5904. Result);
  5905. }
  5906. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  5907. const CXXStdInitializerListExpr *E) {
  5908. const ConstantArrayType *ArrayType =
  5909. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  5910. LValue Array;
  5911. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  5912. return false;
  5913. // Get a pointer to the first element of the array.
  5914. Array.addArray(Info, E, ArrayType);
  5915. // FIXME: Perform the checks on the field types in SemaInit.
  5916. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  5917. RecordDecl::field_iterator Field = Record->field_begin();
  5918. if (Field == Record->field_end())
  5919. return Error(E);
  5920. // Start pointer.
  5921. if (!Field->getType()->isPointerType() ||
  5922. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5923. ArrayType->getElementType()))
  5924. return Error(E);
  5925. // FIXME: What if the initializer_list type has base classes, etc?
  5926. Result = APValue(APValue::UninitStruct(), 0, 2);
  5927. Array.moveInto(Result.getStructField(0));
  5928. if (++Field == Record->field_end())
  5929. return Error(E);
  5930. if (Field->getType()->isPointerType() &&
  5931. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  5932. ArrayType->getElementType())) {
  5933. // End pointer.
  5934. if (!HandleLValueArrayAdjustment(Info, E, Array,
  5935. ArrayType->getElementType(),
  5936. ArrayType->getSize().getZExtValue()))
  5937. return false;
  5938. Array.moveInto(Result.getStructField(1));
  5939. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  5940. // Length.
  5941. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  5942. else
  5943. return Error(E);
  5944. if (++Field != Record->field_end())
  5945. return Error(E);
  5946. return true;
  5947. }
  5948. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  5949. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  5950. if (ClosureClass->isInvalidDecl()) return false;
  5951. if (Info.checkingPotentialConstantExpression()) return true;
  5952. const size_t NumFields =
  5953. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  5954. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  5955. E->capture_init_end()) &&
  5956. "The number of lambda capture initializers should equal the number of "
  5957. "fields within the closure type");
  5958. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  5959. // Iterate through all the lambda's closure object's fields and initialize
  5960. // them.
  5961. auto *CaptureInitIt = E->capture_init_begin();
  5962. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  5963. bool Success = true;
  5964. for (const auto *Field : ClosureClass->fields()) {
  5965. assert(CaptureInitIt != E->capture_init_end());
  5966. // Get the initializer for this field
  5967. Expr *const CurFieldInit = *CaptureInitIt++;
  5968. // If there is no initializer, either this is a VLA or an error has
  5969. // occurred.
  5970. if (!CurFieldInit)
  5971. return Error(E);
  5972. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  5973. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  5974. if (!Info.keepEvaluatingAfterFailure())
  5975. return false;
  5976. Success = false;
  5977. }
  5978. ++CaptureIt;
  5979. }
  5980. return Success;
  5981. }
  5982. static bool EvaluateRecord(const Expr *E, const LValue &This,
  5983. APValue &Result, EvalInfo &Info) {
  5984. assert(E->isRValue() && E->getType()->isRecordType() &&
  5985. "can't evaluate expression as a record rvalue");
  5986. return RecordExprEvaluator(Info, This, Result).Visit(E);
  5987. }
  5988. //===----------------------------------------------------------------------===//
  5989. // Temporary Evaluation
  5990. //
  5991. // Temporaries are represented in the AST as rvalues, but generally behave like
  5992. // lvalues. The full-object of which the temporary is a subobject is implicitly
  5993. // materialized so that a reference can bind to it.
  5994. //===----------------------------------------------------------------------===//
  5995. namespace {
  5996. class TemporaryExprEvaluator
  5997. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  5998. public:
  5999. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  6000. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  6001. /// Visit an expression which constructs the value of this temporary.
  6002. bool VisitConstructExpr(const Expr *E) {
  6003. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  6004. return EvaluateInPlace(Value, Info, Result, E);
  6005. }
  6006. bool VisitCastExpr(const CastExpr *E) {
  6007. switch (E->getCastKind()) {
  6008. default:
  6009. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6010. case CK_ConstructorConversion:
  6011. return VisitConstructExpr(E->getSubExpr());
  6012. }
  6013. }
  6014. bool VisitInitListExpr(const InitListExpr *E) {
  6015. return VisitConstructExpr(E);
  6016. }
  6017. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6018. return VisitConstructExpr(E);
  6019. }
  6020. bool VisitCallExpr(const CallExpr *E) {
  6021. return VisitConstructExpr(E);
  6022. }
  6023. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  6024. return VisitConstructExpr(E);
  6025. }
  6026. bool VisitLambdaExpr(const LambdaExpr *E) {
  6027. return VisitConstructExpr(E);
  6028. }
  6029. };
  6030. } // end anonymous namespace
  6031. /// Evaluate an expression of record type as a temporary.
  6032. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  6033. assert(E->isRValue() && E->getType()->isRecordType());
  6034. return TemporaryExprEvaluator(Info, Result).Visit(E);
  6035. }
  6036. //===----------------------------------------------------------------------===//
  6037. // Vector Evaluation
  6038. //===----------------------------------------------------------------------===//
  6039. namespace {
  6040. class VectorExprEvaluator
  6041. : public ExprEvaluatorBase<VectorExprEvaluator> {
  6042. APValue &Result;
  6043. public:
  6044. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  6045. : ExprEvaluatorBaseTy(info), Result(Result) {}
  6046. bool Success(ArrayRef<APValue> V, const Expr *E) {
  6047. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  6048. // FIXME: remove this APValue copy.
  6049. Result = APValue(V.data(), V.size());
  6050. return true;
  6051. }
  6052. bool Success(const APValue &V, const Expr *E) {
  6053. assert(V.isVector());
  6054. Result = V;
  6055. return true;
  6056. }
  6057. bool ZeroInitialization(const Expr *E);
  6058. bool VisitUnaryReal(const UnaryOperator *E)
  6059. { return Visit(E->getSubExpr()); }
  6060. bool VisitCastExpr(const CastExpr* E);
  6061. bool VisitInitListExpr(const InitListExpr *E);
  6062. bool VisitUnaryImag(const UnaryOperator *E);
  6063. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  6064. // binary comparisons, binary and/or/xor,
  6065. // shufflevector, ExtVectorElementExpr
  6066. };
  6067. } // end anonymous namespace
  6068. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  6069. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  6070. return VectorExprEvaluator(Info, Result).Visit(E);
  6071. }
  6072. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6073. const VectorType *VTy = E->getType()->castAs<VectorType>();
  6074. unsigned NElts = VTy->getNumElements();
  6075. const Expr *SE = E->getSubExpr();
  6076. QualType SETy = SE->getType();
  6077. switch (E->getCastKind()) {
  6078. case CK_VectorSplat: {
  6079. APValue Val = APValue();
  6080. if (SETy->isIntegerType()) {
  6081. APSInt IntResult;
  6082. if (!EvaluateInteger(SE, IntResult, Info))
  6083. return false;
  6084. Val = APValue(std::move(IntResult));
  6085. } else if (SETy->isRealFloatingType()) {
  6086. APFloat FloatResult(0.0);
  6087. if (!EvaluateFloat(SE, FloatResult, Info))
  6088. return false;
  6089. Val = APValue(std::move(FloatResult));
  6090. } else {
  6091. return Error(E);
  6092. }
  6093. // Splat and create vector APValue.
  6094. SmallVector<APValue, 4> Elts(NElts, Val);
  6095. return Success(Elts, E);
  6096. }
  6097. case CK_BitCast: {
  6098. // Evaluate the operand into an APInt we can extract from.
  6099. llvm::APInt SValInt;
  6100. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  6101. return false;
  6102. // Extract the elements
  6103. QualType EltTy = VTy->getElementType();
  6104. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  6105. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  6106. SmallVector<APValue, 4> Elts;
  6107. if (EltTy->isRealFloatingType()) {
  6108. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  6109. unsigned FloatEltSize = EltSize;
  6110. if (&Sem == &APFloat::x87DoubleExtended())
  6111. FloatEltSize = 80;
  6112. for (unsigned i = 0; i < NElts; i++) {
  6113. llvm::APInt Elt;
  6114. if (BigEndian)
  6115. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  6116. else
  6117. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  6118. Elts.push_back(APValue(APFloat(Sem, Elt)));
  6119. }
  6120. } else if (EltTy->isIntegerType()) {
  6121. for (unsigned i = 0; i < NElts; i++) {
  6122. llvm::APInt Elt;
  6123. if (BigEndian)
  6124. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  6125. else
  6126. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  6127. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  6128. }
  6129. } else {
  6130. return Error(E);
  6131. }
  6132. return Success(Elts, E);
  6133. }
  6134. default:
  6135. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6136. }
  6137. }
  6138. bool
  6139. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6140. const VectorType *VT = E->getType()->castAs<VectorType>();
  6141. unsigned NumInits = E->getNumInits();
  6142. unsigned NumElements = VT->getNumElements();
  6143. QualType EltTy = VT->getElementType();
  6144. SmallVector<APValue, 4> Elements;
  6145. // The number of initializers can be less than the number of
  6146. // vector elements. For OpenCL, this can be due to nested vector
  6147. // initialization. For GCC compatibility, missing trailing elements
  6148. // should be initialized with zeroes.
  6149. unsigned CountInits = 0, CountElts = 0;
  6150. while (CountElts < NumElements) {
  6151. // Handle nested vector initialization.
  6152. if (CountInits < NumInits
  6153. && E->getInit(CountInits)->getType()->isVectorType()) {
  6154. APValue v;
  6155. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  6156. return Error(E);
  6157. unsigned vlen = v.getVectorLength();
  6158. for (unsigned j = 0; j < vlen; j++)
  6159. Elements.push_back(v.getVectorElt(j));
  6160. CountElts += vlen;
  6161. } else if (EltTy->isIntegerType()) {
  6162. llvm::APSInt sInt(32);
  6163. if (CountInits < NumInits) {
  6164. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6165. return false;
  6166. } else // trailing integer zero.
  6167. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6168. Elements.push_back(APValue(sInt));
  6169. CountElts++;
  6170. } else {
  6171. llvm::APFloat f(0.0);
  6172. if (CountInits < NumInits) {
  6173. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6174. return false;
  6175. } else // trailing float zero.
  6176. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6177. Elements.push_back(APValue(f));
  6178. CountElts++;
  6179. }
  6180. CountInits++;
  6181. }
  6182. return Success(Elements, E);
  6183. }
  6184. bool
  6185. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6186. const VectorType *VT = E->getType()->getAs<VectorType>();
  6187. QualType EltTy = VT->getElementType();
  6188. APValue ZeroElement;
  6189. if (EltTy->isIntegerType())
  6190. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6191. else
  6192. ZeroElement =
  6193. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6194. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6195. return Success(Elements, E);
  6196. }
  6197. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6198. VisitIgnoredValue(E->getSubExpr());
  6199. return ZeroInitialization(E);
  6200. }
  6201. //===----------------------------------------------------------------------===//
  6202. // Array Evaluation
  6203. //===----------------------------------------------------------------------===//
  6204. namespace {
  6205. class ArrayExprEvaluator
  6206. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6207. const LValue &This;
  6208. APValue &Result;
  6209. public:
  6210. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6211. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6212. bool Success(const APValue &V, const Expr *E) {
  6213. assert((V.isArray() || V.isLValue()) &&
  6214. "expected array or string literal");
  6215. Result = V;
  6216. return true;
  6217. }
  6218. bool ZeroInitialization(const Expr *E) {
  6219. const ConstantArrayType *CAT =
  6220. Info.Ctx.getAsConstantArrayType(E->getType());
  6221. if (!CAT)
  6222. return Error(E);
  6223. Result = APValue(APValue::UninitArray(), 0,
  6224. CAT->getSize().getZExtValue());
  6225. if (!Result.hasArrayFiller()) return true;
  6226. // Zero-initialize all elements.
  6227. LValue Subobject = This;
  6228. Subobject.addArray(Info, E, CAT);
  6229. ImplicitValueInitExpr VIE(CAT->getElementType());
  6230. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6231. }
  6232. bool VisitCallExpr(const CallExpr *E) {
  6233. return handleCallExpr(E, Result, &This);
  6234. }
  6235. bool VisitInitListExpr(const InitListExpr *E);
  6236. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6237. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6238. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6239. const LValue &Subobject,
  6240. APValue *Value, QualType Type);
  6241. };
  6242. } // end anonymous namespace
  6243. static bool EvaluateArray(const Expr *E, const LValue &This,
  6244. APValue &Result, EvalInfo &Info) {
  6245. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  6246. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  6247. }
  6248. // Return true iff the given array filler may depend on the element index.
  6249. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  6250. // For now, just whitelist non-class value-initialization and initialization
  6251. // lists comprised of them.
  6252. if (isa<ImplicitValueInitExpr>(FillerExpr))
  6253. return false;
  6254. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  6255. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  6256. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  6257. return true;
  6258. }
  6259. return false;
  6260. }
  6261. return true;
  6262. }
  6263. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6264. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  6265. if (!CAT)
  6266. return Error(E);
  6267. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  6268. // an appropriately-typed string literal enclosed in braces.
  6269. if (E->isStringLiteralInit()) {
  6270. LValue LV;
  6271. if (!EvaluateLValue(E->getInit(0), LV, Info))
  6272. return false;
  6273. APValue Val;
  6274. LV.moveInto(Val);
  6275. return Success(Val, E);
  6276. }
  6277. bool Success = true;
  6278. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  6279. "zero-initialized array shouldn't have any initialized elts");
  6280. APValue Filler;
  6281. if (Result.isArray() && Result.hasArrayFiller())
  6282. Filler = Result.getArrayFiller();
  6283. unsigned NumEltsToInit = E->getNumInits();
  6284. unsigned NumElts = CAT->getSize().getZExtValue();
  6285. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  6286. // If the initializer might depend on the array index, run it for each
  6287. // array element.
  6288. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  6289. NumEltsToInit = NumElts;
  6290. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  6291. << NumEltsToInit << ".\n");
  6292. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  6293. // If the array was previously zero-initialized, preserve the
  6294. // zero-initialized values.
  6295. if (!Filler.isUninit()) {
  6296. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  6297. Result.getArrayInitializedElt(I) = Filler;
  6298. if (Result.hasArrayFiller())
  6299. Result.getArrayFiller() = Filler;
  6300. }
  6301. LValue Subobject = This;
  6302. Subobject.addArray(Info, E, CAT);
  6303. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  6304. const Expr *Init =
  6305. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  6306. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6307. Info, Subobject, Init) ||
  6308. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  6309. CAT->getElementType(), 1)) {
  6310. if (!Info.noteFailure())
  6311. return false;
  6312. Success = false;
  6313. }
  6314. }
  6315. if (!Result.hasArrayFiller())
  6316. return Success;
  6317. // If we get here, we have a trivial filler, which we can just evaluate
  6318. // once and splat over the rest of the array elements.
  6319. assert(FillerExpr && "no array filler for incomplete init list");
  6320. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  6321. FillerExpr) && Success;
  6322. }
  6323. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  6324. if (E->getCommonExpr() &&
  6325. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  6326. Info, E->getCommonExpr()->getSourceExpr()))
  6327. return false;
  6328. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  6329. uint64_t Elements = CAT->getSize().getZExtValue();
  6330. Result = APValue(APValue::UninitArray(), Elements, Elements);
  6331. LValue Subobject = This;
  6332. Subobject.addArray(Info, E, CAT);
  6333. bool Success = true;
  6334. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  6335. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6336. Info, Subobject, E->getSubExpr()) ||
  6337. !HandleLValueArrayAdjustment(Info, E, Subobject,
  6338. CAT->getElementType(), 1)) {
  6339. if (!Info.noteFailure())
  6340. return false;
  6341. Success = false;
  6342. }
  6343. }
  6344. return Success;
  6345. }
  6346. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6347. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  6348. }
  6349. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6350. const LValue &Subobject,
  6351. APValue *Value,
  6352. QualType Type) {
  6353. bool HadZeroInit = !Value->isUninit();
  6354. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  6355. unsigned N = CAT->getSize().getZExtValue();
  6356. // Preserve the array filler if we had prior zero-initialization.
  6357. APValue Filler =
  6358. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  6359. : APValue();
  6360. *Value = APValue(APValue::UninitArray(), N, N);
  6361. if (HadZeroInit)
  6362. for (unsigned I = 0; I != N; ++I)
  6363. Value->getArrayInitializedElt(I) = Filler;
  6364. // Initialize the elements.
  6365. LValue ArrayElt = Subobject;
  6366. ArrayElt.addArray(Info, E, CAT);
  6367. for (unsigned I = 0; I != N; ++I)
  6368. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  6369. CAT->getElementType()) ||
  6370. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  6371. CAT->getElementType(), 1))
  6372. return false;
  6373. return true;
  6374. }
  6375. if (!Type->isRecordType())
  6376. return Error(E);
  6377. return RecordExprEvaluator(Info, Subobject, *Value)
  6378. .VisitCXXConstructExpr(E, Type);
  6379. }
  6380. //===----------------------------------------------------------------------===//
  6381. // Integer Evaluation
  6382. //
  6383. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  6384. // types and back in constant folding. Integer values are thus represented
  6385. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  6386. //===----------------------------------------------------------------------===//
  6387. namespace {
  6388. class IntExprEvaluator
  6389. : public ExprEvaluatorBase<IntExprEvaluator> {
  6390. APValue &Result;
  6391. public:
  6392. IntExprEvaluator(EvalInfo &info, APValue &result)
  6393. : ExprEvaluatorBaseTy(info), Result(result) {}
  6394. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6395. assert(E->getType()->isIntegralOrEnumerationType() &&
  6396. "Invalid evaluation result.");
  6397. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  6398. "Invalid evaluation result.");
  6399. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6400. "Invalid evaluation result.");
  6401. Result = APValue(SI);
  6402. return true;
  6403. }
  6404. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6405. return Success(SI, E, Result);
  6406. }
  6407. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6408. assert(E->getType()->isIntegralOrEnumerationType() &&
  6409. "Invalid evaluation result.");
  6410. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6411. "Invalid evaluation result.");
  6412. Result = APValue(APSInt(I));
  6413. Result.getInt().setIsUnsigned(
  6414. E->getType()->isUnsignedIntegerOrEnumerationType());
  6415. return true;
  6416. }
  6417. bool Success(const llvm::APInt &I, const Expr *E) {
  6418. return Success(I, E, Result);
  6419. }
  6420. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6421. assert(E->getType()->isIntegralOrEnumerationType() &&
  6422. "Invalid evaluation result.");
  6423. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6424. return true;
  6425. }
  6426. bool Success(uint64_t Value, const Expr *E) {
  6427. return Success(Value, E, Result);
  6428. }
  6429. bool Success(CharUnits Size, const Expr *E) {
  6430. return Success(Size.getQuantity(), E);
  6431. }
  6432. bool Success(const APValue &V, const Expr *E) {
  6433. if (V.isLValue() || V.isAddrLabelDiff()) {
  6434. Result = V;
  6435. return true;
  6436. }
  6437. return Success(V.getInt(), E);
  6438. }
  6439. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6440. //===--------------------------------------------------------------------===//
  6441. // Visitor Methods
  6442. //===--------------------------------------------------------------------===//
  6443. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  6444. return Success(E->getValue(), E);
  6445. }
  6446. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  6447. return Success(E->getValue(), E);
  6448. }
  6449. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  6450. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  6451. if (CheckReferencedDecl(E, E->getDecl()))
  6452. return true;
  6453. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  6454. }
  6455. bool VisitMemberExpr(const MemberExpr *E) {
  6456. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  6457. VisitIgnoredBaseExpression(E->getBase());
  6458. return true;
  6459. }
  6460. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  6461. }
  6462. bool VisitCallExpr(const CallExpr *E);
  6463. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6464. bool VisitBinaryOperator(const BinaryOperator *E);
  6465. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  6466. bool VisitUnaryOperator(const UnaryOperator *E);
  6467. bool VisitCastExpr(const CastExpr* E);
  6468. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  6469. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  6470. return Success(E->getValue(), E);
  6471. }
  6472. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  6473. return Success(E->getValue(), E);
  6474. }
  6475. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  6476. if (Info.ArrayInitIndex == uint64_t(-1)) {
  6477. // We were asked to evaluate this subexpression independent of the
  6478. // enclosing ArrayInitLoopExpr. We can't do that.
  6479. Info.FFDiag(E);
  6480. return false;
  6481. }
  6482. return Success(Info.ArrayInitIndex, E);
  6483. }
  6484. // Note, GNU defines __null as an integer, not a pointer.
  6485. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  6486. return ZeroInitialization(E);
  6487. }
  6488. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  6489. return Success(E->getValue(), E);
  6490. }
  6491. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  6492. return Success(E->getValue(), E);
  6493. }
  6494. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  6495. return Success(E->getValue(), E);
  6496. }
  6497. bool VisitUnaryReal(const UnaryOperator *E);
  6498. bool VisitUnaryImag(const UnaryOperator *E);
  6499. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  6500. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  6501. // FIXME: Missing: array subscript of vector, member of vector
  6502. };
  6503. class FixedPointExprEvaluator
  6504. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  6505. APValue &Result;
  6506. public:
  6507. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  6508. : ExprEvaluatorBaseTy(info), Result(result) {}
  6509. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6510. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6511. assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
  6512. "Invalid evaluation result.");
  6513. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6514. "Invalid evaluation result.");
  6515. Result = APValue(SI);
  6516. return true;
  6517. }
  6518. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6519. return Success(SI, E, Result);
  6520. }
  6521. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6522. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6523. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6524. "Invalid evaluation result.");
  6525. Result = APValue(APSInt(I));
  6526. Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
  6527. return true;
  6528. }
  6529. bool Success(const llvm::APInt &I, const Expr *E) {
  6530. return Success(I, E, Result);
  6531. }
  6532. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6533. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  6534. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6535. return true;
  6536. }
  6537. bool Success(uint64_t Value, const Expr *E) {
  6538. return Success(Value, E, Result);
  6539. }
  6540. bool Success(CharUnits Size, const Expr *E) {
  6541. return Success(Size.getQuantity(), E);
  6542. }
  6543. bool Success(const APValue &V, const Expr *E) {
  6544. if (V.isLValue() || V.isAddrLabelDiff()) {
  6545. Result = V;
  6546. return true;
  6547. }
  6548. return Success(V.getInt(), E);
  6549. }
  6550. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6551. //===--------------------------------------------------------------------===//
  6552. // Visitor Methods
  6553. //===--------------------------------------------------------------------===//
  6554. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  6555. return Success(E->getValue(), E);
  6556. }
  6557. bool VisitUnaryOperator(const UnaryOperator *E);
  6558. };
  6559. } // end anonymous namespace
  6560. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  6561. /// produce either the integer value or a pointer.
  6562. ///
  6563. /// GCC has a heinous extension which folds casts between pointer types and
  6564. /// pointer-sized integral types. We support this by allowing the evaluation of
  6565. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  6566. /// Some simple arithmetic on such values is supported (they are treated much
  6567. /// like char*).
  6568. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  6569. EvalInfo &Info) {
  6570. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  6571. return IntExprEvaluator(Info, Result).Visit(E);
  6572. }
  6573. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  6574. APValue Val;
  6575. if (!EvaluateIntegerOrLValue(E, Val, Info))
  6576. return false;
  6577. if (!Val.isInt()) {
  6578. // FIXME: It would be better to produce the diagnostic for casting
  6579. // a pointer to an integer.
  6580. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6581. return false;
  6582. }
  6583. Result = Val.getInt();
  6584. return true;
  6585. }
  6586. /// Check whether the given declaration can be directly converted to an integral
  6587. /// rvalue. If not, no diagnostic is produced; there are other things we can
  6588. /// try.
  6589. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  6590. // Enums are integer constant exprs.
  6591. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  6592. // Check for signedness/width mismatches between E type and ECD value.
  6593. bool SameSign = (ECD->getInitVal().isSigned()
  6594. == E->getType()->isSignedIntegerOrEnumerationType());
  6595. bool SameWidth = (ECD->getInitVal().getBitWidth()
  6596. == Info.Ctx.getIntWidth(E->getType()));
  6597. if (SameSign && SameWidth)
  6598. return Success(ECD->getInitVal(), E);
  6599. else {
  6600. // Get rid of mismatch (otherwise Success assertions will fail)
  6601. // by computing a new value matching the type of E.
  6602. llvm::APSInt Val = ECD->getInitVal();
  6603. if (!SameSign)
  6604. Val.setIsSigned(!ECD->getInitVal().isSigned());
  6605. if (!SameWidth)
  6606. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  6607. return Success(Val, E);
  6608. }
  6609. }
  6610. return false;
  6611. }
  6612. /// Values returned by __builtin_classify_type, chosen to match the values
  6613. /// produced by GCC's builtin.
  6614. enum class GCCTypeClass {
  6615. None = -1,
  6616. Void = 0,
  6617. Integer = 1,
  6618. // GCC reserves 2 for character types, but instead classifies them as
  6619. // integers.
  6620. Enum = 3,
  6621. Bool = 4,
  6622. Pointer = 5,
  6623. // GCC reserves 6 for references, but appears to never use it (because
  6624. // expressions never have reference type, presumably).
  6625. PointerToDataMember = 7,
  6626. RealFloat = 8,
  6627. Complex = 9,
  6628. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  6629. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6630. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  6631. // uses 12 for that purpose, same as for a class or struct. Maybe it
  6632. // internally implements a pointer to member as a struct? Who knows.
  6633. PointerToMemberFunction = 12, // Not a bug, see above.
  6634. ClassOrStruct = 12,
  6635. Union = 13,
  6636. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  6637. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  6638. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  6639. // literals.
  6640. };
  6641. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6642. /// as GCC.
  6643. static GCCTypeClass
  6644. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  6645. assert(!T->isDependentType() && "unexpected dependent type");
  6646. QualType CanTy = T.getCanonicalType();
  6647. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  6648. switch (CanTy->getTypeClass()) {
  6649. #define TYPE(ID, BASE)
  6650. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6651. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  6652. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  6653. #include "clang/AST/TypeNodes.def"
  6654. case Type::Auto:
  6655. case Type::DeducedTemplateSpecialization:
  6656. llvm_unreachable("unexpected non-canonical or dependent type");
  6657. case Type::Builtin:
  6658. switch (BT->getKind()) {
  6659. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  6660. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  6661. case BuiltinType::ID: return GCCTypeClass::Integer;
  6662. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  6663. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  6664. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  6665. case BuiltinType::ID: break;
  6666. #include "clang/AST/BuiltinTypes.def"
  6667. case BuiltinType::Void:
  6668. return GCCTypeClass::Void;
  6669. case BuiltinType::Bool:
  6670. return GCCTypeClass::Bool;
  6671. case BuiltinType::Char_U:
  6672. case BuiltinType::UChar:
  6673. case BuiltinType::WChar_U:
  6674. case BuiltinType::Char8:
  6675. case BuiltinType::Char16:
  6676. case BuiltinType::Char32:
  6677. case BuiltinType::UShort:
  6678. case BuiltinType::UInt:
  6679. case BuiltinType::ULong:
  6680. case BuiltinType::ULongLong:
  6681. case BuiltinType::UInt128:
  6682. return GCCTypeClass::Integer;
  6683. case BuiltinType::UShortAccum:
  6684. case BuiltinType::UAccum:
  6685. case BuiltinType::ULongAccum:
  6686. case BuiltinType::UShortFract:
  6687. case BuiltinType::UFract:
  6688. case BuiltinType::ULongFract:
  6689. case BuiltinType::SatUShortAccum:
  6690. case BuiltinType::SatUAccum:
  6691. case BuiltinType::SatULongAccum:
  6692. case BuiltinType::SatUShortFract:
  6693. case BuiltinType::SatUFract:
  6694. case BuiltinType::SatULongFract:
  6695. return GCCTypeClass::None;
  6696. case BuiltinType::NullPtr:
  6697. case BuiltinType::ObjCId:
  6698. case BuiltinType::ObjCClass:
  6699. case BuiltinType::ObjCSel:
  6700. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6701. case BuiltinType::Id:
  6702. #include "clang/Basic/OpenCLImageTypes.def"
  6703. case BuiltinType::OCLSampler:
  6704. case BuiltinType::OCLEvent:
  6705. case BuiltinType::OCLClkEvent:
  6706. case BuiltinType::OCLQueue:
  6707. case BuiltinType::OCLReserveID:
  6708. return GCCTypeClass::None;
  6709. case BuiltinType::Dependent:
  6710. llvm_unreachable("unexpected dependent type");
  6711. };
  6712. llvm_unreachable("unexpected placeholder type");
  6713. case Type::Enum:
  6714. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  6715. case Type::Pointer:
  6716. case Type::ConstantArray:
  6717. case Type::VariableArray:
  6718. case Type::IncompleteArray:
  6719. case Type::FunctionNoProto:
  6720. case Type::FunctionProto:
  6721. return GCCTypeClass::Pointer;
  6722. case Type::MemberPointer:
  6723. return CanTy->isMemberDataPointerType()
  6724. ? GCCTypeClass::PointerToDataMember
  6725. : GCCTypeClass::PointerToMemberFunction;
  6726. case Type::Complex:
  6727. return GCCTypeClass::Complex;
  6728. case Type::Record:
  6729. return CanTy->isUnionType() ? GCCTypeClass::Union
  6730. : GCCTypeClass::ClassOrStruct;
  6731. case Type::Atomic:
  6732. // GCC classifies _Atomic T the same as T.
  6733. return EvaluateBuiltinClassifyType(
  6734. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  6735. case Type::BlockPointer:
  6736. case Type::Vector:
  6737. case Type::ExtVector:
  6738. case Type::ObjCObject:
  6739. case Type::ObjCInterface:
  6740. case Type::ObjCObjectPointer:
  6741. case Type::Pipe:
  6742. // GCC classifies vectors as None. We follow its lead and classify all
  6743. // other types that don't fit into the regular classification the same way.
  6744. return GCCTypeClass::None;
  6745. case Type::LValueReference:
  6746. case Type::RValueReference:
  6747. llvm_unreachable("invalid type for expression");
  6748. }
  6749. llvm_unreachable("unexpected type class");
  6750. }
  6751. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  6752. /// as GCC.
  6753. static GCCTypeClass
  6754. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  6755. // If no argument was supplied, default to None. This isn't
  6756. // ideal, however it is what gcc does.
  6757. if (E->getNumArgs() == 0)
  6758. return GCCTypeClass::None;
  6759. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  6760. // being an ICE, but still folds it to a constant using the type of the first
  6761. // argument.
  6762. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  6763. }
  6764. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  6765. /// __builtin_constant_p when applied to the given lvalue.
  6766. ///
  6767. /// An lvalue is only "constant" if it is a pointer or reference to the first
  6768. /// character of a string literal.
  6769. template<typename LValue>
  6770. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  6771. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  6772. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  6773. }
  6774. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  6775. /// GCC as we can manage.
  6776. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  6777. QualType ArgType = Arg->getType();
  6778. // __builtin_constant_p always has one operand. The rules which gcc follows
  6779. // are not precisely documented, but are as follows:
  6780. //
  6781. // - If the operand is of integral, floating, complex or enumeration type,
  6782. // and can be folded to a known value of that type, it returns 1.
  6783. // - If the operand and can be folded to a pointer to the first character
  6784. // of a string literal (or such a pointer cast to an integral type), it
  6785. // returns 1.
  6786. //
  6787. // Otherwise, it returns 0.
  6788. //
  6789. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  6790. // its support for this does not currently work.
  6791. if (ArgType->isIntegralOrEnumerationType()) {
  6792. Expr::EvalResult Result;
  6793. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  6794. return false;
  6795. APValue &V = Result.Val;
  6796. if (V.getKind() == APValue::Int)
  6797. return true;
  6798. if (V.getKind() == APValue::LValue)
  6799. return EvaluateBuiltinConstantPForLValue(V);
  6800. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  6801. return Arg->isEvaluatable(Ctx);
  6802. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  6803. LValue LV;
  6804. Expr::EvalStatus Status;
  6805. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  6806. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  6807. : EvaluatePointer(Arg, LV, Info)) &&
  6808. !Status.HasSideEffects)
  6809. return EvaluateBuiltinConstantPForLValue(LV);
  6810. }
  6811. // Anything else isn't considered to be sufficiently constant.
  6812. return false;
  6813. }
  6814. /// Retrieves the "underlying object type" of the given expression,
  6815. /// as used by __builtin_object_size.
  6816. static QualType getObjectType(APValue::LValueBase B) {
  6817. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  6818. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  6819. return VD->getType();
  6820. } else if (const Expr *E = B.get<const Expr*>()) {
  6821. if (isa<CompoundLiteralExpr>(E))
  6822. return E->getType();
  6823. }
  6824. return QualType();
  6825. }
  6826. /// A more selective version of E->IgnoreParenCasts for
  6827. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  6828. /// to change the type of E.
  6829. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  6830. ///
  6831. /// Always returns an RValue with a pointer representation.
  6832. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  6833. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  6834. auto *NoParens = E->IgnoreParens();
  6835. auto *Cast = dyn_cast<CastExpr>(NoParens);
  6836. if (Cast == nullptr)
  6837. return NoParens;
  6838. // We only conservatively allow a few kinds of casts, because this code is
  6839. // inherently a simple solution that seeks to support the common case.
  6840. auto CastKind = Cast->getCastKind();
  6841. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  6842. CastKind != CK_AddressSpaceConversion)
  6843. return NoParens;
  6844. auto *SubExpr = Cast->getSubExpr();
  6845. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  6846. return NoParens;
  6847. return ignorePointerCastsAndParens(SubExpr);
  6848. }
  6849. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  6850. /// record layout. e.g.
  6851. /// struct { struct { int a, b; } fst, snd; } obj;
  6852. /// obj.fst // no
  6853. /// obj.snd // yes
  6854. /// obj.fst.a // no
  6855. /// obj.fst.b // no
  6856. /// obj.snd.a // no
  6857. /// obj.snd.b // yes
  6858. ///
  6859. /// Please note: this function is specialized for how __builtin_object_size
  6860. /// views "objects".
  6861. ///
  6862. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  6863. /// correct result, it will always return true.
  6864. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  6865. assert(!LVal.Designator.Invalid);
  6866. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  6867. const RecordDecl *Parent = FD->getParent();
  6868. Invalid = Parent->isInvalidDecl();
  6869. if (Invalid || Parent->isUnion())
  6870. return true;
  6871. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  6872. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  6873. };
  6874. auto &Base = LVal.getLValueBase();
  6875. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  6876. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  6877. bool Invalid;
  6878. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6879. return Invalid;
  6880. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  6881. for (auto *FD : IFD->chain()) {
  6882. bool Invalid;
  6883. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  6884. return Invalid;
  6885. }
  6886. }
  6887. }
  6888. unsigned I = 0;
  6889. QualType BaseType = getType(Base);
  6890. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  6891. // If we don't know the array bound, conservatively assume we're looking at
  6892. // the final array element.
  6893. ++I;
  6894. if (BaseType->isIncompleteArrayType())
  6895. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  6896. else
  6897. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  6898. }
  6899. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  6900. const auto &Entry = LVal.Designator.Entries[I];
  6901. if (BaseType->isArrayType()) {
  6902. // Because __builtin_object_size treats arrays as objects, we can ignore
  6903. // the index iff this is the last array in the Designator.
  6904. if (I + 1 == E)
  6905. return true;
  6906. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  6907. uint64_t Index = Entry.ArrayIndex;
  6908. if (Index + 1 != CAT->getSize())
  6909. return false;
  6910. BaseType = CAT->getElementType();
  6911. } else if (BaseType->isAnyComplexType()) {
  6912. const auto *CT = BaseType->castAs<ComplexType>();
  6913. uint64_t Index = Entry.ArrayIndex;
  6914. if (Index != 1)
  6915. return false;
  6916. BaseType = CT->getElementType();
  6917. } else if (auto *FD = getAsField(Entry)) {
  6918. bool Invalid;
  6919. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  6920. return Invalid;
  6921. BaseType = FD->getType();
  6922. } else {
  6923. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  6924. return false;
  6925. }
  6926. }
  6927. return true;
  6928. }
  6929. /// Tests to see if the LValue has a user-specified designator (that isn't
  6930. /// necessarily valid). Note that this always returns 'true' if the LValue has
  6931. /// an unsized array as its first designator entry, because there's currently no
  6932. /// way to tell if the user typed *foo or foo[0].
  6933. static bool refersToCompleteObject(const LValue &LVal) {
  6934. if (LVal.Designator.Invalid)
  6935. return false;
  6936. if (!LVal.Designator.Entries.empty())
  6937. return LVal.Designator.isMostDerivedAnUnsizedArray();
  6938. if (!LVal.InvalidBase)
  6939. return true;
  6940. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  6941. // the LValueBase.
  6942. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  6943. return !E || !isa<MemberExpr>(E);
  6944. }
  6945. /// Attempts to detect a user writing into a piece of memory that's impossible
  6946. /// to figure out the size of by just using types.
  6947. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  6948. const SubobjectDesignator &Designator = LVal.Designator;
  6949. // Notes:
  6950. // - Users can only write off of the end when we have an invalid base. Invalid
  6951. // bases imply we don't know where the memory came from.
  6952. // - We used to be a bit more aggressive here; we'd only be conservative if
  6953. // the array at the end was flexible, or if it had 0 or 1 elements. This
  6954. // broke some common standard library extensions (PR30346), but was
  6955. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  6956. // with some sort of whitelist. OTOH, it seems that GCC is always
  6957. // conservative with the last element in structs (if it's an array), so our
  6958. // current behavior is more compatible than a whitelisting approach would
  6959. // be.
  6960. return LVal.InvalidBase &&
  6961. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  6962. Designator.MostDerivedIsArrayElement &&
  6963. isDesignatorAtObjectEnd(Ctx, LVal);
  6964. }
  6965. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  6966. /// Fails if the conversion would cause loss of precision.
  6967. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  6968. CharUnits &Result) {
  6969. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  6970. if (Int.ugt(CharUnitsMax))
  6971. return false;
  6972. Result = CharUnits::fromQuantity(Int.getZExtValue());
  6973. return true;
  6974. }
  6975. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  6976. /// determine how many bytes exist from the beginning of the object to either
  6977. /// the end of the current subobject, or the end of the object itself, depending
  6978. /// on what the LValue looks like + the value of Type.
  6979. ///
  6980. /// If this returns false, the value of Result is undefined.
  6981. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  6982. unsigned Type, const LValue &LVal,
  6983. CharUnits &EndOffset) {
  6984. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  6985. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  6986. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  6987. return false;
  6988. return HandleSizeof(Info, ExprLoc, Ty, Result);
  6989. };
  6990. // We want to evaluate the size of the entire object. This is a valid fallback
  6991. // for when Type=1 and the designator is invalid, because we're asked for an
  6992. // upper-bound.
  6993. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  6994. // Type=3 wants a lower bound, so we can't fall back to this.
  6995. if (Type == 3 && !DetermineForCompleteObject)
  6996. return false;
  6997. llvm::APInt APEndOffset;
  6998. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  6999. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7000. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7001. if (LVal.InvalidBase)
  7002. return false;
  7003. QualType BaseTy = getObjectType(LVal.getLValueBase());
  7004. return CheckedHandleSizeof(BaseTy, EndOffset);
  7005. }
  7006. // We want to evaluate the size of a subobject.
  7007. const SubobjectDesignator &Designator = LVal.Designator;
  7008. // The following is a moderately common idiom in C:
  7009. //
  7010. // struct Foo { int a; char c[1]; };
  7011. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  7012. // strcpy(&F->c[0], Bar);
  7013. //
  7014. // In order to not break too much legacy code, we need to support it.
  7015. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  7016. // If we can resolve this to an alloc_size call, we can hand that back,
  7017. // because we know for certain how many bytes there are to write to.
  7018. llvm::APInt APEndOffset;
  7019. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7020. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7021. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7022. // If we cannot determine the size of the initial allocation, then we can't
  7023. // given an accurate upper-bound. However, we are still able to give
  7024. // conservative lower-bounds for Type=3.
  7025. if (Type == 1)
  7026. return false;
  7027. }
  7028. CharUnits BytesPerElem;
  7029. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  7030. return false;
  7031. // According to the GCC documentation, we want the size of the subobject
  7032. // denoted by the pointer. But that's not quite right -- what we actually
  7033. // want is the size of the immediately-enclosing array, if there is one.
  7034. int64_t ElemsRemaining;
  7035. if (Designator.MostDerivedIsArrayElement &&
  7036. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  7037. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  7038. uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
  7039. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  7040. } else {
  7041. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  7042. }
  7043. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  7044. return true;
  7045. }
  7046. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  7047. /// returns true and stores the result in @p Size.
  7048. ///
  7049. /// If @p WasError is non-null, this will report whether the failure to evaluate
  7050. /// is to be treated as an Error in IntExprEvaluator.
  7051. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  7052. EvalInfo &Info, uint64_t &Size) {
  7053. // Determine the denoted object.
  7054. LValue LVal;
  7055. {
  7056. // The operand of __builtin_object_size is never evaluated for side-effects.
  7057. // If there are any, but we can determine the pointed-to object anyway, then
  7058. // ignore the side-effects.
  7059. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7060. FoldOffsetRAII Fold(Info);
  7061. if (E->isGLValue()) {
  7062. // It's possible for us to be given GLValues if we're called via
  7063. // Expr::tryEvaluateObjectSize.
  7064. APValue RVal;
  7065. if (!EvaluateAsRValue(Info, E, RVal))
  7066. return false;
  7067. LVal.setFrom(Info.Ctx, RVal);
  7068. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  7069. /*InvalidBaseOK=*/true))
  7070. return false;
  7071. }
  7072. // If we point to before the start of the object, there are no accessible
  7073. // bytes.
  7074. if (LVal.getLValueOffset().isNegative()) {
  7075. Size = 0;
  7076. return true;
  7077. }
  7078. CharUnits EndOffset;
  7079. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  7080. return false;
  7081. // If we've fallen outside of the end offset, just pretend there's nothing to
  7082. // write to/read from.
  7083. if (EndOffset <= LVal.getLValueOffset())
  7084. Size = 0;
  7085. else
  7086. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  7087. return true;
  7088. }
  7089. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7090. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7091. return VisitBuiltinCallExpr(E, BuiltinOp);
  7092. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7093. }
  7094. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7095. unsigned BuiltinOp) {
  7096. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  7097. default:
  7098. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7099. case Builtin::BI__builtin_object_size: {
  7100. // The type was checked when we built the expression.
  7101. unsigned Type =
  7102. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7103. assert(Type <= 3 && "unexpected type");
  7104. uint64_t Size;
  7105. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  7106. return Success(Size, E);
  7107. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  7108. return Success((Type & 2) ? 0 : -1, E);
  7109. // Expression had no side effects, but we couldn't statically determine the
  7110. // size of the referenced object.
  7111. switch (Info.EvalMode) {
  7112. case EvalInfo::EM_ConstantExpression:
  7113. case EvalInfo::EM_PotentialConstantExpression:
  7114. case EvalInfo::EM_ConstantFold:
  7115. case EvalInfo::EM_EvaluateForOverflow:
  7116. case EvalInfo::EM_IgnoreSideEffects:
  7117. case EvalInfo::EM_OffsetFold:
  7118. // Leave it to IR generation.
  7119. return Error(E);
  7120. case EvalInfo::EM_ConstantExpressionUnevaluated:
  7121. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  7122. // Reduce it to a constant now.
  7123. return Success((Type & 2) ? 0 : -1, E);
  7124. }
  7125. llvm_unreachable("unexpected EvalMode");
  7126. }
  7127. case Builtin::BI__builtin_bswap16:
  7128. case Builtin::BI__builtin_bswap32:
  7129. case Builtin::BI__builtin_bswap64: {
  7130. APSInt Val;
  7131. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7132. return false;
  7133. return Success(Val.byteSwap(), E);
  7134. }
  7135. case Builtin::BI__builtin_classify_type:
  7136. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  7137. // FIXME: BI__builtin_clrsb
  7138. // FIXME: BI__builtin_clrsbl
  7139. // FIXME: BI__builtin_clrsbll
  7140. case Builtin::BI__builtin_clz:
  7141. case Builtin::BI__builtin_clzl:
  7142. case Builtin::BI__builtin_clzll:
  7143. case Builtin::BI__builtin_clzs: {
  7144. APSInt Val;
  7145. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7146. return false;
  7147. if (!Val)
  7148. return Error(E);
  7149. return Success(Val.countLeadingZeros(), E);
  7150. }
  7151. case Builtin::BI__builtin_constant_p:
  7152. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  7153. case Builtin::BI__builtin_ctz:
  7154. case Builtin::BI__builtin_ctzl:
  7155. case Builtin::BI__builtin_ctzll:
  7156. case Builtin::BI__builtin_ctzs: {
  7157. APSInt Val;
  7158. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7159. return false;
  7160. if (!Val)
  7161. return Error(E);
  7162. return Success(Val.countTrailingZeros(), E);
  7163. }
  7164. case Builtin::BI__builtin_eh_return_data_regno: {
  7165. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7166. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7167. return Success(Operand, E);
  7168. }
  7169. case Builtin::BI__builtin_expect:
  7170. return Visit(E->getArg(0));
  7171. case Builtin::BI__builtin_ffs:
  7172. case Builtin::BI__builtin_ffsl:
  7173. case Builtin::BI__builtin_ffsll: {
  7174. APSInt Val;
  7175. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7176. return false;
  7177. unsigned N = Val.countTrailingZeros();
  7178. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7179. }
  7180. case Builtin::BI__builtin_fpclassify: {
  7181. APFloat Val(0.0);
  7182. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7183. return false;
  7184. unsigned Arg;
  7185. switch (Val.getCategory()) {
  7186. case APFloat::fcNaN: Arg = 0; break;
  7187. case APFloat::fcInfinity: Arg = 1; break;
  7188. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7189. case APFloat::fcZero: Arg = 4; break;
  7190. }
  7191. return Visit(E->getArg(Arg));
  7192. }
  7193. case Builtin::BI__builtin_isinf_sign: {
  7194. APFloat Val(0.0);
  7195. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7196. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  7197. }
  7198. case Builtin::BI__builtin_isinf: {
  7199. APFloat Val(0.0);
  7200. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7201. Success(Val.isInfinity() ? 1 : 0, E);
  7202. }
  7203. case Builtin::BI__builtin_isfinite: {
  7204. APFloat Val(0.0);
  7205. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7206. Success(Val.isFinite() ? 1 : 0, E);
  7207. }
  7208. case Builtin::BI__builtin_isnan: {
  7209. APFloat Val(0.0);
  7210. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7211. Success(Val.isNaN() ? 1 : 0, E);
  7212. }
  7213. case Builtin::BI__builtin_isnormal: {
  7214. APFloat Val(0.0);
  7215. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7216. Success(Val.isNormal() ? 1 : 0, E);
  7217. }
  7218. case Builtin::BI__builtin_parity:
  7219. case Builtin::BI__builtin_parityl:
  7220. case Builtin::BI__builtin_parityll: {
  7221. APSInt Val;
  7222. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7223. return false;
  7224. return Success(Val.countPopulation() % 2, E);
  7225. }
  7226. case Builtin::BI__builtin_popcount:
  7227. case Builtin::BI__builtin_popcountl:
  7228. case Builtin::BI__builtin_popcountll: {
  7229. APSInt Val;
  7230. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7231. return false;
  7232. return Success(Val.countPopulation(), E);
  7233. }
  7234. case Builtin::BIstrlen:
  7235. case Builtin::BIwcslen:
  7236. // A call to strlen is not a constant expression.
  7237. if (Info.getLangOpts().CPlusPlus11)
  7238. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7239. << /*isConstexpr*/0 << /*isConstructor*/0
  7240. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7241. else
  7242. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7243. LLVM_FALLTHROUGH;
  7244. case Builtin::BI__builtin_strlen:
  7245. case Builtin::BI__builtin_wcslen: {
  7246. // As an extension, we support __builtin_strlen() as a constant expression,
  7247. // and support folding strlen() to a constant.
  7248. LValue String;
  7249. if (!EvaluatePointer(E->getArg(0), String, Info))
  7250. return false;
  7251. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7252. // Fast path: if it's a string literal, search the string value.
  7253. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  7254. String.getLValueBase().dyn_cast<const Expr *>())) {
  7255. // The string literal may have embedded null characters. Find the first
  7256. // one and truncate there.
  7257. StringRef Str = S->getBytes();
  7258. int64_t Off = String.Offset.getQuantity();
  7259. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  7260. S->getCharByteWidth() == 1 &&
  7261. // FIXME: Add fast-path for wchar_t too.
  7262. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  7263. Str = Str.substr(Off);
  7264. StringRef::size_type Pos = Str.find(0);
  7265. if (Pos != StringRef::npos)
  7266. Str = Str.substr(0, Pos);
  7267. return Success(Str.size(), E);
  7268. }
  7269. // Fall through to slow path to issue appropriate diagnostic.
  7270. }
  7271. // Slow path: scan the bytes of the string looking for the terminating 0.
  7272. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  7273. APValue Char;
  7274. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  7275. !Char.isInt())
  7276. return false;
  7277. if (!Char.getInt())
  7278. return Success(Strlen, E);
  7279. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  7280. return false;
  7281. }
  7282. }
  7283. case Builtin::BIstrcmp:
  7284. case Builtin::BIwcscmp:
  7285. case Builtin::BIstrncmp:
  7286. case Builtin::BIwcsncmp:
  7287. case Builtin::BImemcmp:
  7288. case Builtin::BIwmemcmp:
  7289. // A call to strlen is not a constant expression.
  7290. if (Info.getLangOpts().CPlusPlus11)
  7291. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7292. << /*isConstexpr*/0 << /*isConstructor*/0
  7293. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7294. else
  7295. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7296. LLVM_FALLTHROUGH;
  7297. case Builtin::BI__builtin_strcmp:
  7298. case Builtin::BI__builtin_wcscmp:
  7299. case Builtin::BI__builtin_strncmp:
  7300. case Builtin::BI__builtin_wcsncmp:
  7301. case Builtin::BI__builtin_memcmp:
  7302. case Builtin::BI__builtin_wmemcmp: {
  7303. LValue String1, String2;
  7304. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  7305. !EvaluatePointer(E->getArg(1), String2, Info))
  7306. return false;
  7307. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7308. uint64_t MaxLength = uint64_t(-1);
  7309. if (BuiltinOp != Builtin::BIstrcmp &&
  7310. BuiltinOp != Builtin::BIwcscmp &&
  7311. BuiltinOp != Builtin::BI__builtin_strcmp &&
  7312. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  7313. APSInt N;
  7314. if (!EvaluateInteger(E->getArg(2), N, Info))
  7315. return false;
  7316. MaxLength = N.getExtValue();
  7317. }
  7318. bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
  7319. BuiltinOp != Builtin::BIwmemcmp &&
  7320. BuiltinOp != Builtin::BI__builtin_memcmp &&
  7321. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  7322. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  7323. BuiltinOp == Builtin::BIwcsncmp ||
  7324. BuiltinOp == Builtin::BIwmemcmp ||
  7325. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  7326. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  7327. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  7328. for (; MaxLength; --MaxLength) {
  7329. APValue Char1, Char2;
  7330. if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
  7331. !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
  7332. !Char1.isInt() || !Char2.isInt())
  7333. return false;
  7334. if (Char1.getInt() != Char2.getInt()) {
  7335. if (IsWide) // wmemcmp compares with wchar_t signedness.
  7336. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  7337. // memcmp always compares unsigned chars.
  7338. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  7339. }
  7340. if (StopAtNull && !Char1.getInt())
  7341. return Success(0, E);
  7342. assert(!(StopAtNull && !Char2.getInt()));
  7343. if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
  7344. !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
  7345. return false;
  7346. }
  7347. // We hit the strncmp / memcmp limit.
  7348. return Success(0, E);
  7349. }
  7350. case Builtin::BI__atomic_always_lock_free:
  7351. case Builtin::BI__atomic_is_lock_free:
  7352. case Builtin::BI__c11_atomic_is_lock_free: {
  7353. APSInt SizeVal;
  7354. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  7355. return false;
  7356. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  7357. // of two less than the maximum inline atomic width, we know it is
  7358. // lock-free. If the size isn't a power of two, or greater than the
  7359. // maximum alignment where we promote atomics, we know it is not lock-free
  7360. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  7361. // the answer can only be determined at runtime; for example, 16-byte
  7362. // atomics have lock-free implementations on some, but not all,
  7363. // x86-64 processors.
  7364. // Check power-of-two.
  7365. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  7366. if (Size.isPowerOfTwo()) {
  7367. // Check against inlining width.
  7368. unsigned InlineWidthBits =
  7369. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  7370. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  7371. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  7372. Size == CharUnits::One() ||
  7373. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  7374. Expr::NPC_NeverValueDependent))
  7375. // OK, we will inline appropriately-aligned operations of this size,
  7376. // and _Atomic(T) is appropriately-aligned.
  7377. return Success(1, E);
  7378. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  7379. castAs<PointerType>()->getPointeeType();
  7380. if (!PointeeType->isIncompleteType() &&
  7381. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  7382. // OK, we will inline operations on this object.
  7383. return Success(1, E);
  7384. }
  7385. }
  7386. }
  7387. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  7388. Success(0, E) : Error(E);
  7389. }
  7390. case Builtin::BIomp_is_initial_device:
  7391. // We can decide statically which value the runtime would return if called.
  7392. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  7393. case Builtin::BI__builtin_add_overflow:
  7394. case Builtin::BI__builtin_sub_overflow:
  7395. case Builtin::BI__builtin_mul_overflow:
  7396. case Builtin::BI__builtin_sadd_overflow:
  7397. case Builtin::BI__builtin_uadd_overflow:
  7398. case Builtin::BI__builtin_uaddl_overflow:
  7399. case Builtin::BI__builtin_uaddll_overflow:
  7400. case Builtin::BI__builtin_usub_overflow:
  7401. case Builtin::BI__builtin_usubl_overflow:
  7402. case Builtin::BI__builtin_usubll_overflow:
  7403. case Builtin::BI__builtin_umul_overflow:
  7404. case Builtin::BI__builtin_umull_overflow:
  7405. case Builtin::BI__builtin_umulll_overflow:
  7406. case Builtin::BI__builtin_saddl_overflow:
  7407. case Builtin::BI__builtin_saddll_overflow:
  7408. case Builtin::BI__builtin_ssub_overflow:
  7409. case Builtin::BI__builtin_ssubl_overflow:
  7410. case Builtin::BI__builtin_ssubll_overflow:
  7411. case Builtin::BI__builtin_smul_overflow:
  7412. case Builtin::BI__builtin_smull_overflow:
  7413. case Builtin::BI__builtin_smulll_overflow: {
  7414. LValue ResultLValue;
  7415. APSInt LHS, RHS;
  7416. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  7417. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  7418. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  7419. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  7420. return false;
  7421. APSInt Result;
  7422. bool DidOverflow = false;
  7423. // If the types don't have to match, enlarge all 3 to the largest of them.
  7424. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7425. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7426. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7427. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  7428. ResultType->isSignedIntegerOrEnumerationType();
  7429. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  7430. ResultType->isSignedIntegerOrEnumerationType();
  7431. uint64_t LHSSize = LHS.getBitWidth();
  7432. uint64_t RHSSize = RHS.getBitWidth();
  7433. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  7434. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  7435. // Add an additional bit if the signedness isn't uniformly agreed to. We
  7436. // could do this ONLY if there is a signed and an unsigned that both have
  7437. // MaxBits, but the code to check that is pretty nasty. The issue will be
  7438. // caught in the shrink-to-result later anyway.
  7439. if (IsSigned && !AllSigned)
  7440. ++MaxBits;
  7441. LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
  7442. !IsSigned);
  7443. RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
  7444. !IsSigned);
  7445. Result = APSInt(MaxBits, !IsSigned);
  7446. }
  7447. // Find largest int.
  7448. switch (BuiltinOp) {
  7449. default:
  7450. llvm_unreachable("Invalid value for BuiltinOp");
  7451. case Builtin::BI__builtin_add_overflow:
  7452. case Builtin::BI__builtin_sadd_overflow:
  7453. case Builtin::BI__builtin_saddl_overflow:
  7454. case Builtin::BI__builtin_saddll_overflow:
  7455. case Builtin::BI__builtin_uadd_overflow:
  7456. case Builtin::BI__builtin_uaddl_overflow:
  7457. case Builtin::BI__builtin_uaddll_overflow:
  7458. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  7459. : LHS.uadd_ov(RHS, DidOverflow);
  7460. break;
  7461. case Builtin::BI__builtin_sub_overflow:
  7462. case Builtin::BI__builtin_ssub_overflow:
  7463. case Builtin::BI__builtin_ssubl_overflow:
  7464. case Builtin::BI__builtin_ssubll_overflow:
  7465. case Builtin::BI__builtin_usub_overflow:
  7466. case Builtin::BI__builtin_usubl_overflow:
  7467. case Builtin::BI__builtin_usubll_overflow:
  7468. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  7469. : LHS.usub_ov(RHS, DidOverflow);
  7470. break;
  7471. case Builtin::BI__builtin_mul_overflow:
  7472. case Builtin::BI__builtin_smul_overflow:
  7473. case Builtin::BI__builtin_smull_overflow:
  7474. case Builtin::BI__builtin_smulll_overflow:
  7475. case Builtin::BI__builtin_umul_overflow:
  7476. case Builtin::BI__builtin_umull_overflow:
  7477. case Builtin::BI__builtin_umulll_overflow:
  7478. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  7479. : LHS.umul_ov(RHS, DidOverflow);
  7480. break;
  7481. }
  7482. // In the case where multiple sizes are allowed, truncate and see if
  7483. // the values are the same.
  7484. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  7485. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  7486. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  7487. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  7488. // since it will give us the behavior of a TruncOrSelf in the case where
  7489. // its parameter <= its size. We previously set Result to be at least the
  7490. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  7491. // will work exactly like TruncOrSelf.
  7492. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  7493. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  7494. if (!APSInt::isSameValue(Temp, Result))
  7495. DidOverflow = true;
  7496. Result = Temp;
  7497. }
  7498. APValue APV{Result};
  7499. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  7500. return false;
  7501. return Success(DidOverflow, E);
  7502. }
  7503. }
  7504. }
  7505. /// Determine whether this is a pointer past the end of the complete
  7506. /// object referred to by the lvalue.
  7507. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  7508. const LValue &LV) {
  7509. // A null pointer can be viewed as being "past the end" but we don't
  7510. // choose to look at it that way here.
  7511. if (!LV.getLValueBase())
  7512. return false;
  7513. // If the designator is valid and refers to a subobject, we're not pointing
  7514. // past the end.
  7515. if (!LV.getLValueDesignator().Invalid &&
  7516. !LV.getLValueDesignator().isOnePastTheEnd())
  7517. return false;
  7518. // A pointer to an incomplete type might be past-the-end if the type's size is
  7519. // zero. We cannot tell because the type is incomplete.
  7520. QualType Ty = getType(LV.getLValueBase());
  7521. if (Ty->isIncompleteType())
  7522. return true;
  7523. // We're a past-the-end pointer if we point to the byte after the object,
  7524. // no matter what our type or path is.
  7525. auto Size = Ctx.getTypeSizeInChars(Ty);
  7526. return LV.getLValueOffset() == Size;
  7527. }
  7528. namespace {
  7529. /// Data recursive integer evaluator of certain binary operators.
  7530. ///
  7531. /// We use a data recursive algorithm for binary operators so that we are able
  7532. /// to handle extreme cases of chained binary operators without causing stack
  7533. /// overflow.
  7534. class DataRecursiveIntBinOpEvaluator {
  7535. struct EvalResult {
  7536. APValue Val;
  7537. bool Failed;
  7538. EvalResult() : Failed(false) { }
  7539. void swap(EvalResult &RHS) {
  7540. Val.swap(RHS.Val);
  7541. Failed = RHS.Failed;
  7542. RHS.Failed = false;
  7543. }
  7544. };
  7545. struct Job {
  7546. const Expr *E;
  7547. EvalResult LHSResult; // meaningful only for binary operator expression.
  7548. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  7549. Job() = default;
  7550. Job(Job &&) = default;
  7551. void startSpeculativeEval(EvalInfo &Info) {
  7552. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  7553. }
  7554. private:
  7555. SpeculativeEvaluationRAII SpecEvalRAII;
  7556. };
  7557. SmallVector<Job, 16> Queue;
  7558. IntExprEvaluator &IntEval;
  7559. EvalInfo &Info;
  7560. APValue &FinalResult;
  7561. public:
  7562. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  7563. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  7564. /// True if \param E is a binary operator that we are going to handle
  7565. /// data recursively.
  7566. /// We handle binary operators that are comma, logical, or that have operands
  7567. /// with integral or enumeration type.
  7568. static bool shouldEnqueue(const BinaryOperator *E) {
  7569. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  7570. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  7571. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7572. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7573. }
  7574. bool Traverse(const BinaryOperator *E) {
  7575. enqueue(E);
  7576. EvalResult PrevResult;
  7577. while (!Queue.empty())
  7578. process(PrevResult);
  7579. if (PrevResult.Failed) return false;
  7580. FinalResult.swap(PrevResult.Val);
  7581. return true;
  7582. }
  7583. private:
  7584. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7585. return IntEval.Success(Value, E, Result);
  7586. }
  7587. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  7588. return IntEval.Success(Value, E, Result);
  7589. }
  7590. bool Error(const Expr *E) {
  7591. return IntEval.Error(E);
  7592. }
  7593. bool Error(const Expr *E, diag::kind D) {
  7594. return IntEval.Error(E, D);
  7595. }
  7596. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  7597. return Info.CCEDiag(E, D);
  7598. }
  7599. // Returns true if visiting the RHS is necessary, false otherwise.
  7600. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7601. bool &SuppressRHSDiags);
  7602. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7603. const BinaryOperator *E, APValue &Result);
  7604. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  7605. Result.Failed = !Evaluate(Result.Val, Info, E);
  7606. if (Result.Failed)
  7607. Result.Val = APValue();
  7608. }
  7609. void process(EvalResult &Result);
  7610. void enqueue(const Expr *E) {
  7611. E = E->IgnoreParens();
  7612. Queue.resize(Queue.size()+1);
  7613. Queue.back().E = E;
  7614. Queue.back().Kind = Job::AnyExprKind;
  7615. }
  7616. };
  7617. }
  7618. bool DataRecursiveIntBinOpEvaluator::
  7619. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  7620. bool &SuppressRHSDiags) {
  7621. if (E->getOpcode() == BO_Comma) {
  7622. // Ignore LHS but note if we could not evaluate it.
  7623. if (LHSResult.Failed)
  7624. return Info.noteSideEffect();
  7625. return true;
  7626. }
  7627. if (E->isLogicalOp()) {
  7628. bool LHSAsBool;
  7629. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  7630. // We were able to evaluate the LHS, see if we can get away with not
  7631. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  7632. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  7633. Success(LHSAsBool, E, LHSResult.Val);
  7634. return false; // Ignore RHS
  7635. }
  7636. } else {
  7637. LHSResult.Failed = true;
  7638. // Since we weren't able to evaluate the left hand side, it
  7639. // might have had side effects.
  7640. if (!Info.noteSideEffect())
  7641. return false;
  7642. // We can't evaluate the LHS; however, sometimes the result
  7643. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7644. // Don't ignore RHS and suppress diagnostics from this arm.
  7645. SuppressRHSDiags = true;
  7646. }
  7647. return true;
  7648. }
  7649. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7650. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7651. if (LHSResult.Failed && !Info.noteFailure())
  7652. return false; // Ignore RHS;
  7653. return true;
  7654. }
  7655. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  7656. bool IsSub) {
  7657. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  7658. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  7659. // offsets.
  7660. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  7661. CharUnits &Offset = LVal.getLValueOffset();
  7662. uint64_t Offset64 = Offset.getQuantity();
  7663. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  7664. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  7665. : Offset64 + Index64);
  7666. }
  7667. bool DataRecursiveIntBinOpEvaluator::
  7668. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  7669. const BinaryOperator *E, APValue &Result) {
  7670. if (E->getOpcode() == BO_Comma) {
  7671. if (RHSResult.Failed)
  7672. return false;
  7673. Result = RHSResult.Val;
  7674. return true;
  7675. }
  7676. if (E->isLogicalOp()) {
  7677. bool lhsResult, rhsResult;
  7678. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  7679. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  7680. if (LHSIsOK) {
  7681. if (RHSIsOK) {
  7682. if (E->getOpcode() == BO_LOr)
  7683. return Success(lhsResult || rhsResult, E, Result);
  7684. else
  7685. return Success(lhsResult && rhsResult, E, Result);
  7686. }
  7687. } else {
  7688. if (RHSIsOK) {
  7689. // We can't evaluate the LHS; however, sometimes the result
  7690. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  7691. if (rhsResult == (E->getOpcode() == BO_LOr))
  7692. return Success(rhsResult, E, Result);
  7693. }
  7694. }
  7695. return false;
  7696. }
  7697. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  7698. E->getRHS()->getType()->isIntegralOrEnumerationType());
  7699. if (LHSResult.Failed || RHSResult.Failed)
  7700. return false;
  7701. const APValue &LHSVal = LHSResult.Val;
  7702. const APValue &RHSVal = RHSResult.Val;
  7703. // Handle cases like (unsigned long)&a + 4.
  7704. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  7705. Result = LHSVal;
  7706. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  7707. return true;
  7708. }
  7709. // Handle cases like 4 + (unsigned long)&a
  7710. if (E->getOpcode() == BO_Add &&
  7711. RHSVal.isLValue() && LHSVal.isInt()) {
  7712. Result = RHSVal;
  7713. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  7714. return true;
  7715. }
  7716. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  7717. // Handle (intptr_t)&&A - (intptr_t)&&B.
  7718. if (!LHSVal.getLValueOffset().isZero() ||
  7719. !RHSVal.getLValueOffset().isZero())
  7720. return false;
  7721. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  7722. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  7723. if (!LHSExpr || !RHSExpr)
  7724. return false;
  7725. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  7726. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  7727. if (!LHSAddrExpr || !RHSAddrExpr)
  7728. return false;
  7729. // Make sure both labels come from the same function.
  7730. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  7731. RHSAddrExpr->getLabel()->getDeclContext())
  7732. return false;
  7733. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  7734. return true;
  7735. }
  7736. // All the remaining cases expect both operands to be an integer
  7737. if (!LHSVal.isInt() || !RHSVal.isInt())
  7738. return Error(E);
  7739. // Set up the width and signedness manually, in case it can't be deduced
  7740. // from the operation we're performing.
  7741. // FIXME: Don't do this in the cases where we can deduce it.
  7742. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  7743. E->getType()->isUnsignedIntegerOrEnumerationType());
  7744. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  7745. RHSVal.getInt(), Value))
  7746. return false;
  7747. return Success(Value, E, Result);
  7748. }
  7749. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  7750. Job &job = Queue.back();
  7751. switch (job.Kind) {
  7752. case Job::AnyExprKind: {
  7753. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  7754. if (shouldEnqueue(Bop)) {
  7755. job.Kind = Job::BinOpKind;
  7756. enqueue(Bop->getLHS());
  7757. return;
  7758. }
  7759. }
  7760. EvaluateExpr(job.E, Result);
  7761. Queue.pop_back();
  7762. return;
  7763. }
  7764. case Job::BinOpKind: {
  7765. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7766. bool SuppressRHSDiags = false;
  7767. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  7768. Queue.pop_back();
  7769. return;
  7770. }
  7771. if (SuppressRHSDiags)
  7772. job.startSpeculativeEval(Info);
  7773. job.LHSResult.swap(Result);
  7774. job.Kind = Job::BinOpVisitedLHSKind;
  7775. enqueue(Bop->getRHS());
  7776. return;
  7777. }
  7778. case Job::BinOpVisitedLHSKind: {
  7779. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  7780. EvalResult RHS;
  7781. RHS.swap(Result);
  7782. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  7783. Queue.pop_back();
  7784. return;
  7785. }
  7786. }
  7787. llvm_unreachable("Invalid Job::Kind!");
  7788. }
  7789. namespace {
  7790. /// Used when we determine that we should fail, but can keep evaluating prior to
  7791. /// noting that we had a failure.
  7792. class DelayedNoteFailureRAII {
  7793. EvalInfo &Info;
  7794. bool NoteFailure;
  7795. public:
  7796. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  7797. : Info(Info), NoteFailure(NoteFailure) {}
  7798. ~DelayedNoteFailureRAII() {
  7799. if (NoteFailure) {
  7800. bool ContinueAfterFailure = Info.noteFailure();
  7801. (void)ContinueAfterFailure;
  7802. assert(ContinueAfterFailure &&
  7803. "Shouldn't have kept evaluating on failure.");
  7804. }
  7805. }
  7806. };
  7807. }
  7808. template <class SuccessCB, class AfterCB>
  7809. static bool
  7810. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  7811. SuccessCB &&Success, AfterCB &&DoAfter) {
  7812. assert(E->isComparisonOp() && "expected comparison operator");
  7813. assert((E->getOpcode() == BO_Cmp ||
  7814. E->getType()->isIntegralOrEnumerationType()) &&
  7815. "unsupported binary expression evaluation");
  7816. auto Error = [&](const Expr *E) {
  7817. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7818. return false;
  7819. };
  7820. using CCR = ComparisonCategoryResult;
  7821. bool IsRelational = E->isRelationalOp();
  7822. bool IsEquality = E->isEqualityOp();
  7823. if (E->getOpcode() == BO_Cmp) {
  7824. const ComparisonCategoryInfo &CmpInfo =
  7825. Info.Ctx.CompCategories.getInfoForType(E->getType());
  7826. IsRelational = CmpInfo.isOrdered();
  7827. IsEquality = CmpInfo.isEquality();
  7828. }
  7829. QualType LHSTy = E->getLHS()->getType();
  7830. QualType RHSTy = E->getRHS()->getType();
  7831. if (LHSTy->isIntegralOrEnumerationType() &&
  7832. RHSTy->isIntegralOrEnumerationType()) {
  7833. APSInt LHS, RHS;
  7834. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  7835. if (!LHSOK && !Info.noteFailure())
  7836. return false;
  7837. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  7838. return false;
  7839. if (LHS < RHS)
  7840. return Success(CCR::Less, E);
  7841. if (LHS > RHS)
  7842. return Success(CCR::Greater, E);
  7843. return Success(CCR::Equal, E);
  7844. }
  7845. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  7846. ComplexValue LHS, RHS;
  7847. bool LHSOK;
  7848. if (E->isAssignmentOp()) {
  7849. LValue LV;
  7850. EvaluateLValue(E->getLHS(), LV, Info);
  7851. LHSOK = false;
  7852. } else if (LHSTy->isRealFloatingType()) {
  7853. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  7854. if (LHSOK) {
  7855. LHS.makeComplexFloat();
  7856. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  7857. }
  7858. } else {
  7859. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  7860. }
  7861. if (!LHSOK && !Info.noteFailure())
  7862. return false;
  7863. if (E->getRHS()->getType()->isRealFloatingType()) {
  7864. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  7865. return false;
  7866. RHS.makeComplexFloat();
  7867. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  7868. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  7869. return false;
  7870. if (LHS.isComplexFloat()) {
  7871. APFloat::cmpResult CR_r =
  7872. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  7873. APFloat::cmpResult CR_i =
  7874. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  7875. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  7876. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7877. } else {
  7878. assert(IsEquality && "invalid complex comparison");
  7879. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  7880. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  7881. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  7882. }
  7883. }
  7884. if (LHSTy->isRealFloatingType() &&
  7885. RHSTy->isRealFloatingType()) {
  7886. APFloat RHS(0.0), LHS(0.0);
  7887. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  7888. if (!LHSOK && !Info.noteFailure())
  7889. return false;
  7890. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  7891. return false;
  7892. assert(E->isComparisonOp() && "Invalid binary operator!");
  7893. auto GetCmpRes = [&]() {
  7894. switch (LHS.compare(RHS)) {
  7895. case APFloat::cmpEqual:
  7896. return CCR::Equal;
  7897. case APFloat::cmpLessThan:
  7898. return CCR::Less;
  7899. case APFloat::cmpGreaterThan:
  7900. return CCR::Greater;
  7901. case APFloat::cmpUnordered:
  7902. return CCR::Unordered;
  7903. }
  7904. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  7905. };
  7906. return Success(GetCmpRes(), E);
  7907. }
  7908. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  7909. LValue LHSValue, RHSValue;
  7910. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  7911. if (!LHSOK && !Info.noteFailure())
  7912. return false;
  7913. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  7914. return false;
  7915. // Reject differing bases from the normal codepath; we special-case
  7916. // comparisons to null.
  7917. if (!HasSameBase(LHSValue, RHSValue)) {
  7918. // Inequalities and subtractions between unrelated pointers have
  7919. // unspecified or undefined behavior.
  7920. if (!IsEquality)
  7921. return Error(E);
  7922. // A constant address may compare equal to the address of a symbol.
  7923. // The one exception is that address of an object cannot compare equal
  7924. // to a null pointer constant.
  7925. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  7926. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  7927. return Error(E);
  7928. // It's implementation-defined whether distinct literals will have
  7929. // distinct addresses. In clang, the result of such a comparison is
  7930. // unspecified, so it is not a constant expression. However, we do know
  7931. // that the address of a literal will be non-null.
  7932. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  7933. LHSValue.Base && RHSValue.Base)
  7934. return Error(E);
  7935. // We can't tell whether weak symbols will end up pointing to the same
  7936. // object.
  7937. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  7938. return Error(E);
  7939. // We can't compare the address of the start of one object with the
  7940. // past-the-end address of another object, per C++ DR1652.
  7941. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  7942. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  7943. (RHSValue.Base && RHSValue.Offset.isZero() &&
  7944. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  7945. return Error(E);
  7946. // We can't tell whether an object is at the same address as another
  7947. // zero sized object.
  7948. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  7949. (LHSValue.Base && isZeroSized(RHSValue)))
  7950. return Error(E);
  7951. return Success(CCR::Nonequal, E);
  7952. }
  7953. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  7954. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  7955. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  7956. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  7957. // C++11 [expr.rel]p3:
  7958. // Pointers to void (after pointer conversions) can be compared, with a
  7959. // result defined as follows: If both pointers represent the same
  7960. // address or are both the null pointer value, the result is true if the
  7961. // operator is <= or >= and false otherwise; otherwise the result is
  7962. // unspecified.
  7963. // We interpret this as applying to pointers to *cv* void.
  7964. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  7965. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  7966. // C++11 [expr.rel]p2:
  7967. // - If two pointers point to non-static data members of the same object,
  7968. // or to subobjects or array elements fo such members, recursively, the
  7969. // pointer to the later declared member compares greater provided the
  7970. // two members have the same access control and provided their class is
  7971. // not a union.
  7972. // [...]
  7973. // - Otherwise pointer comparisons are unspecified.
  7974. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  7975. bool WasArrayIndex;
  7976. unsigned Mismatch = FindDesignatorMismatch(
  7977. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  7978. // At the point where the designators diverge, the comparison has a
  7979. // specified value if:
  7980. // - we are comparing array indices
  7981. // - we are comparing fields of a union, or fields with the same access
  7982. // Otherwise, the result is unspecified and thus the comparison is not a
  7983. // constant expression.
  7984. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  7985. Mismatch < RHSDesignator.Entries.size()) {
  7986. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  7987. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  7988. if (!LF && !RF)
  7989. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  7990. else if (!LF)
  7991. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  7992. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  7993. << RF->getParent() << RF;
  7994. else if (!RF)
  7995. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  7996. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  7997. << LF->getParent() << LF;
  7998. else if (!LF->getParent()->isUnion() &&
  7999. LF->getAccess() != RF->getAccess())
  8000. Info.CCEDiag(E,
  8001. diag::note_constexpr_pointer_comparison_differing_access)
  8002. << LF << LF->getAccess() << RF << RF->getAccess()
  8003. << LF->getParent();
  8004. }
  8005. }
  8006. // The comparison here must be unsigned, and performed with the same
  8007. // width as the pointer.
  8008. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  8009. uint64_t CompareLHS = LHSOffset.getQuantity();
  8010. uint64_t CompareRHS = RHSOffset.getQuantity();
  8011. assert(PtrSize <= 64 && "Unexpected pointer width");
  8012. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  8013. CompareLHS &= Mask;
  8014. CompareRHS &= Mask;
  8015. // If there is a base and this is a relational operator, we can only
  8016. // compare pointers within the object in question; otherwise, the result
  8017. // depends on where the object is located in memory.
  8018. if (!LHSValue.Base.isNull() && IsRelational) {
  8019. QualType BaseTy = getType(LHSValue.Base);
  8020. if (BaseTy->isIncompleteType())
  8021. return Error(E);
  8022. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  8023. uint64_t OffsetLimit = Size.getQuantity();
  8024. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  8025. return Error(E);
  8026. }
  8027. if (CompareLHS < CompareRHS)
  8028. return Success(CCR::Less, E);
  8029. if (CompareLHS > CompareRHS)
  8030. return Success(CCR::Greater, E);
  8031. return Success(CCR::Equal, E);
  8032. }
  8033. if (LHSTy->isMemberPointerType()) {
  8034. assert(IsEquality && "unexpected member pointer operation");
  8035. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  8036. MemberPtr LHSValue, RHSValue;
  8037. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  8038. if (!LHSOK && !Info.noteFailure())
  8039. return false;
  8040. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8041. return false;
  8042. // C++11 [expr.eq]p2:
  8043. // If both operands are null, they compare equal. Otherwise if only one is
  8044. // null, they compare unequal.
  8045. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  8046. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  8047. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8048. }
  8049. // Otherwise if either is a pointer to a virtual member function, the
  8050. // result is unspecified.
  8051. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  8052. if (MD->isVirtual())
  8053. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8054. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  8055. if (MD->isVirtual())
  8056. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8057. // Otherwise they compare equal if and only if they would refer to the
  8058. // same member of the same most derived object or the same subobject if
  8059. // they were dereferenced with a hypothetical object of the associated
  8060. // class type.
  8061. bool Equal = LHSValue == RHSValue;
  8062. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8063. }
  8064. if (LHSTy->isNullPtrType()) {
  8065. assert(E->isComparisonOp() && "unexpected nullptr operation");
  8066. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  8067. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  8068. // are compared, the result is true of the operator is <=, >= or ==, and
  8069. // false otherwise.
  8070. return Success(CCR::Equal, E);
  8071. }
  8072. return DoAfter();
  8073. }
  8074. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  8075. if (!CheckLiteralType(Info, E))
  8076. return false;
  8077. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8078. const BinaryOperator *E) {
  8079. // Evaluation succeeded. Lookup the information for the comparison category
  8080. // type and fetch the VarDecl for the result.
  8081. const ComparisonCategoryInfo &CmpInfo =
  8082. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8083. const VarDecl *VD =
  8084. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  8085. // Check and evaluate the result as a constant expression.
  8086. LValue LV;
  8087. LV.set(VD);
  8088. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8089. return false;
  8090. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8091. };
  8092. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8093. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  8094. });
  8095. }
  8096. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8097. // We don't call noteFailure immediately because the assignment happens after
  8098. // we evaluate LHS and RHS.
  8099. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  8100. return Error(E);
  8101. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  8102. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  8103. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  8104. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  8105. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  8106. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  8107. if (E->isComparisonOp()) {
  8108. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  8109. // comparisons and then translating the result.
  8110. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8111. const BinaryOperator *E) {
  8112. using CCR = ComparisonCategoryResult;
  8113. bool IsEqual = ResKind == CCR::Equal,
  8114. IsLess = ResKind == CCR::Less,
  8115. IsGreater = ResKind == CCR::Greater;
  8116. auto Op = E->getOpcode();
  8117. switch (Op) {
  8118. default:
  8119. llvm_unreachable("unsupported binary operator");
  8120. case BO_EQ:
  8121. case BO_NE:
  8122. return Success(IsEqual == (Op == BO_EQ), E);
  8123. case BO_LT: return Success(IsLess, E);
  8124. case BO_GT: return Success(IsGreater, E);
  8125. case BO_LE: return Success(IsEqual || IsLess, E);
  8126. case BO_GE: return Success(IsEqual || IsGreater, E);
  8127. }
  8128. };
  8129. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8130. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8131. });
  8132. }
  8133. QualType LHSTy = E->getLHS()->getType();
  8134. QualType RHSTy = E->getRHS()->getType();
  8135. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  8136. E->getOpcode() == BO_Sub) {
  8137. LValue LHSValue, RHSValue;
  8138. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8139. if (!LHSOK && !Info.noteFailure())
  8140. return false;
  8141. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8142. return false;
  8143. // Reject differing bases from the normal codepath; we special-case
  8144. // comparisons to null.
  8145. if (!HasSameBase(LHSValue, RHSValue)) {
  8146. // Handle &&A - &&B.
  8147. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  8148. return Error(E);
  8149. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  8150. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  8151. if (!LHSExpr || !RHSExpr)
  8152. return Error(E);
  8153. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8154. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8155. if (!LHSAddrExpr || !RHSAddrExpr)
  8156. return Error(E);
  8157. // Make sure both labels come from the same function.
  8158. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8159. RHSAddrExpr->getLabel()->getDeclContext())
  8160. return Error(E);
  8161. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  8162. }
  8163. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8164. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8165. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8166. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8167. // C++11 [expr.add]p6:
  8168. // Unless both pointers point to elements of the same array object, or
  8169. // one past the last element of the array object, the behavior is
  8170. // undefined.
  8171. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  8172. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  8173. RHSDesignator))
  8174. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  8175. QualType Type = E->getLHS()->getType();
  8176. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  8177. CharUnits ElementSize;
  8178. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  8179. return false;
  8180. // As an extension, a type may have zero size (empty struct or union in
  8181. // C, array of zero length). Pointer subtraction in such cases has
  8182. // undefined behavior, so is not constant.
  8183. if (ElementSize.isZero()) {
  8184. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  8185. << ElementType;
  8186. return false;
  8187. }
  8188. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  8189. // and produce incorrect results when it overflows. Such behavior
  8190. // appears to be non-conforming, but is common, so perhaps we should
  8191. // assume the standard intended for such cases to be undefined behavior
  8192. // and check for them.
  8193. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  8194. // overflow in the final conversion to ptrdiff_t.
  8195. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  8196. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  8197. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  8198. false);
  8199. APSInt TrueResult = (LHS - RHS) / ElemSize;
  8200. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  8201. if (Result.extend(65) != TrueResult &&
  8202. !HandleOverflow(Info, E, TrueResult, E->getType()))
  8203. return false;
  8204. return Success(Result, E);
  8205. }
  8206. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8207. }
  8208. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  8209. /// a result as the expression's type.
  8210. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  8211. const UnaryExprOrTypeTraitExpr *E) {
  8212. switch(E->getKind()) {
  8213. case UETT_AlignOf: {
  8214. if (E->isArgumentType())
  8215. return Success(GetAlignOfType(Info, E->getArgumentType()), E);
  8216. else
  8217. return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
  8218. }
  8219. case UETT_VecStep: {
  8220. QualType Ty = E->getTypeOfArgument();
  8221. if (Ty->isVectorType()) {
  8222. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  8223. // The vec_step built-in functions that take a 3-component
  8224. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  8225. if (n == 3)
  8226. n = 4;
  8227. return Success(n, E);
  8228. } else
  8229. return Success(1, E);
  8230. }
  8231. case UETT_SizeOf: {
  8232. QualType SrcTy = E->getTypeOfArgument();
  8233. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  8234. // the result is the size of the referenced type."
  8235. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  8236. SrcTy = Ref->getPointeeType();
  8237. CharUnits Sizeof;
  8238. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  8239. return false;
  8240. return Success(Sizeof, E);
  8241. }
  8242. case UETT_OpenMPRequiredSimdAlign:
  8243. assert(E->isArgumentType());
  8244. return Success(
  8245. Info.Ctx.toCharUnitsFromBits(
  8246. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  8247. .getQuantity(),
  8248. E);
  8249. }
  8250. llvm_unreachable("unknown expr/type trait");
  8251. }
  8252. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  8253. CharUnits Result;
  8254. unsigned n = OOE->getNumComponents();
  8255. if (n == 0)
  8256. return Error(OOE);
  8257. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  8258. for (unsigned i = 0; i != n; ++i) {
  8259. OffsetOfNode ON = OOE->getComponent(i);
  8260. switch (ON.getKind()) {
  8261. case OffsetOfNode::Array: {
  8262. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  8263. APSInt IdxResult;
  8264. if (!EvaluateInteger(Idx, IdxResult, Info))
  8265. return false;
  8266. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  8267. if (!AT)
  8268. return Error(OOE);
  8269. CurrentType = AT->getElementType();
  8270. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  8271. Result += IdxResult.getSExtValue() * ElementSize;
  8272. break;
  8273. }
  8274. case OffsetOfNode::Field: {
  8275. FieldDecl *MemberDecl = ON.getField();
  8276. const RecordType *RT = CurrentType->getAs<RecordType>();
  8277. if (!RT)
  8278. return Error(OOE);
  8279. RecordDecl *RD = RT->getDecl();
  8280. if (RD->isInvalidDecl()) return false;
  8281. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8282. unsigned i = MemberDecl->getFieldIndex();
  8283. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  8284. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  8285. CurrentType = MemberDecl->getType().getNonReferenceType();
  8286. break;
  8287. }
  8288. case OffsetOfNode::Identifier:
  8289. llvm_unreachable("dependent __builtin_offsetof");
  8290. case OffsetOfNode::Base: {
  8291. CXXBaseSpecifier *BaseSpec = ON.getBase();
  8292. if (BaseSpec->isVirtual())
  8293. return Error(OOE);
  8294. // Find the layout of the class whose base we are looking into.
  8295. const RecordType *RT = CurrentType->getAs<RecordType>();
  8296. if (!RT)
  8297. return Error(OOE);
  8298. RecordDecl *RD = RT->getDecl();
  8299. if (RD->isInvalidDecl()) return false;
  8300. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8301. // Find the base class itself.
  8302. CurrentType = BaseSpec->getType();
  8303. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  8304. if (!BaseRT)
  8305. return Error(OOE);
  8306. // Add the offset to the base.
  8307. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  8308. break;
  8309. }
  8310. }
  8311. }
  8312. return Success(Result, OOE);
  8313. }
  8314. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8315. switch (E->getOpcode()) {
  8316. default:
  8317. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  8318. // See C99 6.6p3.
  8319. return Error(E);
  8320. case UO_Extension:
  8321. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  8322. // If so, we could clear the diagnostic ID.
  8323. return Visit(E->getSubExpr());
  8324. case UO_Plus:
  8325. // The result is just the value.
  8326. return Visit(E->getSubExpr());
  8327. case UO_Minus: {
  8328. if (!Visit(E->getSubExpr()))
  8329. return false;
  8330. if (!Result.isInt()) return Error(E);
  8331. const APSInt &Value = Result.getInt();
  8332. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  8333. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  8334. E->getType()))
  8335. return false;
  8336. return Success(-Value, E);
  8337. }
  8338. case UO_Not: {
  8339. if (!Visit(E->getSubExpr()))
  8340. return false;
  8341. if (!Result.isInt()) return Error(E);
  8342. return Success(~Result.getInt(), E);
  8343. }
  8344. case UO_LNot: {
  8345. bool bres;
  8346. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8347. return false;
  8348. return Success(!bres, E);
  8349. }
  8350. }
  8351. }
  8352. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  8353. /// result type is integer.
  8354. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8355. const Expr *SubExpr = E->getSubExpr();
  8356. QualType DestType = E->getType();
  8357. QualType SrcType = SubExpr->getType();
  8358. switch (E->getCastKind()) {
  8359. case CK_BaseToDerived:
  8360. case CK_DerivedToBase:
  8361. case CK_UncheckedDerivedToBase:
  8362. case CK_Dynamic:
  8363. case CK_ToUnion:
  8364. case CK_ArrayToPointerDecay:
  8365. case CK_FunctionToPointerDecay:
  8366. case CK_NullToPointer:
  8367. case CK_NullToMemberPointer:
  8368. case CK_BaseToDerivedMemberPointer:
  8369. case CK_DerivedToBaseMemberPointer:
  8370. case CK_ReinterpretMemberPointer:
  8371. case CK_ConstructorConversion:
  8372. case CK_IntegralToPointer:
  8373. case CK_ToVoid:
  8374. case CK_VectorSplat:
  8375. case CK_IntegralToFloating:
  8376. case CK_FloatingCast:
  8377. case CK_CPointerToObjCPointerCast:
  8378. case CK_BlockPointerToObjCPointerCast:
  8379. case CK_AnyPointerToBlockPointerCast:
  8380. case CK_ObjCObjectLValueCast:
  8381. case CK_FloatingRealToComplex:
  8382. case CK_FloatingComplexToReal:
  8383. case CK_FloatingComplexCast:
  8384. case CK_FloatingComplexToIntegralComplex:
  8385. case CK_IntegralRealToComplex:
  8386. case CK_IntegralComplexCast:
  8387. case CK_IntegralComplexToFloatingComplex:
  8388. case CK_BuiltinFnToFnPtr:
  8389. case CK_ZeroToOCLEvent:
  8390. case CK_ZeroToOCLQueue:
  8391. case CK_NonAtomicToAtomic:
  8392. case CK_AddressSpaceConversion:
  8393. case CK_IntToOCLSampler:
  8394. llvm_unreachable("invalid cast kind for integral value");
  8395. case CK_BitCast:
  8396. case CK_Dependent:
  8397. case CK_LValueBitCast:
  8398. case CK_ARCProduceObject:
  8399. case CK_ARCConsumeObject:
  8400. case CK_ARCReclaimReturnedObject:
  8401. case CK_ARCExtendBlockObject:
  8402. case CK_CopyAndAutoreleaseBlockObject:
  8403. return Error(E);
  8404. case CK_UserDefinedConversion:
  8405. case CK_LValueToRValue:
  8406. case CK_AtomicToNonAtomic:
  8407. case CK_NoOp:
  8408. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8409. case CK_MemberPointerToBoolean:
  8410. case CK_PointerToBoolean:
  8411. case CK_IntegralToBoolean:
  8412. case CK_FloatingToBoolean:
  8413. case CK_BooleanToSignedIntegral:
  8414. case CK_FloatingComplexToBoolean:
  8415. case CK_IntegralComplexToBoolean: {
  8416. bool BoolResult;
  8417. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  8418. return false;
  8419. uint64_t IntResult = BoolResult;
  8420. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  8421. IntResult = (uint64_t)-1;
  8422. return Success(IntResult, E);
  8423. }
  8424. case CK_IntegralCast: {
  8425. if (!Visit(SubExpr))
  8426. return false;
  8427. if (!Result.isInt()) {
  8428. // Allow casts of address-of-label differences if they are no-ops
  8429. // or narrowing. (The narrowing case isn't actually guaranteed to
  8430. // be constant-evaluatable except in some narrow cases which are hard
  8431. // to detect here. We let it through on the assumption the user knows
  8432. // what they are doing.)
  8433. if (Result.isAddrLabelDiff())
  8434. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  8435. // Only allow casts of lvalues if they are lossless.
  8436. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  8437. }
  8438. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  8439. Result.getInt()), E);
  8440. }
  8441. case CK_PointerToIntegral: {
  8442. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  8443. LValue LV;
  8444. if (!EvaluatePointer(SubExpr, LV, Info))
  8445. return false;
  8446. if (LV.getLValueBase()) {
  8447. // Only allow based lvalue casts if they are lossless.
  8448. // FIXME: Allow a larger integer size than the pointer size, and allow
  8449. // narrowing back down to pointer width in subsequent integral casts.
  8450. // FIXME: Check integer type's active bits, not its type size.
  8451. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  8452. return Error(E);
  8453. LV.Designator.setInvalid();
  8454. LV.moveInto(Result);
  8455. return true;
  8456. }
  8457. uint64_t V;
  8458. if (LV.isNullPointer())
  8459. V = Info.Ctx.getTargetNullPointerValue(SrcType);
  8460. else
  8461. V = LV.getLValueOffset().getQuantity();
  8462. APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
  8463. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  8464. }
  8465. case CK_IntegralComplexToReal: {
  8466. ComplexValue C;
  8467. if (!EvaluateComplex(SubExpr, C, Info))
  8468. return false;
  8469. return Success(C.getComplexIntReal(), E);
  8470. }
  8471. case CK_FloatingToIntegral: {
  8472. APFloat F(0.0);
  8473. if (!EvaluateFloat(SubExpr, F, Info))
  8474. return false;
  8475. APSInt Value;
  8476. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  8477. return false;
  8478. return Success(Value, E);
  8479. }
  8480. }
  8481. llvm_unreachable("unknown cast resulting in integral value");
  8482. }
  8483. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8484. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8485. ComplexValue LV;
  8486. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8487. return false;
  8488. if (!LV.isComplexInt())
  8489. return Error(E);
  8490. return Success(LV.getComplexIntReal(), E);
  8491. }
  8492. return Visit(E->getSubExpr());
  8493. }
  8494. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8495. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  8496. ComplexValue LV;
  8497. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  8498. return false;
  8499. if (!LV.isComplexInt())
  8500. return Error(E);
  8501. return Success(LV.getComplexIntImag(), E);
  8502. }
  8503. VisitIgnoredValue(E->getSubExpr());
  8504. return Success(0, E);
  8505. }
  8506. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  8507. return Success(E->getPackLength(), E);
  8508. }
  8509. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  8510. return Success(E->getValue(), E);
  8511. }
  8512. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8513. switch (E->getOpcode()) {
  8514. default:
  8515. // Invalid unary operators
  8516. return Error(E);
  8517. case UO_Plus:
  8518. // The result is just the value.
  8519. return Visit(E->getSubExpr());
  8520. case UO_Minus: {
  8521. if (!Visit(E->getSubExpr())) return false;
  8522. if (!Result.isInt()) return Error(E);
  8523. const APSInt &Value = Result.getInt();
  8524. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
  8525. SmallString<64> S;
  8526. FixedPointValueToString(S, Value,
  8527. Info.Ctx.getTypeInfo(E->getType()).Width);
  8528. Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
  8529. if (Info.noteUndefinedBehavior()) return false;
  8530. }
  8531. return Success(-Value, E);
  8532. }
  8533. case UO_LNot: {
  8534. bool bres;
  8535. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  8536. return false;
  8537. return Success(!bres, E);
  8538. }
  8539. }
  8540. }
  8541. //===----------------------------------------------------------------------===//
  8542. // Float Evaluation
  8543. //===----------------------------------------------------------------------===//
  8544. namespace {
  8545. class FloatExprEvaluator
  8546. : public ExprEvaluatorBase<FloatExprEvaluator> {
  8547. APFloat &Result;
  8548. public:
  8549. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  8550. : ExprEvaluatorBaseTy(info), Result(result) {}
  8551. bool Success(const APValue &V, const Expr *e) {
  8552. Result = V.getFloat();
  8553. return true;
  8554. }
  8555. bool ZeroInitialization(const Expr *E) {
  8556. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  8557. return true;
  8558. }
  8559. bool VisitCallExpr(const CallExpr *E);
  8560. bool VisitUnaryOperator(const UnaryOperator *E);
  8561. bool VisitBinaryOperator(const BinaryOperator *E);
  8562. bool VisitFloatingLiteral(const FloatingLiteral *E);
  8563. bool VisitCastExpr(const CastExpr *E);
  8564. bool VisitUnaryReal(const UnaryOperator *E);
  8565. bool VisitUnaryImag(const UnaryOperator *E);
  8566. // FIXME: Missing: array subscript of vector, member of vector
  8567. };
  8568. } // end anonymous namespace
  8569. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  8570. assert(E->isRValue() && E->getType()->isRealFloatingType());
  8571. return FloatExprEvaluator(Info, Result).Visit(E);
  8572. }
  8573. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  8574. QualType ResultTy,
  8575. const Expr *Arg,
  8576. bool SNaN,
  8577. llvm::APFloat &Result) {
  8578. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  8579. if (!S) return false;
  8580. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  8581. llvm::APInt fill;
  8582. // Treat empty strings as if they were zero.
  8583. if (S->getString().empty())
  8584. fill = llvm::APInt(32, 0);
  8585. else if (S->getString().getAsInteger(0, fill))
  8586. return false;
  8587. if (Context.getTargetInfo().isNan2008()) {
  8588. if (SNaN)
  8589. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8590. else
  8591. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8592. } else {
  8593. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  8594. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  8595. // a different encoding to what became a standard in 2008, and for pre-
  8596. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  8597. // sNaN. This is now known as "legacy NaN" encoding.
  8598. if (SNaN)
  8599. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  8600. else
  8601. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  8602. }
  8603. return true;
  8604. }
  8605. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  8606. switch (E->getBuiltinCallee()) {
  8607. default:
  8608. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  8609. case Builtin::BI__builtin_huge_val:
  8610. case Builtin::BI__builtin_huge_valf:
  8611. case Builtin::BI__builtin_huge_vall:
  8612. case Builtin::BI__builtin_huge_valf128:
  8613. case Builtin::BI__builtin_inf:
  8614. case Builtin::BI__builtin_inff:
  8615. case Builtin::BI__builtin_infl:
  8616. case Builtin::BI__builtin_inff128: {
  8617. const llvm::fltSemantics &Sem =
  8618. Info.Ctx.getFloatTypeSemantics(E->getType());
  8619. Result = llvm::APFloat::getInf(Sem);
  8620. return true;
  8621. }
  8622. case Builtin::BI__builtin_nans:
  8623. case Builtin::BI__builtin_nansf:
  8624. case Builtin::BI__builtin_nansl:
  8625. case Builtin::BI__builtin_nansf128:
  8626. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8627. true, Result))
  8628. return Error(E);
  8629. return true;
  8630. case Builtin::BI__builtin_nan:
  8631. case Builtin::BI__builtin_nanf:
  8632. case Builtin::BI__builtin_nanl:
  8633. case Builtin::BI__builtin_nanf128:
  8634. // If this is __builtin_nan() turn this into a nan, otherwise we
  8635. // can't constant fold it.
  8636. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  8637. false, Result))
  8638. return Error(E);
  8639. return true;
  8640. case Builtin::BI__builtin_fabs:
  8641. case Builtin::BI__builtin_fabsf:
  8642. case Builtin::BI__builtin_fabsl:
  8643. case Builtin::BI__builtin_fabsf128:
  8644. if (!EvaluateFloat(E->getArg(0), Result, Info))
  8645. return false;
  8646. if (Result.isNegative())
  8647. Result.changeSign();
  8648. return true;
  8649. // FIXME: Builtin::BI__builtin_powi
  8650. // FIXME: Builtin::BI__builtin_powif
  8651. // FIXME: Builtin::BI__builtin_powil
  8652. case Builtin::BI__builtin_copysign:
  8653. case Builtin::BI__builtin_copysignf:
  8654. case Builtin::BI__builtin_copysignl:
  8655. case Builtin::BI__builtin_copysignf128: {
  8656. APFloat RHS(0.);
  8657. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  8658. !EvaluateFloat(E->getArg(1), RHS, Info))
  8659. return false;
  8660. Result.copySign(RHS);
  8661. return true;
  8662. }
  8663. }
  8664. }
  8665. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  8666. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8667. ComplexValue CV;
  8668. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8669. return false;
  8670. Result = CV.FloatReal;
  8671. return true;
  8672. }
  8673. return Visit(E->getSubExpr());
  8674. }
  8675. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  8676. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  8677. ComplexValue CV;
  8678. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  8679. return false;
  8680. Result = CV.FloatImag;
  8681. return true;
  8682. }
  8683. VisitIgnoredValue(E->getSubExpr());
  8684. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  8685. Result = llvm::APFloat::getZero(Sem);
  8686. return true;
  8687. }
  8688. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8689. switch (E->getOpcode()) {
  8690. default: return Error(E);
  8691. case UO_Plus:
  8692. return EvaluateFloat(E->getSubExpr(), Result, Info);
  8693. case UO_Minus:
  8694. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  8695. return false;
  8696. Result.changeSign();
  8697. return true;
  8698. }
  8699. }
  8700. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8701. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8702. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8703. APFloat RHS(0.0);
  8704. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  8705. if (!LHSOK && !Info.noteFailure())
  8706. return false;
  8707. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  8708. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  8709. }
  8710. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  8711. Result = E->getValue();
  8712. return true;
  8713. }
  8714. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8715. const Expr* SubExpr = E->getSubExpr();
  8716. switch (E->getCastKind()) {
  8717. default:
  8718. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8719. case CK_IntegralToFloating: {
  8720. APSInt IntResult;
  8721. return EvaluateInteger(SubExpr, IntResult, Info) &&
  8722. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  8723. E->getType(), Result);
  8724. }
  8725. case CK_FloatingCast: {
  8726. if (!Visit(SubExpr))
  8727. return false;
  8728. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  8729. Result);
  8730. }
  8731. case CK_FloatingComplexToReal: {
  8732. ComplexValue V;
  8733. if (!EvaluateComplex(SubExpr, V, Info))
  8734. return false;
  8735. Result = V.getComplexFloatReal();
  8736. return true;
  8737. }
  8738. }
  8739. }
  8740. //===----------------------------------------------------------------------===//
  8741. // Complex Evaluation (for float and integer)
  8742. //===----------------------------------------------------------------------===//
  8743. namespace {
  8744. class ComplexExprEvaluator
  8745. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  8746. ComplexValue &Result;
  8747. public:
  8748. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  8749. : ExprEvaluatorBaseTy(info), Result(Result) {}
  8750. bool Success(const APValue &V, const Expr *e) {
  8751. Result.setFrom(V);
  8752. return true;
  8753. }
  8754. bool ZeroInitialization(const Expr *E);
  8755. //===--------------------------------------------------------------------===//
  8756. // Visitor Methods
  8757. //===--------------------------------------------------------------------===//
  8758. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  8759. bool VisitCastExpr(const CastExpr *E);
  8760. bool VisitBinaryOperator(const BinaryOperator *E);
  8761. bool VisitUnaryOperator(const UnaryOperator *E);
  8762. bool VisitInitListExpr(const InitListExpr *E);
  8763. };
  8764. } // end anonymous namespace
  8765. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  8766. EvalInfo &Info) {
  8767. assert(E->isRValue() && E->getType()->isAnyComplexType());
  8768. return ComplexExprEvaluator(Info, Result).Visit(E);
  8769. }
  8770. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  8771. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  8772. if (ElemTy->isRealFloatingType()) {
  8773. Result.makeComplexFloat();
  8774. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  8775. Result.FloatReal = Zero;
  8776. Result.FloatImag = Zero;
  8777. } else {
  8778. Result.makeComplexInt();
  8779. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  8780. Result.IntReal = Zero;
  8781. Result.IntImag = Zero;
  8782. }
  8783. return true;
  8784. }
  8785. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  8786. const Expr* SubExpr = E->getSubExpr();
  8787. if (SubExpr->getType()->isRealFloatingType()) {
  8788. Result.makeComplexFloat();
  8789. APFloat &Imag = Result.FloatImag;
  8790. if (!EvaluateFloat(SubExpr, Imag, Info))
  8791. return false;
  8792. Result.FloatReal = APFloat(Imag.getSemantics());
  8793. return true;
  8794. } else {
  8795. assert(SubExpr->getType()->isIntegerType() &&
  8796. "Unexpected imaginary literal.");
  8797. Result.makeComplexInt();
  8798. APSInt &Imag = Result.IntImag;
  8799. if (!EvaluateInteger(SubExpr, Imag, Info))
  8800. return false;
  8801. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  8802. return true;
  8803. }
  8804. }
  8805. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  8806. switch (E->getCastKind()) {
  8807. case CK_BitCast:
  8808. case CK_BaseToDerived:
  8809. case CK_DerivedToBase:
  8810. case CK_UncheckedDerivedToBase:
  8811. case CK_Dynamic:
  8812. case CK_ToUnion:
  8813. case CK_ArrayToPointerDecay:
  8814. case CK_FunctionToPointerDecay:
  8815. case CK_NullToPointer:
  8816. case CK_NullToMemberPointer:
  8817. case CK_BaseToDerivedMemberPointer:
  8818. case CK_DerivedToBaseMemberPointer:
  8819. case CK_MemberPointerToBoolean:
  8820. case CK_ReinterpretMemberPointer:
  8821. case CK_ConstructorConversion:
  8822. case CK_IntegralToPointer:
  8823. case CK_PointerToIntegral:
  8824. case CK_PointerToBoolean:
  8825. case CK_ToVoid:
  8826. case CK_VectorSplat:
  8827. case CK_IntegralCast:
  8828. case CK_BooleanToSignedIntegral:
  8829. case CK_IntegralToBoolean:
  8830. case CK_IntegralToFloating:
  8831. case CK_FloatingToIntegral:
  8832. case CK_FloatingToBoolean:
  8833. case CK_FloatingCast:
  8834. case CK_CPointerToObjCPointerCast:
  8835. case CK_BlockPointerToObjCPointerCast:
  8836. case CK_AnyPointerToBlockPointerCast:
  8837. case CK_ObjCObjectLValueCast:
  8838. case CK_FloatingComplexToReal:
  8839. case CK_FloatingComplexToBoolean:
  8840. case CK_IntegralComplexToReal:
  8841. case CK_IntegralComplexToBoolean:
  8842. case CK_ARCProduceObject:
  8843. case CK_ARCConsumeObject:
  8844. case CK_ARCReclaimReturnedObject:
  8845. case CK_ARCExtendBlockObject:
  8846. case CK_CopyAndAutoreleaseBlockObject:
  8847. case CK_BuiltinFnToFnPtr:
  8848. case CK_ZeroToOCLEvent:
  8849. case CK_ZeroToOCLQueue:
  8850. case CK_NonAtomicToAtomic:
  8851. case CK_AddressSpaceConversion:
  8852. case CK_IntToOCLSampler:
  8853. llvm_unreachable("invalid cast kind for complex value");
  8854. case CK_LValueToRValue:
  8855. case CK_AtomicToNonAtomic:
  8856. case CK_NoOp:
  8857. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  8858. case CK_Dependent:
  8859. case CK_LValueBitCast:
  8860. case CK_UserDefinedConversion:
  8861. return Error(E);
  8862. case CK_FloatingRealToComplex: {
  8863. APFloat &Real = Result.FloatReal;
  8864. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  8865. return false;
  8866. Result.makeComplexFloat();
  8867. Result.FloatImag = APFloat(Real.getSemantics());
  8868. return true;
  8869. }
  8870. case CK_FloatingComplexCast: {
  8871. if (!Visit(E->getSubExpr()))
  8872. return false;
  8873. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8874. QualType From
  8875. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8876. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  8877. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  8878. }
  8879. case CK_FloatingComplexToIntegralComplex: {
  8880. if (!Visit(E->getSubExpr()))
  8881. return false;
  8882. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8883. QualType From
  8884. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8885. Result.makeComplexInt();
  8886. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  8887. To, Result.IntReal) &&
  8888. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  8889. To, Result.IntImag);
  8890. }
  8891. case CK_IntegralRealToComplex: {
  8892. APSInt &Real = Result.IntReal;
  8893. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  8894. return false;
  8895. Result.makeComplexInt();
  8896. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  8897. return true;
  8898. }
  8899. case CK_IntegralComplexCast: {
  8900. if (!Visit(E->getSubExpr()))
  8901. return false;
  8902. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  8903. QualType From
  8904. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  8905. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  8906. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  8907. return true;
  8908. }
  8909. case CK_IntegralComplexToFloatingComplex: {
  8910. if (!Visit(E->getSubExpr()))
  8911. return false;
  8912. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  8913. QualType From
  8914. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  8915. Result.makeComplexFloat();
  8916. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  8917. To, Result.FloatReal) &&
  8918. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  8919. To, Result.FloatImag);
  8920. }
  8921. }
  8922. llvm_unreachable("unknown cast resulting in complex value");
  8923. }
  8924. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8925. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  8926. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8927. // Track whether the LHS or RHS is real at the type system level. When this is
  8928. // the case we can simplify our evaluation strategy.
  8929. bool LHSReal = false, RHSReal = false;
  8930. bool LHSOK;
  8931. if (E->getLHS()->getType()->isRealFloatingType()) {
  8932. LHSReal = true;
  8933. APFloat &Real = Result.FloatReal;
  8934. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  8935. if (LHSOK) {
  8936. Result.makeComplexFloat();
  8937. Result.FloatImag = APFloat(Real.getSemantics());
  8938. }
  8939. } else {
  8940. LHSOK = Visit(E->getLHS());
  8941. }
  8942. if (!LHSOK && !Info.noteFailure())
  8943. return false;
  8944. ComplexValue RHS;
  8945. if (E->getRHS()->getType()->isRealFloatingType()) {
  8946. RHSReal = true;
  8947. APFloat &Real = RHS.FloatReal;
  8948. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  8949. return false;
  8950. RHS.makeComplexFloat();
  8951. RHS.FloatImag = APFloat(Real.getSemantics());
  8952. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  8953. return false;
  8954. assert(!(LHSReal && RHSReal) &&
  8955. "Cannot have both operands of a complex operation be real.");
  8956. switch (E->getOpcode()) {
  8957. default: return Error(E);
  8958. case BO_Add:
  8959. if (Result.isComplexFloat()) {
  8960. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  8961. APFloat::rmNearestTiesToEven);
  8962. if (LHSReal)
  8963. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  8964. else if (!RHSReal)
  8965. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  8966. APFloat::rmNearestTiesToEven);
  8967. } else {
  8968. Result.getComplexIntReal() += RHS.getComplexIntReal();
  8969. Result.getComplexIntImag() += RHS.getComplexIntImag();
  8970. }
  8971. break;
  8972. case BO_Sub:
  8973. if (Result.isComplexFloat()) {
  8974. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  8975. APFloat::rmNearestTiesToEven);
  8976. if (LHSReal) {
  8977. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  8978. Result.getComplexFloatImag().changeSign();
  8979. } else if (!RHSReal) {
  8980. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  8981. APFloat::rmNearestTiesToEven);
  8982. }
  8983. } else {
  8984. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  8985. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  8986. }
  8987. break;
  8988. case BO_Mul:
  8989. if (Result.isComplexFloat()) {
  8990. // This is an implementation of complex multiplication according to the
  8991. // constraints laid out in C11 Annex G. The implemention uses the
  8992. // following naming scheme:
  8993. // (a + ib) * (c + id)
  8994. ComplexValue LHS = Result;
  8995. APFloat &A = LHS.getComplexFloatReal();
  8996. APFloat &B = LHS.getComplexFloatImag();
  8997. APFloat &C = RHS.getComplexFloatReal();
  8998. APFloat &D = RHS.getComplexFloatImag();
  8999. APFloat &ResR = Result.getComplexFloatReal();
  9000. APFloat &ResI = Result.getComplexFloatImag();
  9001. if (LHSReal) {
  9002. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  9003. ResR = A * C;
  9004. ResI = A * D;
  9005. } else if (RHSReal) {
  9006. ResR = C * A;
  9007. ResI = C * B;
  9008. } else {
  9009. // In the fully general case, we need to handle NaNs and infinities
  9010. // robustly.
  9011. APFloat AC = A * C;
  9012. APFloat BD = B * D;
  9013. APFloat AD = A * D;
  9014. APFloat BC = B * C;
  9015. ResR = AC - BD;
  9016. ResI = AD + BC;
  9017. if (ResR.isNaN() && ResI.isNaN()) {
  9018. bool Recalc = false;
  9019. if (A.isInfinity() || B.isInfinity()) {
  9020. A = APFloat::copySign(
  9021. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9022. B = APFloat::copySign(
  9023. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9024. if (C.isNaN())
  9025. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9026. if (D.isNaN())
  9027. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9028. Recalc = true;
  9029. }
  9030. if (C.isInfinity() || D.isInfinity()) {
  9031. C = APFloat::copySign(
  9032. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9033. D = APFloat::copySign(
  9034. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9035. if (A.isNaN())
  9036. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9037. if (B.isNaN())
  9038. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9039. Recalc = true;
  9040. }
  9041. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  9042. AD.isInfinity() || BC.isInfinity())) {
  9043. if (A.isNaN())
  9044. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9045. if (B.isNaN())
  9046. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9047. if (C.isNaN())
  9048. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9049. if (D.isNaN())
  9050. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9051. Recalc = true;
  9052. }
  9053. if (Recalc) {
  9054. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  9055. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  9056. }
  9057. }
  9058. }
  9059. } else {
  9060. ComplexValue LHS = Result;
  9061. Result.getComplexIntReal() =
  9062. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  9063. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  9064. Result.getComplexIntImag() =
  9065. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  9066. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  9067. }
  9068. break;
  9069. case BO_Div:
  9070. if (Result.isComplexFloat()) {
  9071. // This is an implementation of complex division according to the
  9072. // constraints laid out in C11 Annex G. The implemention uses the
  9073. // following naming scheme:
  9074. // (a + ib) / (c + id)
  9075. ComplexValue LHS = Result;
  9076. APFloat &A = LHS.getComplexFloatReal();
  9077. APFloat &B = LHS.getComplexFloatImag();
  9078. APFloat &C = RHS.getComplexFloatReal();
  9079. APFloat &D = RHS.getComplexFloatImag();
  9080. APFloat &ResR = Result.getComplexFloatReal();
  9081. APFloat &ResI = Result.getComplexFloatImag();
  9082. if (RHSReal) {
  9083. ResR = A / C;
  9084. ResI = B / C;
  9085. } else {
  9086. if (LHSReal) {
  9087. // No real optimizations we can do here, stub out with zero.
  9088. B = APFloat::getZero(A.getSemantics());
  9089. }
  9090. int DenomLogB = 0;
  9091. APFloat MaxCD = maxnum(abs(C), abs(D));
  9092. if (MaxCD.isFinite()) {
  9093. DenomLogB = ilogb(MaxCD);
  9094. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  9095. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  9096. }
  9097. APFloat Denom = C * C + D * D;
  9098. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  9099. APFloat::rmNearestTiesToEven);
  9100. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  9101. APFloat::rmNearestTiesToEven);
  9102. if (ResR.isNaN() && ResI.isNaN()) {
  9103. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  9104. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  9105. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  9106. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  9107. D.isFinite()) {
  9108. A = APFloat::copySign(
  9109. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9110. B = APFloat::copySign(
  9111. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9112. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  9113. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  9114. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  9115. C = APFloat::copySign(
  9116. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9117. D = APFloat::copySign(
  9118. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9119. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  9120. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  9121. }
  9122. }
  9123. }
  9124. } else {
  9125. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  9126. return Error(E, diag::note_expr_divide_by_zero);
  9127. ComplexValue LHS = Result;
  9128. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9129. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  9130. Result.getComplexIntReal() =
  9131. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9132. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  9133. Result.getComplexIntImag() =
  9134. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  9135. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  9136. }
  9137. break;
  9138. }
  9139. return true;
  9140. }
  9141. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9142. // Get the operand value into 'Result'.
  9143. if (!Visit(E->getSubExpr()))
  9144. return false;
  9145. switch (E->getOpcode()) {
  9146. default:
  9147. return Error(E);
  9148. case UO_Extension:
  9149. return true;
  9150. case UO_Plus:
  9151. // The result is always just the subexpr.
  9152. return true;
  9153. case UO_Minus:
  9154. if (Result.isComplexFloat()) {
  9155. Result.getComplexFloatReal().changeSign();
  9156. Result.getComplexFloatImag().changeSign();
  9157. }
  9158. else {
  9159. Result.getComplexIntReal() = -Result.getComplexIntReal();
  9160. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9161. }
  9162. return true;
  9163. case UO_Not:
  9164. if (Result.isComplexFloat())
  9165. Result.getComplexFloatImag().changeSign();
  9166. else
  9167. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9168. return true;
  9169. }
  9170. }
  9171. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9172. if (E->getNumInits() == 2) {
  9173. if (E->getType()->isComplexType()) {
  9174. Result.makeComplexFloat();
  9175. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  9176. return false;
  9177. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  9178. return false;
  9179. } else {
  9180. Result.makeComplexInt();
  9181. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  9182. return false;
  9183. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  9184. return false;
  9185. }
  9186. return true;
  9187. }
  9188. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  9189. }
  9190. //===----------------------------------------------------------------------===//
  9191. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  9192. // implicit conversion.
  9193. //===----------------------------------------------------------------------===//
  9194. namespace {
  9195. class AtomicExprEvaluator :
  9196. public ExprEvaluatorBase<AtomicExprEvaluator> {
  9197. const LValue *This;
  9198. APValue &Result;
  9199. public:
  9200. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  9201. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9202. bool Success(const APValue &V, const Expr *E) {
  9203. Result = V;
  9204. return true;
  9205. }
  9206. bool ZeroInitialization(const Expr *E) {
  9207. ImplicitValueInitExpr VIE(
  9208. E->getType()->castAs<AtomicType>()->getValueType());
  9209. // For atomic-qualified class (and array) types in C++, initialize the
  9210. // _Atomic-wrapped subobject directly, in-place.
  9211. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  9212. : Evaluate(Result, Info, &VIE);
  9213. }
  9214. bool VisitCastExpr(const CastExpr *E) {
  9215. switch (E->getCastKind()) {
  9216. default:
  9217. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9218. case CK_NonAtomicToAtomic:
  9219. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  9220. : Evaluate(Result, Info, E->getSubExpr());
  9221. }
  9222. }
  9223. };
  9224. } // end anonymous namespace
  9225. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  9226. EvalInfo &Info) {
  9227. assert(E->isRValue() && E->getType()->isAtomicType());
  9228. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  9229. }
  9230. //===----------------------------------------------------------------------===//
  9231. // Void expression evaluation, primarily for a cast to void on the LHS of a
  9232. // comma operator
  9233. //===----------------------------------------------------------------------===//
  9234. namespace {
  9235. class VoidExprEvaluator
  9236. : public ExprEvaluatorBase<VoidExprEvaluator> {
  9237. public:
  9238. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  9239. bool Success(const APValue &V, const Expr *e) { return true; }
  9240. bool ZeroInitialization(const Expr *E) { return true; }
  9241. bool VisitCastExpr(const CastExpr *E) {
  9242. switch (E->getCastKind()) {
  9243. default:
  9244. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9245. case CK_ToVoid:
  9246. VisitIgnoredValue(E->getSubExpr());
  9247. return true;
  9248. }
  9249. }
  9250. bool VisitCallExpr(const CallExpr *E) {
  9251. switch (E->getBuiltinCallee()) {
  9252. default:
  9253. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9254. case Builtin::BI__assume:
  9255. case Builtin::BI__builtin_assume:
  9256. // The argument is not evaluated!
  9257. return true;
  9258. }
  9259. }
  9260. };
  9261. } // end anonymous namespace
  9262. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  9263. assert(E->isRValue() && E->getType()->isVoidType());
  9264. return VoidExprEvaluator(Info).Visit(E);
  9265. }
  9266. //===----------------------------------------------------------------------===//
  9267. // Top level Expr::EvaluateAsRValue method.
  9268. //===----------------------------------------------------------------------===//
  9269. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  9270. // In C, function designators are not lvalues, but we evaluate them as if they
  9271. // are.
  9272. QualType T = E->getType();
  9273. if (E->isGLValue() || T->isFunctionType()) {
  9274. LValue LV;
  9275. if (!EvaluateLValue(E, LV, Info))
  9276. return false;
  9277. LV.moveInto(Result);
  9278. } else if (T->isVectorType()) {
  9279. if (!EvaluateVector(E, Result, Info))
  9280. return false;
  9281. } else if (T->isIntegralOrEnumerationType()) {
  9282. if (!IntExprEvaluator(Info, Result).Visit(E))
  9283. return false;
  9284. } else if (T->hasPointerRepresentation()) {
  9285. LValue LV;
  9286. if (!EvaluatePointer(E, LV, Info))
  9287. return false;
  9288. LV.moveInto(Result);
  9289. } else if (T->isRealFloatingType()) {
  9290. llvm::APFloat F(0.0);
  9291. if (!EvaluateFloat(E, F, Info))
  9292. return false;
  9293. Result = APValue(F);
  9294. } else if (T->isAnyComplexType()) {
  9295. ComplexValue C;
  9296. if (!EvaluateComplex(E, C, Info))
  9297. return false;
  9298. C.moveInto(Result);
  9299. } else if (T->isFixedPointType()) {
  9300. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  9301. } else if (T->isMemberPointerType()) {
  9302. MemberPtr P;
  9303. if (!EvaluateMemberPointer(E, P, Info))
  9304. return false;
  9305. P.moveInto(Result);
  9306. return true;
  9307. } else if (T->isArrayType()) {
  9308. LValue LV;
  9309. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9310. if (!EvaluateArray(E, LV, Value, Info))
  9311. return false;
  9312. Result = Value;
  9313. } else if (T->isRecordType()) {
  9314. LValue LV;
  9315. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9316. if (!EvaluateRecord(E, LV, Value, Info))
  9317. return false;
  9318. Result = Value;
  9319. } else if (T->isVoidType()) {
  9320. if (!Info.getLangOpts().CPlusPlus11)
  9321. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  9322. << E->getType();
  9323. if (!EvaluateVoid(E, Info))
  9324. return false;
  9325. } else if (T->isAtomicType()) {
  9326. QualType Unqual = T.getAtomicUnqualifiedType();
  9327. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  9328. LValue LV;
  9329. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  9330. if (!EvaluateAtomic(E, &LV, Value, Info))
  9331. return false;
  9332. } else {
  9333. if (!EvaluateAtomic(E, nullptr, Result, Info))
  9334. return false;
  9335. }
  9336. } else if (Info.getLangOpts().CPlusPlus11) {
  9337. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  9338. return false;
  9339. } else {
  9340. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  9341. return false;
  9342. }
  9343. return true;
  9344. }
  9345. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  9346. /// cases, the in-place evaluation is essential, since later initializers for
  9347. /// an object can indirectly refer to subobjects which were initialized earlier.
  9348. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  9349. const Expr *E, bool AllowNonLiteralTypes) {
  9350. assert(!E->isValueDependent());
  9351. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  9352. return false;
  9353. if (E->isRValue()) {
  9354. // Evaluate arrays and record types in-place, so that later initializers can
  9355. // refer to earlier-initialized members of the object.
  9356. QualType T = E->getType();
  9357. if (T->isArrayType())
  9358. return EvaluateArray(E, This, Result, Info);
  9359. else if (T->isRecordType())
  9360. return EvaluateRecord(E, This, Result, Info);
  9361. else if (T->isAtomicType()) {
  9362. QualType Unqual = T.getAtomicUnqualifiedType();
  9363. if (Unqual->isArrayType() || Unqual->isRecordType())
  9364. return EvaluateAtomic(E, &This, Result, Info);
  9365. }
  9366. }
  9367. // For any other type, in-place evaluation is unimportant.
  9368. return Evaluate(Result, Info, E);
  9369. }
  9370. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  9371. /// lvalue-to-rvalue cast if it is an lvalue.
  9372. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  9373. if (E->getType().isNull())
  9374. return false;
  9375. if (!CheckLiteralType(Info, E))
  9376. return false;
  9377. if (!::Evaluate(Result, Info, E))
  9378. return false;
  9379. if (E->isGLValue()) {
  9380. LValue LV;
  9381. LV.setFrom(Info.Ctx, Result);
  9382. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  9383. return false;
  9384. }
  9385. // Check this core constant expression is a constant expression.
  9386. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  9387. }
  9388. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  9389. const ASTContext &Ctx, bool &IsConst) {
  9390. // Fast-path evaluations of integer literals, since we sometimes see files
  9391. // containing vast quantities of these.
  9392. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  9393. Result.Val = APValue(APSInt(L->getValue(),
  9394. L->getType()->isUnsignedIntegerType()));
  9395. IsConst = true;
  9396. return true;
  9397. }
  9398. // This case should be rare, but we need to check it before we check on
  9399. // the type below.
  9400. if (Exp->getType().isNull()) {
  9401. IsConst = false;
  9402. return true;
  9403. }
  9404. // FIXME: Evaluating values of large array and record types can cause
  9405. // performance problems. Only do so in C++11 for now.
  9406. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  9407. Exp->getType()->isRecordType()) &&
  9408. !Ctx.getLangOpts().CPlusPlus11) {
  9409. IsConst = false;
  9410. return true;
  9411. }
  9412. return false;
  9413. }
  9414. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  9415. /// any crazy technique (that has nothing to do with language standards) that
  9416. /// we want to. If this function returns true, it returns the folded constant
  9417. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  9418. /// will be applied to the result.
  9419. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  9420. bool IsConst;
  9421. if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
  9422. return IsConst;
  9423. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  9424. return ::EvaluateAsRValue(Info, this, Result.Val);
  9425. }
  9426. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  9427. const ASTContext &Ctx) const {
  9428. EvalResult Scratch;
  9429. return EvaluateAsRValue(Scratch, Ctx) &&
  9430. HandleConversionToBool(Scratch.Val, Result);
  9431. }
  9432. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  9433. Expr::SideEffectsKind SEK) {
  9434. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  9435. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  9436. }
  9437. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  9438. SideEffectsKind AllowSideEffects) const {
  9439. if (!getType()->isIntegralOrEnumerationType())
  9440. return false;
  9441. EvalResult ExprResult;
  9442. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  9443. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9444. return false;
  9445. Result = ExprResult.Val.getInt();
  9446. return true;
  9447. }
  9448. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  9449. SideEffectsKind AllowSideEffects) const {
  9450. if (!getType()->isRealFloatingType())
  9451. return false;
  9452. EvalResult ExprResult;
  9453. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  9454. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  9455. return false;
  9456. Result = ExprResult.Val.getFloat();
  9457. return true;
  9458. }
  9459. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  9460. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  9461. LValue LV;
  9462. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  9463. !CheckLValueConstantExpression(Info, getExprLoc(),
  9464. Ctx.getLValueReferenceType(getType()), LV,
  9465. Expr::EvaluateForCodeGen))
  9466. return false;
  9467. LV.moveInto(Result.Val);
  9468. return true;
  9469. }
  9470. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  9471. const ASTContext &Ctx) const {
  9472. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  9473. EvalInfo Info(Ctx, Result, EM);
  9474. if (!::Evaluate(Result.Val, Info, this))
  9475. return false;
  9476. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  9477. Usage);
  9478. }
  9479. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  9480. const VarDecl *VD,
  9481. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  9482. // FIXME: Evaluating initializers for large array and record types can cause
  9483. // performance problems. Only do so in C++11 for now.
  9484. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  9485. !Ctx.getLangOpts().CPlusPlus11)
  9486. return false;
  9487. Expr::EvalStatus EStatus;
  9488. EStatus.Diag = &Notes;
  9489. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  9490. ? EvalInfo::EM_ConstantExpression
  9491. : EvalInfo::EM_ConstantFold);
  9492. InitInfo.setEvaluatingDecl(VD, Value);
  9493. LValue LVal;
  9494. LVal.set(VD);
  9495. // C++11 [basic.start.init]p2:
  9496. // Variables with static storage duration or thread storage duration shall be
  9497. // zero-initialized before any other initialization takes place.
  9498. // This behavior is not present in C.
  9499. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  9500. !VD->getType()->isReferenceType()) {
  9501. ImplicitValueInitExpr VIE(VD->getType());
  9502. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  9503. /*AllowNonLiteralTypes=*/true))
  9504. return false;
  9505. }
  9506. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  9507. /*AllowNonLiteralTypes=*/true) ||
  9508. EStatus.HasSideEffects)
  9509. return false;
  9510. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  9511. Value);
  9512. }
  9513. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  9514. /// constant folded, but discard the result.
  9515. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  9516. EvalResult Result;
  9517. return EvaluateAsRValue(Result, Ctx) &&
  9518. !hasUnacceptableSideEffect(Result, SEK);
  9519. }
  9520. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  9521. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  9522. EvalResult EvalResult;
  9523. EvalResult.Diag = Diag;
  9524. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  9525. (void)Result;
  9526. assert(Result && "Could not evaluate expression");
  9527. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  9528. return EvalResult.Val.getInt();
  9529. }
  9530. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  9531. bool IsConst;
  9532. EvalResult EvalResult;
  9533. if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
  9534. EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
  9535. (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
  9536. }
  9537. }
  9538. bool Expr::EvalResult::isGlobalLValue() const {
  9539. assert(Val.isLValue());
  9540. return IsGlobalLValue(Val.getLValueBase());
  9541. }
  9542. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  9543. /// an integer constant expression.
  9544. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  9545. /// comma, etc
  9546. // CheckICE - This function does the fundamental ICE checking: the returned
  9547. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  9548. // and a (possibly null) SourceLocation indicating the location of the problem.
  9549. //
  9550. // Note that to reduce code duplication, this helper does no evaluation
  9551. // itself; the caller checks whether the expression is evaluatable, and
  9552. // in the rare cases where CheckICE actually cares about the evaluated
  9553. // value, it calls into Evaluate.
  9554. namespace {
  9555. enum ICEKind {
  9556. /// This expression is an ICE.
  9557. IK_ICE,
  9558. /// This expression is not an ICE, but if it isn't evaluated, it's
  9559. /// a legal subexpression for an ICE. This return value is used to handle
  9560. /// the comma operator in C99 mode, and non-constant subexpressions.
  9561. IK_ICEIfUnevaluated,
  9562. /// This expression is not an ICE, and is not a legal subexpression for one.
  9563. IK_NotICE
  9564. };
  9565. struct ICEDiag {
  9566. ICEKind Kind;
  9567. SourceLocation Loc;
  9568. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  9569. };
  9570. }
  9571. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  9572. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  9573. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  9574. Expr::EvalResult EVResult;
  9575. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  9576. !EVResult.Val.isInt())
  9577. return ICEDiag(IK_NotICE, E->getLocStart());
  9578. return NoDiag();
  9579. }
  9580. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  9581. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  9582. if (!E->getType()->isIntegralOrEnumerationType())
  9583. return ICEDiag(IK_NotICE, E->getLocStart());
  9584. switch (E->getStmtClass()) {
  9585. #define ABSTRACT_STMT(Node)
  9586. #define STMT(Node, Base) case Expr::Node##Class:
  9587. #define EXPR(Node, Base)
  9588. #include "clang/AST/StmtNodes.inc"
  9589. case Expr::PredefinedExprClass:
  9590. case Expr::FloatingLiteralClass:
  9591. case Expr::ImaginaryLiteralClass:
  9592. case Expr::StringLiteralClass:
  9593. case Expr::ArraySubscriptExprClass:
  9594. case Expr::OMPArraySectionExprClass:
  9595. case Expr::MemberExprClass:
  9596. case Expr::CompoundAssignOperatorClass:
  9597. case Expr::CompoundLiteralExprClass:
  9598. case Expr::ExtVectorElementExprClass:
  9599. case Expr::DesignatedInitExprClass:
  9600. case Expr::ArrayInitLoopExprClass:
  9601. case Expr::ArrayInitIndexExprClass:
  9602. case Expr::NoInitExprClass:
  9603. case Expr::DesignatedInitUpdateExprClass:
  9604. case Expr::ImplicitValueInitExprClass:
  9605. case Expr::ParenListExprClass:
  9606. case Expr::VAArgExprClass:
  9607. case Expr::AddrLabelExprClass:
  9608. case Expr::StmtExprClass:
  9609. case Expr::CXXMemberCallExprClass:
  9610. case Expr::CUDAKernelCallExprClass:
  9611. case Expr::CXXDynamicCastExprClass:
  9612. case Expr::CXXTypeidExprClass:
  9613. case Expr::CXXUuidofExprClass:
  9614. case Expr::MSPropertyRefExprClass:
  9615. case Expr::MSPropertySubscriptExprClass:
  9616. case Expr::CXXNullPtrLiteralExprClass:
  9617. case Expr::UserDefinedLiteralClass:
  9618. case Expr::CXXThisExprClass:
  9619. case Expr::CXXThrowExprClass:
  9620. case Expr::CXXNewExprClass:
  9621. case Expr::CXXDeleteExprClass:
  9622. case Expr::CXXPseudoDestructorExprClass:
  9623. case Expr::UnresolvedLookupExprClass:
  9624. case Expr::TypoExprClass:
  9625. case Expr::DependentScopeDeclRefExprClass:
  9626. case Expr::CXXConstructExprClass:
  9627. case Expr::CXXInheritedCtorInitExprClass:
  9628. case Expr::CXXStdInitializerListExprClass:
  9629. case Expr::CXXBindTemporaryExprClass:
  9630. case Expr::ExprWithCleanupsClass:
  9631. case Expr::CXXTemporaryObjectExprClass:
  9632. case Expr::CXXUnresolvedConstructExprClass:
  9633. case Expr::CXXDependentScopeMemberExprClass:
  9634. case Expr::UnresolvedMemberExprClass:
  9635. case Expr::ObjCStringLiteralClass:
  9636. case Expr::ObjCBoxedExprClass:
  9637. case Expr::ObjCArrayLiteralClass:
  9638. case Expr::ObjCDictionaryLiteralClass:
  9639. case Expr::ObjCEncodeExprClass:
  9640. case Expr::ObjCMessageExprClass:
  9641. case Expr::ObjCSelectorExprClass:
  9642. case Expr::ObjCProtocolExprClass:
  9643. case Expr::ObjCIvarRefExprClass:
  9644. case Expr::ObjCPropertyRefExprClass:
  9645. case Expr::ObjCSubscriptRefExprClass:
  9646. case Expr::ObjCIsaExprClass:
  9647. case Expr::ObjCAvailabilityCheckExprClass:
  9648. case Expr::ShuffleVectorExprClass:
  9649. case Expr::ConvertVectorExprClass:
  9650. case Expr::BlockExprClass:
  9651. case Expr::NoStmtClass:
  9652. case Expr::OpaqueValueExprClass:
  9653. case Expr::PackExpansionExprClass:
  9654. case Expr::SubstNonTypeTemplateParmPackExprClass:
  9655. case Expr::FunctionParmPackExprClass:
  9656. case Expr::AsTypeExprClass:
  9657. case Expr::ObjCIndirectCopyRestoreExprClass:
  9658. case Expr::MaterializeTemporaryExprClass:
  9659. case Expr::PseudoObjectExprClass:
  9660. case Expr::AtomicExprClass:
  9661. case Expr::LambdaExprClass:
  9662. case Expr::CXXFoldExprClass:
  9663. case Expr::CoawaitExprClass:
  9664. case Expr::DependentCoawaitExprClass:
  9665. case Expr::CoyieldExprClass:
  9666. return ICEDiag(IK_NotICE, E->getLocStart());
  9667. case Expr::InitListExprClass: {
  9668. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  9669. // form "T x = { a };" is equivalent to "T x = a;".
  9670. // Unless we're initializing a reference, T is a scalar as it is known to be
  9671. // of integral or enumeration type.
  9672. if (E->isRValue())
  9673. if (cast<InitListExpr>(E)->getNumInits() == 1)
  9674. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  9675. return ICEDiag(IK_NotICE, E->getLocStart());
  9676. }
  9677. case Expr::SizeOfPackExprClass:
  9678. case Expr::GNUNullExprClass:
  9679. // GCC considers the GNU __null value to be an integral constant expression.
  9680. return NoDiag();
  9681. case Expr::SubstNonTypeTemplateParmExprClass:
  9682. return
  9683. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  9684. case Expr::ParenExprClass:
  9685. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  9686. case Expr::GenericSelectionExprClass:
  9687. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  9688. case Expr::IntegerLiteralClass:
  9689. case Expr::FixedPointLiteralClass:
  9690. case Expr::CharacterLiteralClass:
  9691. case Expr::ObjCBoolLiteralExprClass:
  9692. case Expr::CXXBoolLiteralExprClass:
  9693. case Expr::CXXScalarValueInitExprClass:
  9694. case Expr::TypeTraitExprClass:
  9695. case Expr::ArrayTypeTraitExprClass:
  9696. case Expr::ExpressionTraitExprClass:
  9697. case Expr::CXXNoexceptExprClass:
  9698. return NoDiag();
  9699. case Expr::CallExprClass:
  9700. case Expr::CXXOperatorCallExprClass: {
  9701. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  9702. // constant expressions, but they can never be ICEs because an ICE cannot
  9703. // contain an operand of (pointer to) function type.
  9704. const CallExpr *CE = cast<CallExpr>(E);
  9705. if (CE->getBuiltinCallee())
  9706. return CheckEvalInICE(E, Ctx);
  9707. return ICEDiag(IK_NotICE, E->getLocStart());
  9708. }
  9709. case Expr::DeclRefExprClass: {
  9710. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  9711. return NoDiag();
  9712. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  9713. if (Ctx.getLangOpts().CPlusPlus &&
  9714. D && IsConstNonVolatile(D->getType())) {
  9715. // Parameter variables are never constants. Without this check,
  9716. // getAnyInitializer() can find a default argument, which leads
  9717. // to chaos.
  9718. if (isa<ParmVarDecl>(D))
  9719. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9720. // C++ 7.1.5.1p2
  9721. // A variable of non-volatile const-qualified integral or enumeration
  9722. // type initialized by an ICE can be used in ICEs.
  9723. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  9724. if (!Dcl->getType()->isIntegralOrEnumerationType())
  9725. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9726. const VarDecl *VD;
  9727. // Look for a declaration of this variable that has an initializer, and
  9728. // check whether it is an ICE.
  9729. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  9730. return NoDiag();
  9731. else
  9732. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  9733. }
  9734. }
  9735. return ICEDiag(IK_NotICE, E->getLocStart());
  9736. }
  9737. case Expr::UnaryOperatorClass: {
  9738. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  9739. switch (Exp->getOpcode()) {
  9740. case UO_PostInc:
  9741. case UO_PostDec:
  9742. case UO_PreInc:
  9743. case UO_PreDec:
  9744. case UO_AddrOf:
  9745. case UO_Deref:
  9746. case UO_Coawait:
  9747. // C99 6.6/3 allows increment and decrement within unevaluated
  9748. // subexpressions of constant expressions, but they can never be ICEs
  9749. // because an ICE cannot contain an lvalue operand.
  9750. return ICEDiag(IK_NotICE, E->getLocStart());
  9751. case UO_Extension:
  9752. case UO_LNot:
  9753. case UO_Plus:
  9754. case UO_Minus:
  9755. case UO_Not:
  9756. case UO_Real:
  9757. case UO_Imag:
  9758. return CheckICE(Exp->getSubExpr(), Ctx);
  9759. }
  9760. // OffsetOf falls through here.
  9761. LLVM_FALLTHROUGH;
  9762. }
  9763. case Expr::OffsetOfExprClass: {
  9764. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  9765. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  9766. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  9767. // compliance: we should warn earlier for offsetof expressions with
  9768. // array subscripts that aren't ICEs, and if the array subscripts
  9769. // are ICEs, the value of the offsetof must be an integer constant.
  9770. return CheckEvalInICE(E, Ctx);
  9771. }
  9772. case Expr::UnaryExprOrTypeTraitExprClass: {
  9773. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  9774. if ((Exp->getKind() == UETT_SizeOf) &&
  9775. Exp->getTypeOfArgument()->isVariableArrayType())
  9776. return ICEDiag(IK_NotICE, E->getLocStart());
  9777. return NoDiag();
  9778. }
  9779. case Expr::BinaryOperatorClass: {
  9780. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  9781. switch (Exp->getOpcode()) {
  9782. case BO_PtrMemD:
  9783. case BO_PtrMemI:
  9784. case BO_Assign:
  9785. case BO_MulAssign:
  9786. case BO_DivAssign:
  9787. case BO_RemAssign:
  9788. case BO_AddAssign:
  9789. case BO_SubAssign:
  9790. case BO_ShlAssign:
  9791. case BO_ShrAssign:
  9792. case BO_AndAssign:
  9793. case BO_XorAssign:
  9794. case BO_OrAssign:
  9795. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  9796. // constant expressions, but they can never be ICEs because an ICE cannot
  9797. // contain an lvalue operand.
  9798. return ICEDiag(IK_NotICE, E->getLocStart());
  9799. case BO_Mul:
  9800. case BO_Div:
  9801. case BO_Rem:
  9802. case BO_Add:
  9803. case BO_Sub:
  9804. case BO_Shl:
  9805. case BO_Shr:
  9806. case BO_LT:
  9807. case BO_GT:
  9808. case BO_LE:
  9809. case BO_GE:
  9810. case BO_EQ:
  9811. case BO_NE:
  9812. case BO_And:
  9813. case BO_Xor:
  9814. case BO_Or:
  9815. case BO_Comma:
  9816. case BO_Cmp: {
  9817. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9818. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9819. if (Exp->getOpcode() == BO_Div ||
  9820. Exp->getOpcode() == BO_Rem) {
  9821. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  9822. // we don't evaluate one.
  9823. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  9824. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  9825. if (REval == 0)
  9826. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  9827. if (REval.isSigned() && REval.isAllOnesValue()) {
  9828. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  9829. if (LEval.isMinSignedValue())
  9830. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  9831. }
  9832. }
  9833. }
  9834. if (Exp->getOpcode() == BO_Comma) {
  9835. if (Ctx.getLangOpts().C99) {
  9836. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  9837. // if it isn't evaluated.
  9838. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  9839. return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
  9840. } else {
  9841. // In both C89 and C++, commas in ICEs are illegal.
  9842. return ICEDiag(IK_NotICE, E->getLocStart());
  9843. }
  9844. }
  9845. return Worst(LHSResult, RHSResult);
  9846. }
  9847. case BO_LAnd:
  9848. case BO_LOr: {
  9849. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  9850. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  9851. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  9852. // Rare case where the RHS has a comma "side-effect"; we need
  9853. // to actually check the condition to see whether the side
  9854. // with the comma is evaluated.
  9855. if ((Exp->getOpcode() == BO_LAnd) !=
  9856. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  9857. return RHSResult;
  9858. return NoDiag();
  9859. }
  9860. return Worst(LHSResult, RHSResult);
  9861. }
  9862. }
  9863. LLVM_FALLTHROUGH;
  9864. }
  9865. case Expr::ImplicitCastExprClass:
  9866. case Expr::CStyleCastExprClass:
  9867. case Expr::CXXFunctionalCastExprClass:
  9868. case Expr::CXXStaticCastExprClass:
  9869. case Expr::CXXReinterpretCastExprClass:
  9870. case Expr::CXXConstCastExprClass:
  9871. case Expr::ObjCBridgedCastExprClass: {
  9872. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  9873. if (isa<ExplicitCastExpr>(E)) {
  9874. if (const FloatingLiteral *FL
  9875. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  9876. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  9877. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  9878. APSInt IgnoredVal(DestWidth, !DestSigned);
  9879. bool Ignored;
  9880. // If the value does not fit in the destination type, the behavior is
  9881. // undefined, so we are not required to treat it as a constant
  9882. // expression.
  9883. if (FL->getValue().convertToInteger(IgnoredVal,
  9884. llvm::APFloat::rmTowardZero,
  9885. &Ignored) & APFloat::opInvalidOp)
  9886. return ICEDiag(IK_NotICE, E->getLocStart());
  9887. return NoDiag();
  9888. }
  9889. }
  9890. switch (cast<CastExpr>(E)->getCastKind()) {
  9891. case CK_LValueToRValue:
  9892. case CK_AtomicToNonAtomic:
  9893. case CK_NonAtomicToAtomic:
  9894. case CK_NoOp:
  9895. case CK_IntegralToBoolean:
  9896. case CK_IntegralCast:
  9897. return CheckICE(SubExpr, Ctx);
  9898. default:
  9899. return ICEDiag(IK_NotICE, E->getLocStart());
  9900. }
  9901. }
  9902. case Expr::BinaryConditionalOperatorClass: {
  9903. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  9904. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  9905. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  9906. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9907. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  9908. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  9909. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  9910. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  9911. return FalseResult;
  9912. }
  9913. case Expr::ConditionalOperatorClass: {
  9914. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  9915. // If the condition (ignoring parens) is a __builtin_constant_p call,
  9916. // then only the true side is actually considered in an integer constant
  9917. // expression, and it is fully evaluated. This is an important GNU
  9918. // extension. See GCC PR38377 for discussion.
  9919. if (const CallExpr *CallCE
  9920. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  9921. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  9922. return CheckEvalInICE(E, Ctx);
  9923. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  9924. if (CondResult.Kind == IK_NotICE)
  9925. return CondResult;
  9926. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  9927. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  9928. if (TrueResult.Kind == IK_NotICE)
  9929. return TrueResult;
  9930. if (FalseResult.Kind == IK_NotICE)
  9931. return FalseResult;
  9932. if (CondResult.Kind == IK_ICEIfUnevaluated)
  9933. return CondResult;
  9934. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  9935. return NoDiag();
  9936. // Rare case where the diagnostics depend on which side is evaluated
  9937. // Note that if we get here, CondResult is 0, and at least one of
  9938. // TrueResult and FalseResult is non-zero.
  9939. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  9940. return FalseResult;
  9941. return TrueResult;
  9942. }
  9943. case Expr::CXXDefaultArgExprClass:
  9944. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  9945. case Expr::CXXDefaultInitExprClass:
  9946. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  9947. case Expr::ChooseExprClass: {
  9948. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  9949. }
  9950. }
  9951. llvm_unreachable("Invalid StmtClass!");
  9952. }
  9953. /// Evaluate an expression as a C++11 integral constant expression.
  9954. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  9955. const Expr *E,
  9956. llvm::APSInt *Value,
  9957. SourceLocation *Loc) {
  9958. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  9959. if (Loc) *Loc = E->getExprLoc();
  9960. return false;
  9961. }
  9962. APValue Result;
  9963. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  9964. return false;
  9965. if (!Result.isInt()) {
  9966. if (Loc) *Loc = E->getExprLoc();
  9967. return false;
  9968. }
  9969. if (Value) *Value = Result.getInt();
  9970. return true;
  9971. }
  9972. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  9973. SourceLocation *Loc) const {
  9974. if (Ctx.getLangOpts().CPlusPlus11)
  9975. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  9976. ICEDiag D = CheckICE(this, Ctx);
  9977. if (D.Kind != IK_ICE) {
  9978. if (Loc) *Loc = D.Loc;
  9979. return false;
  9980. }
  9981. return true;
  9982. }
  9983. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  9984. SourceLocation *Loc, bool isEvaluated) const {
  9985. if (Ctx.getLangOpts().CPlusPlus11)
  9986. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  9987. if (!isIntegerConstantExpr(Ctx, Loc))
  9988. return false;
  9989. // The only possible side-effects here are due to UB discovered in the
  9990. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  9991. // required to treat the expression as an ICE, so we produce the folded
  9992. // value.
  9993. if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
  9994. llvm_unreachable("ICE cannot be evaluated!");
  9995. return true;
  9996. }
  9997. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  9998. return CheckICE(this, Ctx).Kind == IK_ICE;
  9999. }
  10000. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  10001. SourceLocation *Loc) const {
  10002. // We support this checking in C++98 mode in order to diagnose compatibility
  10003. // issues.
  10004. assert(Ctx.getLangOpts().CPlusPlus);
  10005. // Build evaluation settings.
  10006. Expr::EvalStatus Status;
  10007. SmallVector<PartialDiagnosticAt, 8> Diags;
  10008. Status.Diag = &Diags;
  10009. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10010. APValue Scratch;
  10011. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  10012. if (!Diags.empty()) {
  10013. IsConstExpr = false;
  10014. if (Loc) *Loc = Diags[0].first;
  10015. } else if (!IsConstExpr) {
  10016. // FIXME: This shouldn't happen.
  10017. if (Loc) *Loc = getExprLoc();
  10018. }
  10019. return IsConstExpr;
  10020. }
  10021. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  10022. const FunctionDecl *Callee,
  10023. ArrayRef<const Expr*> Args,
  10024. const Expr *This) const {
  10025. Expr::EvalStatus Status;
  10026. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  10027. LValue ThisVal;
  10028. const LValue *ThisPtr = nullptr;
  10029. if (This) {
  10030. #ifndef NDEBUG
  10031. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  10032. assert(MD && "Don't provide `this` for non-methods.");
  10033. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  10034. #endif
  10035. if (EvaluateObjectArgument(Info, This, ThisVal))
  10036. ThisPtr = &ThisVal;
  10037. if (Info.EvalStatus.HasSideEffects)
  10038. return false;
  10039. }
  10040. ArgVector ArgValues(Args.size());
  10041. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  10042. I != E; ++I) {
  10043. if ((*I)->isValueDependent() ||
  10044. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  10045. // If evaluation fails, throw away the argument entirely.
  10046. ArgValues[I - Args.begin()] = APValue();
  10047. if (Info.EvalStatus.HasSideEffects)
  10048. return false;
  10049. }
  10050. // Build fake call to Callee.
  10051. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  10052. ArgValues.data());
  10053. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  10054. }
  10055. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  10056. SmallVectorImpl<
  10057. PartialDiagnosticAt> &Diags) {
  10058. // FIXME: It would be useful to check constexpr function templates, but at the
  10059. // moment the constant expression evaluator cannot cope with the non-rigorous
  10060. // ASTs which we build for dependent expressions.
  10061. if (FD->isDependentContext())
  10062. return true;
  10063. Expr::EvalStatus Status;
  10064. Status.Diag = &Diags;
  10065. EvalInfo Info(FD->getASTContext(), Status,
  10066. EvalInfo::EM_PotentialConstantExpression);
  10067. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  10068. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  10069. // Fabricate an arbitrary expression on the stack and pretend that it
  10070. // is a temporary being used as the 'this' pointer.
  10071. LValue This;
  10072. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  10073. This.set({&VIE, Info.CurrentCall->Index});
  10074. ArrayRef<const Expr*> Args;
  10075. APValue Scratch;
  10076. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  10077. // Evaluate the call as a constant initializer, to allow the construction
  10078. // of objects of non-literal types.
  10079. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  10080. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  10081. } else {
  10082. SourceLocation Loc = FD->getLocation();
  10083. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  10084. Args, FD->getBody(), Info, Scratch, nullptr);
  10085. }
  10086. return Diags.empty();
  10087. }
  10088. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  10089. const FunctionDecl *FD,
  10090. SmallVectorImpl<
  10091. PartialDiagnosticAt> &Diags) {
  10092. Expr::EvalStatus Status;
  10093. Status.Diag = &Diags;
  10094. EvalInfo Info(FD->getASTContext(), Status,
  10095. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  10096. // Fabricate a call stack frame to give the arguments a plausible cover story.
  10097. ArrayRef<const Expr*> Args;
  10098. ArgVector ArgValues(0);
  10099. bool Success = EvaluateArgs(Args, ArgValues, Info);
  10100. (void)Success;
  10101. assert(Success &&
  10102. "Failed to set up arguments for potential constant evaluation");
  10103. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  10104. APValue ResultScratch;
  10105. Evaluate(ResultScratch, Info, E);
  10106. return Diags.empty();
  10107. }
  10108. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  10109. unsigned Type) const {
  10110. if (!getType()->isPointerType())
  10111. return false;
  10112. Expr::EvalStatus Status;
  10113. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  10114. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  10115. }