ExprConstant.cpp 235 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685
  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 rules only, at the moment), or, if folding failed too,
  27. // 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/CharUnits.h"
  38. #include "clang/AST/RecordLayout.h"
  39. #include "clang/AST/StmtVisitor.h"
  40. #include "clang/AST/TypeLoc.h"
  41. #include "clang/AST/ASTDiagnostic.h"
  42. #include "clang/AST/Expr.h"
  43. #include "clang/Basic/Builtins.h"
  44. #include "clang/Basic/TargetInfo.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/Support/SaveAndRestore.h"
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using llvm::APSInt;
  51. using llvm::APFloat;
  52. static bool IsGlobalLValue(APValue::LValueBase B);
  53. namespace {
  54. struct LValue;
  55. struct CallStackFrame;
  56. struct EvalInfo;
  57. static QualType getType(APValue::LValueBase B) {
  58. if (!B) return QualType();
  59. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
  60. return D->getType();
  61. return B.get<const Expr*>()->getType();
  62. }
  63. /// Get an LValue path entry, which is known to not be an array index, as a
  64. /// field or base class.
  65. static
  66. APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
  67. APValue::BaseOrMemberType Value;
  68. Value.setFromOpaqueValue(E.BaseOrMember);
  69. return Value;
  70. }
  71. /// Get an LValue path entry, which is known to not be an array index, as a
  72. /// field declaration.
  73. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  74. return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
  75. }
  76. /// Get an LValue path entry, which is known to not be an array index, as a
  77. /// base class declaration.
  78. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  79. return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
  80. }
  81. /// Determine whether this LValue path entry for a base class names a virtual
  82. /// base class.
  83. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  84. return getAsBaseOrMember(E).getInt();
  85. }
  86. /// Find the path length and type of the most-derived subobject in the given
  87. /// path, and find the size of the containing array, if any.
  88. static
  89. unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
  90. ArrayRef<APValue::LValuePathEntry> Path,
  91. uint64_t &ArraySize, QualType &Type) {
  92. unsigned MostDerivedLength = 0;
  93. Type = Base;
  94. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  95. if (Type->isArrayType()) {
  96. const ConstantArrayType *CAT =
  97. cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
  98. Type = CAT->getElementType();
  99. ArraySize = CAT->getSize().getZExtValue();
  100. MostDerivedLength = I + 1;
  101. } else if (Type->isAnyComplexType()) {
  102. const ComplexType *CT = Type->castAs<ComplexType>();
  103. Type = CT->getElementType();
  104. ArraySize = 2;
  105. MostDerivedLength = I + 1;
  106. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  107. Type = FD->getType();
  108. ArraySize = 0;
  109. MostDerivedLength = I + 1;
  110. } else {
  111. // Path[I] describes a base class.
  112. ArraySize = 0;
  113. }
  114. }
  115. return MostDerivedLength;
  116. }
  117. // The order of this enum is important for diagnostics.
  118. enum CheckSubobjectKind {
  119. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  120. CSK_This, CSK_Real, CSK_Imag
  121. };
  122. /// A path from a glvalue to a subobject of that glvalue.
  123. struct SubobjectDesignator {
  124. /// True if the subobject was named in a manner not supported by C++11. Such
  125. /// lvalues can still be folded, but they are not core constant expressions
  126. /// and we cannot perform lvalue-to-rvalue conversions on them.
  127. bool Invalid : 1;
  128. /// Is this a pointer one past the end of an object?
  129. bool IsOnePastTheEnd : 1;
  130. /// The length of the path to the most-derived object of which this is a
  131. /// subobject.
  132. unsigned MostDerivedPathLength : 30;
  133. /// The size of the array of which the most-derived object is an element, or
  134. /// 0 if the most-derived object is not an array element.
  135. uint64_t MostDerivedArraySize;
  136. /// The type of the most derived object referred to by this address.
  137. QualType MostDerivedType;
  138. typedef APValue::LValuePathEntry PathEntry;
  139. /// The entries on the path from the glvalue to the designated subobject.
  140. SmallVector<PathEntry, 8> Entries;
  141. SubobjectDesignator() : Invalid(true) {}
  142. explicit SubobjectDesignator(QualType T)
  143. : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
  144. MostDerivedArraySize(0), MostDerivedType(T) {}
  145. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  146. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  147. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  148. if (!Invalid) {
  149. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  150. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  151. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  152. if (V.getLValueBase())
  153. MostDerivedPathLength =
  154. findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
  155. V.getLValuePath(), MostDerivedArraySize,
  156. MostDerivedType);
  157. }
  158. }
  159. void setInvalid() {
  160. Invalid = true;
  161. Entries.clear();
  162. }
  163. /// Determine whether this is a one-past-the-end pointer.
  164. bool isOnePastTheEnd() const {
  165. if (IsOnePastTheEnd)
  166. return true;
  167. if (MostDerivedArraySize &&
  168. Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
  169. return true;
  170. return false;
  171. }
  172. /// Check that this refers to a valid subobject.
  173. bool isValidSubobject() const {
  174. if (Invalid)
  175. return false;
  176. return !isOnePastTheEnd();
  177. }
  178. /// Check that this refers to a valid subobject, and if not, produce a
  179. /// relevant diagnostic and set the designator as invalid.
  180. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  181. /// Update this designator to refer to the first element within this array.
  182. void addArrayUnchecked(const ConstantArrayType *CAT) {
  183. PathEntry Entry;
  184. Entry.ArrayIndex = 0;
  185. Entries.push_back(Entry);
  186. // This is a most-derived object.
  187. MostDerivedType = CAT->getElementType();
  188. MostDerivedArraySize = CAT->getSize().getZExtValue();
  189. MostDerivedPathLength = Entries.size();
  190. }
  191. /// Update this designator to refer to the given base or member of this
  192. /// object.
  193. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  194. PathEntry Entry;
  195. APValue::BaseOrMemberType Value(D, Virtual);
  196. Entry.BaseOrMember = Value.getOpaqueValue();
  197. Entries.push_back(Entry);
  198. // If this isn't a base class, it's a new most-derived object.
  199. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  200. MostDerivedType = FD->getType();
  201. MostDerivedArraySize = 0;
  202. MostDerivedPathLength = Entries.size();
  203. }
  204. }
  205. /// Update this designator to refer to the given complex component.
  206. void addComplexUnchecked(QualType EltTy, bool Imag) {
  207. PathEntry Entry;
  208. Entry.ArrayIndex = Imag;
  209. Entries.push_back(Entry);
  210. // This is technically a most-derived object, though in practice this
  211. // is unlikely to matter.
  212. MostDerivedType = EltTy;
  213. MostDerivedArraySize = 2;
  214. MostDerivedPathLength = Entries.size();
  215. }
  216. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
  217. /// Add N to the address of this subobject.
  218. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  219. if (Invalid) return;
  220. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
  221. Entries.back().ArrayIndex += N;
  222. if (Entries.back().ArrayIndex > MostDerivedArraySize) {
  223. diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
  224. setInvalid();
  225. }
  226. return;
  227. }
  228. // [expr.add]p4: For the purposes of these operators, a pointer to a
  229. // nonarray object behaves the same as a pointer to the first element of
  230. // an array of length one with the type of the object as its element type.
  231. if (IsOnePastTheEnd && N == (uint64_t)-1)
  232. IsOnePastTheEnd = false;
  233. else if (!IsOnePastTheEnd && N == 1)
  234. IsOnePastTheEnd = true;
  235. else if (N != 0) {
  236. diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
  237. setInvalid();
  238. }
  239. }
  240. };
  241. /// A stack frame in the constexpr call stack.
  242. struct CallStackFrame {
  243. EvalInfo &Info;
  244. /// Parent - The caller of this stack frame.
  245. CallStackFrame *Caller;
  246. /// CallLoc - The location of the call expression for this call.
  247. SourceLocation CallLoc;
  248. /// Callee - The function which was called.
  249. const FunctionDecl *Callee;
  250. /// Index - The call index of this call.
  251. unsigned Index;
  252. /// This - The binding for the this pointer in this call, if any.
  253. const LValue *This;
  254. /// ParmBindings - Parameter bindings for this function call, indexed by
  255. /// parameters' function scope indices.
  256. const APValue *Arguments;
  257. typedef llvm::DenseMap<const Expr*, APValue> MapTy;
  258. typedef MapTy::const_iterator temp_iterator;
  259. /// Temporaries - Temporary lvalues materialized within this stack frame.
  260. MapTy Temporaries;
  261. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  262. const FunctionDecl *Callee, const LValue *This,
  263. const APValue *Arguments);
  264. ~CallStackFrame();
  265. };
  266. /// A partial diagnostic which we might know in advance that we are not going
  267. /// to emit.
  268. class OptionalDiagnostic {
  269. PartialDiagnostic *Diag;
  270. public:
  271. explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
  272. template<typename T>
  273. OptionalDiagnostic &operator<<(const T &v) {
  274. if (Diag)
  275. *Diag << v;
  276. return *this;
  277. }
  278. OptionalDiagnostic &operator<<(const APSInt &I) {
  279. if (Diag) {
  280. llvm::SmallVector<char, 32> Buffer;
  281. I.toString(Buffer);
  282. *Diag << StringRef(Buffer.data(), Buffer.size());
  283. }
  284. return *this;
  285. }
  286. OptionalDiagnostic &operator<<(const APFloat &F) {
  287. if (Diag) {
  288. llvm::SmallVector<char, 32> Buffer;
  289. F.toString(Buffer);
  290. *Diag << StringRef(Buffer.data(), Buffer.size());
  291. }
  292. return *this;
  293. }
  294. };
  295. /// EvalInfo - This is a private struct used by the evaluator to capture
  296. /// information about a subexpression as it is folded. It retains information
  297. /// about the AST context, but also maintains information about the folded
  298. /// expression.
  299. ///
  300. /// If an expression could be evaluated, it is still possible it is not a C
  301. /// "integer constant expression" or constant expression. If not, this struct
  302. /// captures information about how and why not.
  303. ///
  304. /// One bit of information passed *into* the request for constant folding
  305. /// indicates whether the subexpression is "evaluated" or not according to C
  306. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  307. /// evaluate the expression regardless of what the RHS is, but C only allows
  308. /// certain things in certain situations.
  309. struct EvalInfo {
  310. ASTContext &Ctx;
  311. /// EvalStatus - Contains information about the evaluation.
  312. Expr::EvalStatus &EvalStatus;
  313. /// CurrentCall - The top of the constexpr call stack.
  314. CallStackFrame *CurrentCall;
  315. /// CallStackDepth - The number of calls in the call stack right now.
  316. unsigned CallStackDepth;
  317. /// NextCallIndex - The next call index to assign.
  318. unsigned NextCallIndex;
  319. typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
  320. /// OpaqueValues - Values used as the common expression in a
  321. /// BinaryConditionalOperator.
  322. MapTy OpaqueValues;
  323. /// BottomFrame - The frame in which evaluation started. This must be
  324. /// initialized after CurrentCall and CallStackDepth.
  325. CallStackFrame BottomFrame;
  326. /// EvaluatingDecl - This is the declaration whose initializer is being
  327. /// evaluated, if any.
  328. const VarDecl *EvaluatingDecl;
  329. /// EvaluatingDeclValue - This is the value being constructed for the
  330. /// declaration whose initializer is being evaluated, if any.
  331. APValue *EvaluatingDeclValue;
  332. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  333. /// notes attached to it will also be stored, otherwise they will not be.
  334. bool HasActiveDiagnostic;
  335. /// CheckingPotentialConstantExpression - Are we checking whether the
  336. /// expression is a potential constant expression? If so, some diagnostics
  337. /// are suppressed.
  338. bool CheckingPotentialConstantExpression;
  339. /// \brief Stack depth of IntExprEvaluator.
  340. /// We check this against a maximum value to avoid stack overflow, see
  341. /// test case in test/Sema/many-logical-ops.c.
  342. // FIXME: This is a hack; handle properly unlimited logical ops.
  343. unsigned IntExprEvaluatorDepth;
  344. EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
  345. : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
  346. CallStackDepth(0), NextCallIndex(1),
  347. BottomFrame(*this, SourceLocation(), 0, 0, 0),
  348. EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
  349. CheckingPotentialConstantExpression(false), IntExprEvaluatorDepth(0) {}
  350. const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
  351. MapTy::const_iterator i = OpaqueValues.find(e);
  352. if (i == OpaqueValues.end()) return 0;
  353. return &i->second;
  354. }
  355. void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
  356. EvaluatingDecl = VD;
  357. EvaluatingDeclValue = &Value;
  358. }
  359. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  360. bool CheckCallLimit(SourceLocation Loc) {
  361. // Don't perform any constexpr calls (other than the call we're checking)
  362. // when checking a potential constant expression.
  363. if (CheckingPotentialConstantExpression && CallStackDepth > 1)
  364. return false;
  365. if (NextCallIndex == 0) {
  366. // NextCallIndex has wrapped around.
  367. Diag(Loc, diag::note_constexpr_call_limit_exceeded);
  368. return false;
  369. }
  370. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  371. return true;
  372. Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
  373. << getLangOpts().ConstexprCallDepth;
  374. return false;
  375. }
  376. CallStackFrame *getCallFrame(unsigned CallIndex) {
  377. assert(CallIndex && "no call index in getCallFrame");
  378. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  379. // be null in this loop.
  380. CallStackFrame *Frame = CurrentCall;
  381. while (Frame->Index > CallIndex)
  382. Frame = Frame->Caller;
  383. return (Frame->Index == CallIndex) ? Frame : 0;
  384. }
  385. private:
  386. /// Add a diagnostic to the diagnostics list.
  387. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  388. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  389. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  390. return EvalStatus.Diag->back().second;
  391. }
  392. /// Add notes containing a call stack to the current point of evaluation.
  393. void addCallStack(unsigned Limit);
  394. public:
  395. /// Diagnose that the evaluation cannot be folded.
  396. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
  397. = diag::note_invalid_subexpr_in_const_expr,
  398. unsigned ExtraNotes = 0) {
  399. // If we have a prior diagnostic, it will be noting that the expression
  400. // isn't a constant expression. This diagnostic is more important.
  401. // FIXME: We might want to show both diagnostics to the user.
  402. if (EvalStatus.Diag) {
  403. unsigned CallStackNotes = CallStackDepth - 1;
  404. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  405. if (Limit)
  406. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  407. if (CheckingPotentialConstantExpression)
  408. CallStackNotes = 0;
  409. HasActiveDiagnostic = true;
  410. EvalStatus.Diag->clear();
  411. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  412. addDiag(Loc, DiagId);
  413. if (!CheckingPotentialConstantExpression)
  414. addCallStack(Limit);
  415. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  416. }
  417. HasActiveDiagnostic = false;
  418. return OptionalDiagnostic();
  419. }
  420. /// Diagnose that the evaluation does not produce a C++11 core constant
  421. /// expression.
  422. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  423. = diag::note_invalid_subexpr_in_const_expr,
  424. unsigned ExtraNotes = 0) {
  425. // Don't override a previous diagnostic.
  426. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  427. HasActiveDiagnostic = false;
  428. return OptionalDiagnostic();
  429. }
  430. return Diag(Loc, DiagId, ExtraNotes);
  431. }
  432. /// Add a note to a prior diagnostic.
  433. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  434. if (!HasActiveDiagnostic)
  435. return OptionalDiagnostic();
  436. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  437. }
  438. /// Add a stack of notes to a prior diagnostic.
  439. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  440. if (HasActiveDiagnostic) {
  441. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  442. Diags.begin(), Diags.end());
  443. }
  444. }
  445. /// Should we continue evaluation as much as possible after encountering a
  446. /// construct which can't be folded?
  447. bool keepEvaluatingAfterFailure() {
  448. return CheckingPotentialConstantExpression &&
  449. EvalStatus.Diag && EvalStatus.Diag->empty();
  450. }
  451. };
  452. /// Object used to treat all foldable expressions as constant expressions.
  453. struct FoldConstant {
  454. bool Enabled;
  455. explicit FoldConstant(EvalInfo &Info)
  456. : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
  457. !Info.EvalStatus.HasSideEffects) {
  458. }
  459. // Treat the value we've computed since this object was created as constant.
  460. void Fold(EvalInfo &Info) {
  461. if (Enabled && !Info.EvalStatus.Diag->empty() &&
  462. !Info.EvalStatus.HasSideEffects)
  463. Info.EvalStatus.Diag->clear();
  464. }
  465. };
  466. /// RAII object used to suppress diagnostics and side-effects from a
  467. /// speculative evaluation.
  468. class SpeculativeEvaluationRAII {
  469. EvalInfo &Info;
  470. Expr::EvalStatus Old;
  471. public:
  472. SpeculativeEvaluationRAII(EvalInfo &Info,
  473. llvm::SmallVectorImpl<PartialDiagnosticAt>
  474. *NewDiag = 0)
  475. : Info(Info), Old(Info.EvalStatus) {
  476. Info.EvalStatus.Diag = NewDiag;
  477. }
  478. ~SpeculativeEvaluationRAII() {
  479. Info.EvalStatus = Old;
  480. }
  481. };
  482. }
  483. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  484. CheckSubobjectKind CSK) {
  485. if (Invalid)
  486. return false;
  487. if (isOnePastTheEnd()) {
  488. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
  489. << CSK;
  490. setInvalid();
  491. return false;
  492. }
  493. return true;
  494. }
  495. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  496. const Expr *E, uint64_t N) {
  497. if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
  498. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
  499. << static_cast<int>(N) << /*array*/ 0
  500. << static_cast<unsigned>(MostDerivedArraySize);
  501. else
  502. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
  503. << static_cast<int>(N) << /*non-array*/ 1;
  504. setInvalid();
  505. }
  506. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  507. const FunctionDecl *Callee, const LValue *This,
  508. const APValue *Arguments)
  509. : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
  510. Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
  511. Info.CurrentCall = this;
  512. ++Info.CallStackDepth;
  513. }
  514. CallStackFrame::~CallStackFrame() {
  515. assert(Info.CurrentCall == this && "calls retired out of order");
  516. --Info.CallStackDepth;
  517. Info.CurrentCall = Caller;
  518. }
  519. /// Produce a string describing the given constexpr call.
  520. static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
  521. unsigned ArgIndex = 0;
  522. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  523. !isa<CXXConstructorDecl>(Frame->Callee) &&
  524. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  525. if (!IsMemberCall)
  526. Out << *Frame->Callee << '(';
  527. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  528. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  529. if (ArgIndex > (unsigned)IsMemberCall)
  530. Out << ", ";
  531. const ParmVarDecl *Param = *I;
  532. const APValue &Arg = Frame->Arguments[ArgIndex];
  533. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  534. if (ArgIndex == 0 && IsMemberCall)
  535. Out << "->" << *Frame->Callee << '(';
  536. }
  537. Out << ')';
  538. }
  539. void EvalInfo::addCallStack(unsigned Limit) {
  540. // Determine which calls to skip, if any.
  541. unsigned ActiveCalls = CallStackDepth - 1;
  542. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  543. if (Limit && Limit < ActiveCalls) {
  544. SkipStart = Limit / 2 + Limit % 2;
  545. SkipEnd = ActiveCalls - Limit / 2;
  546. }
  547. // Walk the call stack and add the diagnostics.
  548. unsigned CallIdx = 0;
  549. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  550. Frame = Frame->Caller, ++CallIdx) {
  551. // Skip this call?
  552. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  553. if (CallIdx == SkipStart) {
  554. // Note that we're skipping calls.
  555. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  556. << unsigned(ActiveCalls - Limit);
  557. }
  558. continue;
  559. }
  560. llvm::SmallVector<char, 128> Buffer;
  561. llvm::raw_svector_ostream Out(Buffer);
  562. describeCall(Frame, Out);
  563. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  564. }
  565. }
  566. namespace {
  567. struct ComplexValue {
  568. private:
  569. bool IsInt;
  570. public:
  571. APSInt IntReal, IntImag;
  572. APFloat FloatReal, FloatImag;
  573. ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
  574. void makeComplexFloat() { IsInt = false; }
  575. bool isComplexFloat() const { return !IsInt; }
  576. APFloat &getComplexFloatReal() { return FloatReal; }
  577. APFloat &getComplexFloatImag() { return FloatImag; }
  578. void makeComplexInt() { IsInt = true; }
  579. bool isComplexInt() const { return IsInt; }
  580. APSInt &getComplexIntReal() { return IntReal; }
  581. APSInt &getComplexIntImag() { return IntImag; }
  582. void moveInto(APValue &v) const {
  583. if (isComplexFloat())
  584. v = APValue(FloatReal, FloatImag);
  585. else
  586. v = APValue(IntReal, IntImag);
  587. }
  588. void setFrom(const APValue &v) {
  589. assert(v.isComplexFloat() || v.isComplexInt());
  590. if (v.isComplexFloat()) {
  591. makeComplexFloat();
  592. FloatReal = v.getComplexFloatReal();
  593. FloatImag = v.getComplexFloatImag();
  594. } else {
  595. makeComplexInt();
  596. IntReal = v.getComplexIntReal();
  597. IntImag = v.getComplexIntImag();
  598. }
  599. }
  600. };
  601. struct LValue {
  602. APValue::LValueBase Base;
  603. CharUnits Offset;
  604. unsigned CallIndex;
  605. SubobjectDesignator Designator;
  606. const APValue::LValueBase getLValueBase() const { return Base; }
  607. CharUnits &getLValueOffset() { return Offset; }
  608. const CharUnits &getLValueOffset() const { return Offset; }
  609. unsigned getLValueCallIndex() const { return CallIndex; }
  610. SubobjectDesignator &getLValueDesignator() { return Designator; }
  611. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  612. void moveInto(APValue &V) const {
  613. if (Designator.Invalid)
  614. V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
  615. else
  616. V = APValue(Base, Offset, Designator.Entries,
  617. Designator.IsOnePastTheEnd, CallIndex);
  618. }
  619. void setFrom(ASTContext &Ctx, const APValue &V) {
  620. assert(V.isLValue());
  621. Base = V.getLValueBase();
  622. Offset = V.getLValueOffset();
  623. CallIndex = V.getLValueCallIndex();
  624. Designator = SubobjectDesignator(Ctx, V);
  625. }
  626. void set(APValue::LValueBase B, unsigned I = 0) {
  627. Base = B;
  628. Offset = CharUnits::Zero();
  629. CallIndex = I;
  630. Designator = SubobjectDesignator(getType(B));
  631. }
  632. // Check that this LValue is not based on a null pointer. If it is, produce
  633. // a diagnostic and mark the designator as invalid.
  634. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  635. CheckSubobjectKind CSK) {
  636. if (Designator.Invalid)
  637. return false;
  638. if (!Base) {
  639. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
  640. << CSK;
  641. Designator.setInvalid();
  642. return false;
  643. }
  644. return true;
  645. }
  646. // Check this LValue refers to an object. If not, set the designator to be
  647. // invalid and emit a diagnostic.
  648. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  649. return checkNullPointer(Info, E, CSK) &&
  650. Designator.checkSubobject(Info, E, CSK);
  651. }
  652. void addDecl(EvalInfo &Info, const Expr *E,
  653. const Decl *D, bool Virtual = false) {
  654. checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
  655. Designator.addDeclUnchecked(D, Virtual);
  656. }
  657. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  658. checkSubobject(Info, E, CSK_ArrayToPointer);
  659. Designator.addArrayUnchecked(CAT);
  660. }
  661. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  662. checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real);
  663. Designator.addComplexUnchecked(EltTy, Imag);
  664. }
  665. void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
  666. if (!checkNullPointer(Info, E, CSK_ArrayIndex))
  667. return;
  668. Designator.adjustIndex(Info, E, N);
  669. }
  670. };
  671. struct MemberPtr {
  672. MemberPtr() {}
  673. explicit MemberPtr(const ValueDecl *Decl) :
  674. DeclAndIsDerivedMember(Decl, false), Path() {}
  675. /// The member or (direct or indirect) field referred to by this member
  676. /// pointer, or 0 if this is a null member pointer.
  677. const ValueDecl *getDecl() const {
  678. return DeclAndIsDerivedMember.getPointer();
  679. }
  680. /// Is this actually a member of some type derived from the relevant class?
  681. bool isDerivedMember() const {
  682. return DeclAndIsDerivedMember.getInt();
  683. }
  684. /// Get the class which the declaration actually lives in.
  685. const CXXRecordDecl *getContainingRecord() const {
  686. return cast<CXXRecordDecl>(
  687. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  688. }
  689. void moveInto(APValue &V) const {
  690. V = APValue(getDecl(), isDerivedMember(), Path);
  691. }
  692. void setFrom(const APValue &V) {
  693. assert(V.isMemberPointer());
  694. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  695. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  696. Path.clear();
  697. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  698. Path.insert(Path.end(), P.begin(), P.end());
  699. }
  700. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  701. /// whether the member is a member of some class derived from the class type
  702. /// of the member pointer.
  703. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  704. /// Path - The path of base/derived classes from the member declaration's
  705. /// class (exclusive) to the class type of the member pointer (inclusive).
  706. SmallVector<const CXXRecordDecl*, 4> Path;
  707. /// Perform a cast towards the class of the Decl (either up or down the
  708. /// hierarchy).
  709. bool castBack(const CXXRecordDecl *Class) {
  710. assert(!Path.empty());
  711. const CXXRecordDecl *Expected;
  712. if (Path.size() >= 2)
  713. Expected = Path[Path.size() - 2];
  714. else
  715. Expected = getContainingRecord();
  716. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  717. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  718. // if B does not contain the original member and is not a base or
  719. // derived class of the class containing the original member, the result
  720. // of the cast is undefined.
  721. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  722. // (D::*). We consider that to be a language defect.
  723. return false;
  724. }
  725. Path.pop_back();
  726. return true;
  727. }
  728. /// Perform a base-to-derived member pointer cast.
  729. bool castToDerived(const CXXRecordDecl *Derived) {
  730. if (!getDecl())
  731. return true;
  732. if (!isDerivedMember()) {
  733. Path.push_back(Derived);
  734. return true;
  735. }
  736. if (!castBack(Derived))
  737. return false;
  738. if (Path.empty())
  739. DeclAndIsDerivedMember.setInt(false);
  740. return true;
  741. }
  742. /// Perform a derived-to-base member pointer cast.
  743. bool castToBase(const CXXRecordDecl *Base) {
  744. if (!getDecl())
  745. return true;
  746. if (Path.empty())
  747. DeclAndIsDerivedMember.setInt(true);
  748. if (isDerivedMember()) {
  749. Path.push_back(Base);
  750. return true;
  751. }
  752. return castBack(Base);
  753. }
  754. };
  755. /// Compare two member pointers, which are assumed to be of the same type.
  756. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  757. if (!LHS.getDecl() || !RHS.getDecl())
  758. return !LHS.getDecl() && !RHS.getDecl();
  759. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  760. return false;
  761. return LHS.Path == RHS.Path;
  762. }
  763. /// Kinds of constant expression checking, for diagnostics.
  764. enum CheckConstantExpressionKind {
  765. CCEK_Constant, ///< A normal constant.
  766. CCEK_ReturnValue, ///< A constexpr function return value.
  767. CCEK_MemberInit ///< A constexpr constructor mem-initializer.
  768. };
  769. }
  770. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  771. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  772. const LValue &This, const Expr *E,
  773. CheckConstantExpressionKind CCEK = CCEK_Constant,
  774. bool AllowNonLiteralTypes = false);
  775. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
  776. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
  777. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  778. EvalInfo &Info);
  779. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  780. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  781. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  782. EvalInfo &Info);
  783. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  784. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  785. //===----------------------------------------------------------------------===//
  786. // Misc utilities
  787. //===----------------------------------------------------------------------===//
  788. /// Should this call expression be treated as a string literal?
  789. static bool IsStringLiteralCall(const CallExpr *E) {
  790. unsigned Builtin = E->isBuiltinCall();
  791. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  792. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  793. }
  794. static bool IsGlobalLValue(APValue::LValueBase B) {
  795. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  796. // constant expression of pointer type that evaluates to...
  797. // ... a null pointer value, or a prvalue core constant expression of type
  798. // std::nullptr_t.
  799. if (!B) return true;
  800. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  801. // ... the address of an object with static storage duration,
  802. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  803. return VD->hasGlobalStorage();
  804. // ... the address of a function,
  805. return isa<FunctionDecl>(D);
  806. }
  807. const Expr *E = B.get<const Expr*>();
  808. switch (E->getStmtClass()) {
  809. default:
  810. return false;
  811. case Expr::CompoundLiteralExprClass: {
  812. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  813. return CLE->isFileScope() && CLE->isLValue();
  814. }
  815. // A string literal has static storage duration.
  816. case Expr::StringLiteralClass:
  817. case Expr::PredefinedExprClass:
  818. case Expr::ObjCStringLiteralClass:
  819. case Expr::ObjCEncodeExprClass:
  820. case Expr::CXXTypeidExprClass:
  821. return true;
  822. case Expr::CallExprClass:
  823. return IsStringLiteralCall(cast<CallExpr>(E));
  824. // For GCC compatibility, &&label has static storage duration.
  825. case Expr::AddrLabelExprClass:
  826. return true;
  827. // A Block literal expression may be used as the initialization value for
  828. // Block variables at global or local static scope.
  829. case Expr::BlockExprClass:
  830. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  831. case Expr::ImplicitValueInitExprClass:
  832. // FIXME:
  833. // We can never form an lvalue with an implicit value initialization as its
  834. // base through expression evaluation, so these only appear in one case: the
  835. // implicit variable declaration we invent when checking whether a constexpr
  836. // constructor can produce a constant expression. We must assume that such
  837. // an expression might be a global lvalue.
  838. return true;
  839. }
  840. }
  841. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  842. assert(Base && "no location for a null lvalue");
  843. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  844. if (VD)
  845. Info.Note(VD->getLocation(), diag::note_declared_at);
  846. else
  847. Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
  848. diag::note_constexpr_temporary_here);
  849. }
  850. /// Check that this reference or pointer core constant expression is a valid
  851. /// value for an address or reference constant expression. Return true if we
  852. /// can fold this expression, whether or not it's a constant expression.
  853. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  854. QualType Type, const LValue &LVal) {
  855. bool IsReferenceType = Type->isReferenceType();
  856. APValue::LValueBase Base = LVal.getLValueBase();
  857. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  858. // Check that the object is a global. Note that the fake 'this' object we
  859. // manufacture when checking potential constant expressions is conservatively
  860. // assumed to be global here.
  861. if (!IsGlobalLValue(Base)) {
  862. if (Info.getLangOpts().CPlusPlus0x) {
  863. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  864. Info.Diag(Loc, diag::note_constexpr_non_global, 1)
  865. << IsReferenceType << !Designator.Entries.empty()
  866. << !!VD << VD;
  867. NoteLValueLocation(Info, Base);
  868. } else {
  869. Info.Diag(Loc);
  870. }
  871. // Don't allow references to temporaries to escape.
  872. return false;
  873. }
  874. assert((Info.CheckingPotentialConstantExpression ||
  875. LVal.getLValueCallIndex() == 0) &&
  876. "have call index for global lvalue");
  877. // Allow address constant expressions to be past-the-end pointers. This is
  878. // an extension: the standard requires them to point to an object.
  879. if (!IsReferenceType)
  880. return true;
  881. // A reference constant expression must refer to an object.
  882. if (!Base) {
  883. // FIXME: diagnostic
  884. Info.CCEDiag(Loc);
  885. return true;
  886. }
  887. // Does this refer one past the end of some object?
  888. if (Designator.isOnePastTheEnd()) {
  889. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  890. Info.Diag(Loc, diag::note_constexpr_past_end, 1)
  891. << !Designator.Entries.empty() << !!VD << VD;
  892. NoteLValueLocation(Info, Base);
  893. }
  894. return true;
  895. }
  896. /// Check that this core constant expression is of literal type, and if not,
  897. /// produce an appropriate diagnostic.
  898. static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
  899. if (!E->isRValue() || E->getType()->isLiteralType())
  900. return true;
  901. // Prvalue constant expressions must be of literal types.
  902. if (Info.getLangOpts().CPlusPlus0x)
  903. Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
  904. << E->getType();
  905. else
  906. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  907. return false;
  908. }
  909. /// Check that this core constant expression value is a valid value for a
  910. /// constant expression. If not, report an appropriate diagnostic. Does not
  911. /// check that the expression is of literal type.
  912. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
  913. QualType Type, const APValue &Value) {
  914. // Core issue 1454: For a literal constant expression of array or class type,
  915. // each subobject of its value shall have been initialized by a constant
  916. // expression.
  917. if (Value.isArray()) {
  918. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  919. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  920. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  921. Value.getArrayInitializedElt(I)))
  922. return false;
  923. }
  924. if (!Value.hasArrayFiller())
  925. return true;
  926. return CheckConstantExpression(Info, DiagLoc, EltTy,
  927. Value.getArrayFiller());
  928. }
  929. if (Value.isUnion() && Value.getUnionField()) {
  930. return CheckConstantExpression(Info, DiagLoc,
  931. Value.getUnionField()->getType(),
  932. Value.getUnionValue());
  933. }
  934. if (Value.isStruct()) {
  935. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  936. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  937. unsigned BaseIndex = 0;
  938. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  939. End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
  940. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  941. Value.getStructBase(BaseIndex)))
  942. return false;
  943. }
  944. }
  945. for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  946. I != E; ++I) {
  947. if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
  948. Value.getStructField((*I)->getFieldIndex())))
  949. return false;
  950. }
  951. }
  952. if (Value.isLValue()) {
  953. LValue LVal;
  954. LVal.setFrom(Info.Ctx, Value);
  955. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
  956. }
  957. // Everything else is fine.
  958. return true;
  959. }
  960. const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  961. return LVal.Base.dyn_cast<const ValueDecl*>();
  962. }
  963. static bool IsLiteralLValue(const LValue &Value) {
  964. return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
  965. }
  966. static bool IsWeakLValue(const LValue &Value) {
  967. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  968. return Decl && Decl->isWeak();
  969. }
  970. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  971. // A null base expression indicates a null pointer. These are always
  972. // evaluatable, and they are false unless the offset is zero.
  973. if (!Value.getLValueBase()) {
  974. Result = !Value.getLValueOffset().isZero();
  975. return true;
  976. }
  977. // We have a non-null base. These are generally known to be true, but if it's
  978. // a weak declaration it can be null at runtime.
  979. Result = true;
  980. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  981. return !Decl || !Decl->isWeak();
  982. }
  983. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  984. switch (Val.getKind()) {
  985. case APValue::Uninitialized:
  986. return false;
  987. case APValue::Int:
  988. Result = Val.getInt().getBoolValue();
  989. return true;
  990. case APValue::Float:
  991. Result = !Val.getFloat().isZero();
  992. return true;
  993. case APValue::ComplexInt:
  994. Result = Val.getComplexIntReal().getBoolValue() ||
  995. Val.getComplexIntImag().getBoolValue();
  996. return true;
  997. case APValue::ComplexFloat:
  998. Result = !Val.getComplexFloatReal().isZero() ||
  999. !Val.getComplexFloatImag().isZero();
  1000. return true;
  1001. case APValue::LValue:
  1002. return EvalPointerValueAsBool(Val, Result);
  1003. case APValue::MemberPointer:
  1004. Result = Val.getMemberPointerDecl();
  1005. return true;
  1006. case APValue::Vector:
  1007. case APValue::Array:
  1008. case APValue::Struct:
  1009. case APValue::Union:
  1010. case APValue::AddrLabelDiff:
  1011. return false;
  1012. }
  1013. llvm_unreachable("unknown APValue kind");
  1014. }
  1015. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1016. EvalInfo &Info) {
  1017. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1018. APValue Val;
  1019. if (!Evaluate(Val, Info, E))
  1020. return false;
  1021. return HandleConversionToBool(Val, Result);
  1022. }
  1023. template<typename T>
  1024. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1025. const T &SrcValue, QualType DestType) {
  1026. Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
  1027. << SrcValue << DestType;
  1028. return false;
  1029. }
  1030. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1031. QualType SrcType, const APFloat &Value,
  1032. QualType DestType, APSInt &Result) {
  1033. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1034. // Determine whether we are converting to unsigned or signed.
  1035. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1036. Result = APSInt(DestWidth, !DestSigned);
  1037. bool ignored;
  1038. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1039. & APFloat::opInvalidOp)
  1040. return HandleOverflow(Info, E, Value, DestType);
  1041. return true;
  1042. }
  1043. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1044. QualType SrcType, QualType DestType,
  1045. APFloat &Result) {
  1046. APFloat Value = Result;
  1047. bool ignored;
  1048. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1049. APFloat::rmNearestTiesToEven, &ignored)
  1050. & APFloat::opOverflow)
  1051. return HandleOverflow(Info, E, Value, DestType);
  1052. return true;
  1053. }
  1054. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1055. QualType DestType, QualType SrcType,
  1056. APSInt &Value) {
  1057. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1058. APSInt Result = Value;
  1059. // Figure out if this is a truncate, extend or noop cast.
  1060. // If the input is signed, do a sign extend, noop, or truncate.
  1061. Result = Result.extOrTrunc(DestWidth);
  1062. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1063. return Result;
  1064. }
  1065. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1066. QualType SrcType, const APSInt &Value,
  1067. QualType DestType, APFloat &Result) {
  1068. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1069. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1070. APFloat::rmNearestTiesToEven)
  1071. & APFloat::opOverflow)
  1072. return HandleOverflow(Info, E, Value, DestType);
  1073. return true;
  1074. }
  1075. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1076. llvm::APInt &Res) {
  1077. APValue SVal;
  1078. if (!Evaluate(SVal, Info, E))
  1079. return false;
  1080. if (SVal.isInt()) {
  1081. Res = SVal.getInt();
  1082. return true;
  1083. }
  1084. if (SVal.isFloat()) {
  1085. Res = SVal.getFloat().bitcastToAPInt();
  1086. return true;
  1087. }
  1088. if (SVal.isVector()) {
  1089. QualType VecTy = E->getType();
  1090. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1091. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1092. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1093. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1094. Res = llvm::APInt::getNullValue(VecSize);
  1095. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1096. APValue &Elt = SVal.getVectorElt(i);
  1097. llvm::APInt EltAsInt;
  1098. if (Elt.isInt()) {
  1099. EltAsInt = Elt.getInt();
  1100. } else if (Elt.isFloat()) {
  1101. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1102. } else {
  1103. // Don't try to handle vectors of anything other than int or float
  1104. // (not sure if it's possible to hit this case).
  1105. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1106. return false;
  1107. }
  1108. unsigned BaseEltSize = EltAsInt.getBitWidth();
  1109. if (BigEndian)
  1110. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  1111. else
  1112. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  1113. }
  1114. return true;
  1115. }
  1116. // Give up if the input isn't an int, float, or vector. For example, we
  1117. // reject "(v4i16)(intptr_t)&a".
  1118. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1119. return false;
  1120. }
  1121. /// Cast an lvalue referring to a base subobject to a derived class, by
  1122. /// truncating the lvalue's path to the given length.
  1123. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  1124. const RecordDecl *TruncatedType,
  1125. unsigned TruncatedElements) {
  1126. SubobjectDesignator &D = Result.Designator;
  1127. // Check we actually point to a derived class object.
  1128. if (TruncatedElements == D.Entries.size())
  1129. return true;
  1130. assert(TruncatedElements >= D.MostDerivedPathLength &&
  1131. "not casting to a derived class");
  1132. if (!Result.checkSubobject(Info, E, CSK_Derived))
  1133. return false;
  1134. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  1135. const RecordDecl *RD = TruncatedType;
  1136. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  1137. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1138. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  1139. if (isVirtualBaseClass(D.Entries[I]))
  1140. Result.Offset -= Layout.getVBaseClassOffset(Base);
  1141. else
  1142. Result.Offset -= Layout.getBaseClassOffset(Base);
  1143. RD = Base;
  1144. }
  1145. D.Entries.resize(TruncatedElements);
  1146. return true;
  1147. }
  1148. static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1149. const CXXRecordDecl *Derived,
  1150. const CXXRecordDecl *Base,
  1151. const ASTRecordLayout *RL = 0) {
  1152. if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
  1153. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  1154. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  1155. }
  1156. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  1157. const CXXRecordDecl *DerivedDecl,
  1158. const CXXBaseSpecifier *Base) {
  1159. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  1160. if (!Base->isVirtual()) {
  1161. HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  1162. return true;
  1163. }
  1164. SubobjectDesignator &D = Obj.Designator;
  1165. if (D.Invalid)
  1166. return false;
  1167. // Extract most-derived object and corresponding type.
  1168. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  1169. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  1170. return false;
  1171. // Find the virtual base class.
  1172. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  1173. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  1174. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  1175. return true;
  1176. }
  1177. /// Update LVal to refer to the given field, which must be a member of the type
  1178. /// currently described by LVal.
  1179. static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  1180. const FieldDecl *FD,
  1181. const ASTRecordLayout *RL = 0) {
  1182. if (!RL)
  1183. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  1184. unsigned I = FD->getFieldIndex();
  1185. LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
  1186. LVal.addDecl(Info, E, FD);
  1187. }
  1188. /// Update LVal to refer to the given indirect field.
  1189. static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  1190. LValue &LVal,
  1191. const IndirectFieldDecl *IFD) {
  1192. for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
  1193. CE = IFD->chain_end(); C != CE; ++C)
  1194. HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
  1195. }
  1196. /// Get the size of the given type in char units.
  1197. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  1198. QualType Type, CharUnits &Size) {
  1199. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  1200. // extension.
  1201. if (Type->isVoidType() || Type->isFunctionType()) {
  1202. Size = CharUnits::One();
  1203. return true;
  1204. }
  1205. if (!Type->isConstantSizeType()) {
  1206. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  1207. // FIXME: Better diagnostic.
  1208. Info.Diag(Loc);
  1209. return false;
  1210. }
  1211. Size = Info.Ctx.getTypeSizeInChars(Type);
  1212. return true;
  1213. }
  1214. /// Update a pointer value to model pointer arithmetic.
  1215. /// \param Info - Information about the ongoing evaluation.
  1216. /// \param E - The expression being evaluated, for diagnostic purposes.
  1217. /// \param LVal - The pointer value to be updated.
  1218. /// \param EltTy - The pointee type represented by LVal.
  1219. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  1220. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  1221. LValue &LVal, QualType EltTy,
  1222. int64_t Adjustment) {
  1223. CharUnits SizeOfPointee;
  1224. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  1225. return false;
  1226. // Compute the new offset in the appropriate width.
  1227. LVal.Offset += Adjustment * SizeOfPointee;
  1228. LVal.adjustIndex(Info, E, Adjustment);
  1229. return true;
  1230. }
  1231. /// Update an lvalue to refer to a component of a complex number.
  1232. /// \param Info - Information about the ongoing evaluation.
  1233. /// \param LVal - The lvalue to be updated.
  1234. /// \param EltTy - The complex number's component type.
  1235. /// \param Imag - False for the real component, true for the imaginary.
  1236. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  1237. LValue &LVal, QualType EltTy,
  1238. bool Imag) {
  1239. if (Imag) {
  1240. CharUnits SizeOfComponent;
  1241. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  1242. return false;
  1243. LVal.Offset += SizeOfComponent;
  1244. }
  1245. LVal.addComplex(Info, E, EltTy, Imag);
  1246. return true;
  1247. }
  1248. /// Try to evaluate the initializer for a variable declaration.
  1249. static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  1250. const VarDecl *VD,
  1251. CallStackFrame *Frame, APValue &Result) {
  1252. // If this is a parameter to an active constexpr function call, perform
  1253. // argument substitution.
  1254. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  1255. // Assume arguments of a potential constant expression are unknown
  1256. // constant expressions.
  1257. if (Info.CheckingPotentialConstantExpression)
  1258. return false;
  1259. if (!Frame || !Frame->Arguments) {
  1260. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1261. return false;
  1262. }
  1263. Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
  1264. return true;
  1265. }
  1266. // Dig out the initializer, and use the declaration which it's attached to.
  1267. const Expr *Init = VD->getAnyInitializer(VD);
  1268. if (!Init || Init->isValueDependent()) {
  1269. // If we're checking a potential constant expression, the variable could be
  1270. // initialized later.
  1271. if (!Info.CheckingPotentialConstantExpression)
  1272. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1273. return false;
  1274. }
  1275. // If we're currently evaluating the initializer of this declaration, use that
  1276. // in-flight value.
  1277. if (Info.EvaluatingDecl == VD) {
  1278. Result = *Info.EvaluatingDeclValue;
  1279. return !Result.isUninit();
  1280. }
  1281. // Never evaluate the initializer of a weak variable. We can't be sure that
  1282. // this is the definition which will be used.
  1283. if (VD->isWeak()) {
  1284. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1285. return false;
  1286. }
  1287. // Check that we can fold the initializer. In C++, we will have already done
  1288. // this in the cases where it matters for conformance.
  1289. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  1290. if (!VD->evaluateValue(Notes)) {
  1291. Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
  1292. Notes.size() + 1) << VD;
  1293. Info.Note(VD->getLocation(), diag::note_declared_at);
  1294. Info.addNotes(Notes);
  1295. return false;
  1296. } else if (!VD->checkInitIsICE()) {
  1297. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
  1298. Notes.size() + 1) << VD;
  1299. Info.Note(VD->getLocation(), diag::note_declared_at);
  1300. Info.addNotes(Notes);
  1301. }
  1302. Result = *VD->getEvaluatedValue();
  1303. return true;
  1304. }
  1305. static bool IsConstNonVolatile(QualType T) {
  1306. Qualifiers Quals = T.getQualifiers();
  1307. return Quals.hasConst() && !Quals.hasVolatile();
  1308. }
  1309. /// Get the base index of the given base class within an APValue representing
  1310. /// the given derived class.
  1311. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  1312. const CXXRecordDecl *Base) {
  1313. Base = Base->getCanonicalDecl();
  1314. unsigned Index = 0;
  1315. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  1316. E = Derived->bases_end(); I != E; ++I, ++Index) {
  1317. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  1318. return Index;
  1319. }
  1320. llvm_unreachable("base class missing from derived class's bases list");
  1321. }
  1322. /// Extract the value of a character from a string literal.
  1323. static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  1324. uint64_t Index) {
  1325. // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
  1326. const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
  1327. assert(S && "unexpected string literal expression kind");
  1328. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  1329. Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
  1330. if (Index < S->getLength())
  1331. Value = S->getCodeUnit(Index);
  1332. return Value;
  1333. }
  1334. /// Extract the designated sub-object of an rvalue.
  1335. static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
  1336. APValue &Obj, QualType ObjType,
  1337. const SubobjectDesignator &Sub, QualType SubType) {
  1338. if (Sub.Invalid)
  1339. // A diagnostic will have already been produced.
  1340. return false;
  1341. if (Sub.isOnePastTheEnd()) {
  1342. Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
  1343. (unsigned)diag::note_constexpr_read_past_end :
  1344. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1345. return false;
  1346. }
  1347. if (Sub.Entries.empty())
  1348. return true;
  1349. if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
  1350. // This object might be initialized later.
  1351. return false;
  1352. APValue *O = &Obj;
  1353. // Walk the designator's path to find the subobject.
  1354. for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
  1355. if (ObjType->isArrayType()) {
  1356. // Next subobject is an array element.
  1357. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  1358. assert(CAT && "vla in literal type?");
  1359. uint64_t Index = Sub.Entries[I].ArrayIndex;
  1360. if (CAT->getSize().ule(Index)) {
  1361. // Note, it should not be possible to form a pointer with a valid
  1362. // designator which points more than one past the end of the array.
  1363. Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
  1364. (unsigned)diag::note_constexpr_read_past_end :
  1365. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1366. return false;
  1367. }
  1368. // An array object is represented as either an Array APValue or as an
  1369. // LValue which refers to a string literal.
  1370. if (O->isLValue()) {
  1371. assert(I == N - 1 && "extracting subobject of character?");
  1372. assert(!O->hasLValuePath() || O->getLValuePath().empty());
  1373. Obj = APValue(ExtractStringLiteralCharacter(
  1374. Info, O->getLValueBase().get<const Expr*>(), Index));
  1375. return true;
  1376. } else if (O->getArrayInitializedElts() > Index)
  1377. O = &O->getArrayInitializedElt(Index);
  1378. else
  1379. O = &O->getArrayFiller();
  1380. ObjType = CAT->getElementType();
  1381. } else if (ObjType->isAnyComplexType()) {
  1382. // Next subobject is a complex number.
  1383. uint64_t Index = Sub.Entries[I].ArrayIndex;
  1384. if (Index > 1) {
  1385. Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
  1386. (unsigned)diag::note_constexpr_read_past_end :
  1387. (unsigned)diag::note_invalid_subexpr_in_const_expr);
  1388. return false;
  1389. }
  1390. assert(I == N - 1 && "extracting subobject of scalar?");
  1391. if (O->isComplexInt()) {
  1392. Obj = APValue(Index ? O->getComplexIntImag()
  1393. : O->getComplexIntReal());
  1394. } else {
  1395. assert(O->isComplexFloat());
  1396. Obj = APValue(Index ? O->getComplexFloatImag()
  1397. : O->getComplexFloatReal());
  1398. }
  1399. return true;
  1400. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  1401. if (Field->isMutable()) {
  1402. Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
  1403. << Field;
  1404. Info.Note(Field->getLocation(), diag::note_declared_at);
  1405. return false;
  1406. }
  1407. // Next subobject is a class, struct or union field.
  1408. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  1409. if (RD->isUnion()) {
  1410. const FieldDecl *UnionField = O->getUnionField();
  1411. if (!UnionField ||
  1412. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  1413. Info.Diag(E->getExprLoc(),
  1414. diag::note_constexpr_read_inactive_union_member)
  1415. << Field << !UnionField << UnionField;
  1416. return false;
  1417. }
  1418. O = &O->getUnionValue();
  1419. } else
  1420. O = &O->getStructField(Field->getFieldIndex());
  1421. ObjType = Field->getType();
  1422. if (ObjType.isVolatileQualified()) {
  1423. if (Info.getLangOpts().CPlusPlus) {
  1424. // FIXME: Include a description of the path to the volatile subobject.
  1425. Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
  1426. << 2 << Field;
  1427. Info.Note(Field->getLocation(), diag::note_declared_at);
  1428. } else {
  1429. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1430. }
  1431. return false;
  1432. }
  1433. } else {
  1434. // Next subobject is a base class.
  1435. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  1436. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  1437. O = &O->getStructBase(getBaseIndex(Derived, Base));
  1438. ObjType = Info.Ctx.getRecordType(Base);
  1439. }
  1440. if (O->isUninit()) {
  1441. if (!Info.CheckingPotentialConstantExpression)
  1442. Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
  1443. return false;
  1444. }
  1445. }
  1446. // This may look super-stupid, but it serves an important purpose: if we just
  1447. // swapped Obj and *O, we'd create an object which had itself as a subobject.
  1448. // To avoid the leak, we ensure that Tmp ends up owning the original complete
  1449. // object, which is destroyed by Tmp's destructor.
  1450. APValue Tmp;
  1451. O->swap(Tmp);
  1452. Obj.swap(Tmp);
  1453. return true;
  1454. }
  1455. /// Find the position where two subobject designators diverge, or equivalently
  1456. /// the length of the common initial subsequence.
  1457. static unsigned FindDesignatorMismatch(QualType ObjType,
  1458. const SubobjectDesignator &A,
  1459. const SubobjectDesignator &B,
  1460. bool &WasArrayIndex) {
  1461. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  1462. for (/**/; I != N; ++I) {
  1463. if (!ObjType.isNull() &&
  1464. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  1465. // Next subobject is an array element.
  1466. if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
  1467. WasArrayIndex = true;
  1468. return I;
  1469. }
  1470. if (ObjType->isAnyComplexType())
  1471. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  1472. else
  1473. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  1474. } else {
  1475. if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
  1476. WasArrayIndex = false;
  1477. return I;
  1478. }
  1479. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  1480. // Next subobject is a field.
  1481. ObjType = FD->getType();
  1482. else
  1483. // Next subobject is a base class.
  1484. ObjType = QualType();
  1485. }
  1486. }
  1487. WasArrayIndex = false;
  1488. return I;
  1489. }
  1490. /// Determine whether the given subobject designators refer to elements of the
  1491. /// same array object.
  1492. static bool AreElementsOfSameArray(QualType ObjType,
  1493. const SubobjectDesignator &A,
  1494. const SubobjectDesignator &B) {
  1495. if (A.Entries.size() != B.Entries.size())
  1496. return false;
  1497. bool IsArray = A.MostDerivedArraySize != 0;
  1498. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  1499. // A is a subobject of the array element.
  1500. return false;
  1501. // If A (and B) designates an array element, the last entry will be the array
  1502. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  1503. // of length 1' case, and the entire path must match.
  1504. bool WasArrayIndex;
  1505. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  1506. return CommonLength >= A.Entries.size() - IsArray;
  1507. }
  1508. /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
  1509. /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
  1510. /// for looking up the glvalue referred to by an entity of reference type.
  1511. ///
  1512. /// \param Info - Information about the ongoing evaluation.
  1513. /// \param Conv - The expression for which we are performing the conversion.
  1514. /// Used for diagnostics.
  1515. /// \param Type - The type we expect this conversion to produce, before
  1516. /// stripping cv-qualifiers in the case of a non-clas type.
  1517. /// \param LVal - The glvalue on which we are attempting to perform this action.
  1518. /// \param RVal - The produced value will be placed here.
  1519. static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  1520. QualType Type,
  1521. const LValue &LVal, APValue &RVal) {
  1522. if (LVal.Designator.Invalid)
  1523. // A diagnostic will have already been produced.
  1524. return false;
  1525. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  1526. SourceLocation Loc = Conv->getExprLoc();
  1527. if (!LVal.Base) {
  1528. // FIXME: Indirection through a null pointer deserves a specific diagnostic.
  1529. Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
  1530. return false;
  1531. }
  1532. CallStackFrame *Frame = 0;
  1533. if (LVal.CallIndex) {
  1534. Frame = Info.getCallFrame(LVal.CallIndex);
  1535. if (!Frame) {
  1536. Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
  1537. NoteLValueLocation(Info, LVal.Base);
  1538. return false;
  1539. }
  1540. }
  1541. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  1542. // is not a constant expression (even if the object is non-volatile). We also
  1543. // apply this rule to C++98, in order to conform to the expected 'volatile'
  1544. // semantics.
  1545. if (Type.isVolatileQualified()) {
  1546. if (Info.getLangOpts().CPlusPlus)
  1547. Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
  1548. else
  1549. Info.Diag(Loc);
  1550. return false;
  1551. }
  1552. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  1553. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  1554. // In C++11, constexpr, non-volatile variables initialized with constant
  1555. // expressions are constant expressions too. Inside constexpr functions,
  1556. // parameters are constant expressions even if they're non-const.
  1557. // In C, such things can also be folded, although they are not ICEs.
  1558. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1559. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  1560. VD = VDef;
  1561. if (!VD || VD->isInvalidDecl()) {
  1562. Info.Diag(Loc);
  1563. return false;
  1564. }
  1565. // DR1313: If the object is volatile-qualified but the glvalue was not,
  1566. // behavior is undefined so the result is not a constant expression.
  1567. QualType VT = VD->getType();
  1568. if (VT.isVolatileQualified()) {
  1569. if (Info.getLangOpts().CPlusPlus) {
  1570. Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
  1571. Info.Note(VD->getLocation(), diag::note_declared_at);
  1572. } else {
  1573. Info.Diag(Loc);
  1574. }
  1575. return false;
  1576. }
  1577. if (!isa<ParmVarDecl>(VD)) {
  1578. if (VD->isConstexpr()) {
  1579. // OK, we can read this variable.
  1580. } else if (VT->isIntegralOrEnumerationType()) {
  1581. if (!VT.isConstQualified()) {
  1582. if (Info.getLangOpts().CPlusPlus) {
  1583. Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  1584. Info.Note(VD->getLocation(), diag::note_declared_at);
  1585. } else {
  1586. Info.Diag(Loc);
  1587. }
  1588. return false;
  1589. }
  1590. } else if (VT->isFloatingType() && VT.isConstQualified()) {
  1591. // We support folding of const floating-point types, in order to make
  1592. // static const data members of such types (supported as an extension)
  1593. // more useful.
  1594. if (Info.getLangOpts().CPlusPlus0x) {
  1595. Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  1596. Info.Note(VD->getLocation(), diag::note_declared_at);
  1597. } else {
  1598. Info.CCEDiag(Loc);
  1599. }
  1600. } else {
  1601. // FIXME: Allow folding of values of any literal type in all languages.
  1602. if (Info.getLangOpts().CPlusPlus0x) {
  1603. Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  1604. Info.Note(VD->getLocation(), diag::note_declared_at);
  1605. } else {
  1606. Info.Diag(Loc);
  1607. }
  1608. return false;
  1609. }
  1610. }
  1611. if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
  1612. return false;
  1613. if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
  1614. return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
  1615. // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
  1616. // conversion. This happens when the declaration and the lvalue should be
  1617. // considered synonymous, for instance when initializing an array of char
  1618. // from a string literal. Continue as if the initializer lvalue was the
  1619. // value we were originally given.
  1620. assert(RVal.getLValueOffset().isZero() &&
  1621. "offset for lvalue init of non-reference");
  1622. Base = RVal.getLValueBase().get<const Expr*>();
  1623. if (unsigned CallIndex = RVal.getLValueCallIndex()) {
  1624. Frame = Info.getCallFrame(CallIndex);
  1625. if (!Frame) {
  1626. Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
  1627. NoteLValueLocation(Info, RVal.getLValueBase());
  1628. return false;
  1629. }
  1630. } else {
  1631. Frame = 0;
  1632. }
  1633. }
  1634. // Volatile temporary objects cannot be read in constant expressions.
  1635. if (Base->getType().isVolatileQualified()) {
  1636. if (Info.getLangOpts().CPlusPlus) {
  1637. Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
  1638. Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
  1639. } else {
  1640. Info.Diag(Loc);
  1641. }
  1642. return false;
  1643. }
  1644. if (Frame) {
  1645. // If this is a temporary expression with a nontrivial initializer, grab the
  1646. // value from the relevant stack frame.
  1647. RVal = Frame->Temporaries[Base];
  1648. } else if (const CompoundLiteralExpr *CLE
  1649. = dyn_cast<CompoundLiteralExpr>(Base)) {
  1650. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  1651. // initializer until now for such expressions. Such an expression can't be
  1652. // an ICE in C, so this only matters for fold.
  1653. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  1654. if (!Evaluate(RVal, Info, CLE->getInitializer()))
  1655. return false;
  1656. } else if (isa<StringLiteral>(Base)) {
  1657. // We represent a string literal array as an lvalue pointing at the
  1658. // corresponding expression, rather than building an array of chars.
  1659. // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
  1660. RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
  1661. } else {
  1662. Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  1663. return false;
  1664. }
  1665. return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
  1666. Type);
  1667. }
  1668. /// Build an lvalue for the object argument of a member function call.
  1669. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  1670. LValue &This) {
  1671. if (Object->getType()->isPointerType())
  1672. return EvaluatePointer(Object, This, Info);
  1673. if (Object->isGLValue())
  1674. return EvaluateLValue(Object, This, Info);
  1675. if (Object->getType()->isLiteralType())
  1676. return EvaluateTemporary(Object, This, Info);
  1677. return false;
  1678. }
  1679. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  1680. /// lvalue referring to the result.
  1681. ///
  1682. /// \param Info - Information about the ongoing evaluation.
  1683. /// \param BO - The member pointer access operation.
  1684. /// \param LV - Filled in with a reference to the resulting object.
  1685. /// \param IncludeMember - Specifies whether the member itself is included in
  1686. /// the resulting LValue subobject designator. This is not possible when
  1687. /// creating a bound member function.
  1688. /// \return The field or method declaration to which the member pointer refers,
  1689. /// or 0 if evaluation fails.
  1690. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  1691. const BinaryOperator *BO,
  1692. LValue &LV,
  1693. bool IncludeMember = true) {
  1694. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  1695. bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
  1696. if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
  1697. return 0;
  1698. MemberPtr MemPtr;
  1699. if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
  1700. return 0;
  1701. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  1702. // member value, the behavior is undefined.
  1703. if (!MemPtr.getDecl())
  1704. return 0;
  1705. if (!EvalObjOK)
  1706. return 0;
  1707. if (MemPtr.isDerivedMember()) {
  1708. // This is a member of some derived class. Truncate LV appropriately.
  1709. // The end of the derived-to-base path for the base object must match the
  1710. // derived-to-base path for the member pointer.
  1711. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  1712. LV.Designator.Entries.size())
  1713. return 0;
  1714. unsigned PathLengthToMember =
  1715. LV.Designator.Entries.size() - MemPtr.Path.size();
  1716. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  1717. const CXXRecordDecl *LVDecl = getAsBaseClass(
  1718. LV.Designator.Entries[PathLengthToMember + I]);
  1719. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  1720. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
  1721. return 0;
  1722. }
  1723. // Truncate the lvalue to the appropriate derived class.
  1724. if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
  1725. PathLengthToMember))
  1726. return 0;
  1727. } else if (!MemPtr.Path.empty()) {
  1728. // Extend the LValue path with the member pointer's path.
  1729. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  1730. MemPtr.Path.size() + IncludeMember);
  1731. // Walk down to the appropriate base class.
  1732. QualType LVType = BO->getLHS()->getType();
  1733. if (const PointerType *PT = LVType->getAs<PointerType>())
  1734. LVType = PT->getPointeeType();
  1735. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  1736. assert(RD && "member pointer access on non-class-type expression");
  1737. // The first class in the path is that of the lvalue.
  1738. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  1739. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  1740. HandleLValueDirectBase(Info, BO, LV, RD, Base);
  1741. RD = Base;
  1742. }
  1743. // Finally cast to the class containing the member.
  1744. HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
  1745. }
  1746. // Add the member. Note that we cannot build bound member functions here.
  1747. if (IncludeMember) {
  1748. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
  1749. HandleLValueMember(Info, BO, LV, FD);
  1750. else if (const IndirectFieldDecl *IFD =
  1751. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
  1752. HandleLValueIndirectMember(Info, BO, LV, IFD);
  1753. else
  1754. llvm_unreachable("can't construct reference to bound member function");
  1755. }
  1756. return MemPtr.getDecl();
  1757. }
  1758. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  1759. /// the provided lvalue, which currently refers to the base object.
  1760. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  1761. LValue &Result) {
  1762. SubobjectDesignator &D = Result.Designator;
  1763. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  1764. return false;
  1765. QualType TargetQT = E->getType();
  1766. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  1767. TargetQT = PT->getPointeeType();
  1768. // Check this cast lands within the final derived-to-base subobject path.
  1769. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  1770. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
  1771. << D.MostDerivedType << TargetQT;
  1772. return false;
  1773. }
  1774. // Check the type of the final cast. We don't need to check the path,
  1775. // since a cast can only be formed if the path is unique.
  1776. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  1777. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  1778. const CXXRecordDecl *FinalType;
  1779. if (NewEntriesSize == D.MostDerivedPathLength)
  1780. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  1781. else
  1782. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  1783. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  1784. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
  1785. << D.MostDerivedType << TargetQT;
  1786. return false;
  1787. }
  1788. // Truncate the lvalue to the appropriate derived class.
  1789. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  1790. }
  1791. namespace {
  1792. enum EvalStmtResult {
  1793. /// Evaluation failed.
  1794. ESR_Failed,
  1795. /// Hit a 'return' statement.
  1796. ESR_Returned,
  1797. /// Evaluation succeeded.
  1798. ESR_Succeeded
  1799. };
  1800. }
  1801. // Evaluate a statement.
  1802. static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
  1803. const Stmt *S) {
  1804. switch (S->getStmtClass()) {
  1805. default:
  1806. return ESR_Failed;
  1807. case Stmt::NullStmtClass:
  1808. case Stmt::DeclStmtClass:
  1809. return ESR_Succeeded;
  1810. case Stmt::ReturnStmtClass: {
  1811. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  1812. if (!Evaluate(Result, Info, RetExpr))
  1813. return ESR_Failed;
  1814. return ESR_Returned;
  1815. }
  1816. case Stmt::CompoundStmtClass: {
  1817. const CompoundStmt *CS = cast<CompoundStmt>(S);
  1818. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  1819. BE = CS->body_end(); BI != BE; ++BI) {
  1820. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  1821. if (ESR != ESR_Succeeded)
  1822. return ESR;
  1823. }
  1824. return ESR_Succeeded;
  1825. }
  1826. }
  1827. }
  1828. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  1829. /// default constructor. If so, we'll fold it whether or not it's marked as
  1830. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  1831. /// so we need special handling.
  1832. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  1833. const CXXConstructorDecl *CD,
  1834. bool IsValueInitialization) {
  1835. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  1836. return false;
  1837. // Value-initialization does not call a trivial default constructor, so such a
  1838. // call is a core constant expression whether or not the constructor is
  1839. // constexpr.
  1840. if (!CD->isConstexpr() && !IsValueInitialization) {
  1841. if (Info.getLangOpts().CPlusPlus0x) {
  1842. // FIXME: If DiagDecl is an implicitly-declared special member function,
  1843. // we should be much more explicit about why it's not constexpr.
  1844. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  1845. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  1846. Info.Note(CD->getLocation(), diag::note_declared_at);
  1847. } else {
  1848. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  1849. }
  1850. }
  1851. return true;
  1852. }
  1853. /// CheckConstexprFunction - Check that a function can be called in a constant
  1854. /// expression.
  1855. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  1856. const FunctionDecl *Declaration,
  1857. const FunctionDecl *Definition) {
  1858. // Potential constant expressions can contain calls to declared, but not yet
  1859. // defined, constexpr functions.
  1860. if (Info.CheckingPotentialConstantExpression && !Definition &&
  1861. Declaration->isConstexpr())
  1862. return false;
  1863. // Can we evaluate this function call?
  1864. if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
  1865. return true;
  1866. if (Info.getLangOpts().CPlusPlus0x) {
  1867. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  1868. // FIXME: If DiagDecl is an implicitly-declared special member function, we
  1869. // should be much more explicit about why it's not constexpr.
  1870. Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
  1871. << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
  1872. << DiagDecl;
  1873. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  1874. } else {
  1875. Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  1876. }
  1877. return false;
  1878. }
  1879. namespace {
  1880. typedef SmallVector<APValue, 8> ArgVector;
  1881. }
  1882. /// EvaluateArgs - Evaluate the arguments to a function call.
  1883. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  1884. EvalInfo &Info) {
  1885. bool Success = true;
  1886. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  1887. I != E; ++I) {
  1888. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  1889. // If we're checking for a potential constant expression, evaluate all
  1890. // initializers even if some of them fail.
  1891. if (!Info.keepEvaluatingAfterFailure())
  1892. return false;
  1893. Success = false;
  1894. }
  1895. }
  1896. return Success;
  1897. }
  1898. /// Evaluate a function call.
  1899. static bool HandleFunctionCall(SourceLocation CallLoc,
  1900. const FunctionDecl *Callee, const LValue *This,
  1901. ArrayRef<const Expr*> Args, const Stmt *Body,
  1902. EvalInfo &Info, APValue &Result) {
  1903. ArgVector ArgValues(Args.size());
  1904. if (!EvaluateArgs(Args, ArgValues, Info))
  1905. return false;
  1906. if (!Info.CheckCallLimit(CallLoc))
  1907. return false;
  1908. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  1909. return EvaluateStmt(Result, Info, Body) == ESR_Returned;
  1910. }
  1911. /// Evaluate a constructor call.
  1912. static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
  1913. ArrayRef<const Expr*> Args,
  1914. const CXXConstructorDecl *Definition,
  1915. EvalInfo &Info, APValue &Result) {
  1916. ArgVector ArgValues(Args.size());
  1917. if (!EvaluateArgs(Args, ArgValues, Info))
  1918. return false;
  1919. if (!Info.CheckCallLimit(CallLoc))
  1920. return false;
  1921. const CXXRecordDecl *RD = Definition->getParent();
  1922. if (RD->getNumVBases()) {
  1923. Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  1924. return false;
  1925. }
  1926. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
  1927. // If it's a delegating constructor, just delegate.
  1928. if (Definition->isDelegatingConstructor()) {
  1929. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  1930. return EvaluateInPlace(Result, Info, This, (*I)->getInit());
  1931. }
  1932. // For a trivial copy or move constructor, perform an APValue copy. This is
  1933. // essential for unions, where the operations performed by the constructor
  1934. // cannot be represented by ctor-initializers.
  1935. if (Definition->isDefaulted() &&
  1936. ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
  1937. (Definition->isMoveConstructor() && Definition->isTrivial()))) {
  1938. LValue RHS;
  1939. RHS.setFrom(Info.Ctx, ArgValues[0]);
  1940. return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  1941. RHS, Result);
  1942. }
  1943. // Reserve space for the struct members.
  1944. if (!RD->isUnion() && Result.isUninit())
  1945. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  1946. std::distance(RD->field_begin(), RD->field_end()));
  1947. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  1948. bool Success = true;
  1949. unsigned BasesSeen = 0;
  1950. #ifndef NDEBUG
  1951. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  1952. #endif
  1953. for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
  1954. E = Definition->init_end(); I != E; ++I) {
  1955. LValue Subobject = This;
  1956. APValue *Value = &Result;
  1957. // Determine the subobject to initialize.
  1958. if ((*I)->isBaseInitializer()) {
  1959. QualType BaseType((*I)->getBaseClass(), 0);
  1960. #ifndef NDEBUG
  1961. // Non-virtual base classes are initialized in the order in the class
  1962. // definition. We have already checked for virtual base classes.
  1963. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  1964. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  1965. "base class initializers not in expected order");
  1966. ++BaseIt;
  1967. #endif
  1968. HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
  1969. BaseType->getAsCXXRecordDecl(), &Layout);
  1970. Value = &Result.getStructBase(BasesSeen++);
  1971. } else if (FieldDecl *FD = (*I)->getMember()) {
  1972. HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
  1973. if (RD->isUnion()) {
  1974. Result = APValue(FD);
  1975. Value = &Result.getUnionValue();
  1976. } else {
  1977. Value = &Result.getStructField(FD->getFieldIndex());
  1978. }
  1979. } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
  1980. // Walk the indirect field decl's chain to find the object to initialize,
  1981. // and make sure we've initialized every step along it.
  1982. for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
  1983. CE = IFD->chain_end();
  1984. C != CE; ++C) {
  1985. FieldDecl *FD = cast<FieldDecl>(*C);
  1986. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  1987. // Switch the union field if it differs. This happens if we had
  1988. // preceding zero-initialization, and we're now initializing a union
  1989. // subobject other than the first.
  1990. // FIXME: In this case, the values of the other subobjects are
  1991. // specified, since zero-initialization sets all padding bits to zero.
  1992. if (Value->isUninit() ||
  1993. (Value->isUnion() && Value->getUnionField() != FD)) {
  1994. if (CD->isUnion())
  1995. *Value = APValue(FD);
  1996. else
  1997. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  1998. std::distance(CD->field_begin(), CD->field_end()));
  1999. }
  2000. HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
  2001. if (CD->isUnion())
  2002. Value = &Value->getUnionValue();
  2003. else
  2004. Value = &Value->getStructField(FD->getFieldIndex());
  2005. }
  2006. } else {
  2007. llvm_unreachable("unknown base initializer kind");
  2008. }
  2009. if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
  2010. (*I)->isBaseInitializer()
  2011. ? CCEK_Constant : CCEK_MemberInit)) {
  2012. // If we're checking for a potential constant expression, evaluate all
  2013. // initializers even if some of them fail.
  2014. if (!Info.keepEvaluatingAfterFailure())
  2015. return false;
  2016. Success = false;
  2017. }
  2018. }
  2019. return Success;
  2020. }
  2021. namespace {
  2022. class HasSideEffect
  2023. : public ConstStmtVisitor<HasSideEffect, bool> {
  2024. const ASTContext &Ctx;
  2025. public:
  2026. HasSideEffect(const ASTContext &C) : Ctx(C) {}
  2027. // Unhandled nodes conservatively default to having side effects.
  2028. bool VisitStmt(const Stmt *S) {
  2029. return true;
  2030. }
  2031. bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
  2032. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
  2033. return Visit(E->getResultExpr());
  2034. }
  2035. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2036. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  2037. return true;
  2038. return false;
  2039. }
  2040. bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
  2041. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  2042. return true;
  2043. return false;
  2044. }
  2045. // We don't want to evaluate BlockExprs multiple times, as they generate
  2046. // a ton of code.
  2047. bool VisitBlockExpr(const BlockExpr *E) { return true; }
  2048. bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
  2049. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
  2050. { return Visit(E->getInitializer()); }
  2051. bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
  2052. bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
  2053. bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
  2054. bool VisitStringLiteral(const StringLiteral *E) { return false; }
  2055. bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
  2056. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
  2057. { return false; }
  2058. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
  2059. { return Visit(E->getLHS()) || Visit(E->getRHS()); }
  2060. bool VisitChooseExpr(const ChooseExpr *E)
  2061. { return Visit(E->getChosenSubExpr(Ctx)); }
  2062. bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
  2063. bool VisitBinAssign(const BinaryOperator *E) { return true; }
  2064. bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
  2065. bool VisitBinaryOperator(const BinaryOperator *E)
  2066. { return Visit(E->getLHS()) || Visit(E->getRHS()); }
  2067. bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
  2068. bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
  2069. bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
  2070. bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
  2071. bool VisitUnaryDeref(const UnaryOperator *E) {
  2072. if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
  2073. return true;
  2074. return Visit(E->getSubExpr());
  2075. }
  2076. bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
  2077. // Has side effects if any element does.
  2078. bool VisitInitListExpr(const InitListExpr *E) {
  2079. for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
  2080. if (Visit(E->getInit(i))) return true;
  2081. if (const Expr *filler = E->getArrayFiller())
  2082. return Visit(filler);
  2083. return false;
  2084. }
  2085. bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
  2086. };
  2087. class OpaqueValueEvaluation {
  2088. EvalInfo &info;
  2089. OpaqueValueExpr *opaqueValue;
  2090. public:
  2091. OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
  2092. Expr *value)
  2093. : info(info), opaqueValue(opaqueValue) {
  2094. // If evaluation fails, fail immediately.
  2095. if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
  2096. this->opaqueValue = 0;
  2097. return;
  2098. }
  2099. }
  2100. bool hasError() const { return opaqueValue == 0; }
  2101. ~OpaqueValueEvaluation() {
  2102. // FIXME: For a recursive constexpr call, an outer stack frame might have
  2103. // been using this opaque value too, and will now have to re-evaluate the
  2104. // source expression.
  2105. if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
  2106. }
  2107. };
  2108. } // end anonymous namespace
  2109. //===----------------------------------------------------------------------===//
  2110. // Generic Evaluation
  2111. //===----------------------------------------------------------------------===//
  2112. namespace {
  2113. // FIXME: RetTy is always bool. Remove it.
  2114. template <class Derived, typename RetTy=bool>
  2115. class ExprEvaluatorBase
  2116. : public ConstStmtVisitor<Derived, RetTy> {
  2117. private:
  2118. RetTy DerivedSuccess(const APValue &V, const Expr *E) {
  2119. return static_cast<Derived*>(this)->Success(V, E);
  2120. }
  2121. RetTy DerivedZeroInitialization(const Expr *E) {
  2122. return static_cast<Derived*>(this)->ZeroInitialization(E);
  2123. }
  2124. // Check whether a conditional operator with a non-constant condition is a
  2125. // potential constant expression. If neither arm is a potential constant
  2126. // expression, then the conditional operator is not either.
  2127. template<typename ConditionalOperator>
  2128. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  2129. assert(Info.CheckingPotentialConstantExpression);
  2130. // Speculatively evaluate both arms.
  2131. {
  2132. llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
  2133. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  2134. StmtVisitorTy::Visit(E->getFalseExpr());
  2135. if (Diag.empty())
  2136. return;
  2137. Diag.clear();
  2138. StmtVisitorTy::Visit(E->getTrueExpr());
  2139. if (Diag.empty())
  2140. return;
  2141. }
  2142. Error(E, diag::note_constexpr_conditional_never_const);
  2143. }
  2144. template<typename ConditionalOperator>
  2145. bool HandleConditionalOperator(const ConditionalOperator *E) {
  2146. bool BoolResult;
  2147. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  2148. if (Info.CheckingPotentialConstantExpression)
  2149. CheckPotentialConstantConditional(E);
  2150. return false;
  2151. }
  2152. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  2153. return StmtVisitorTy::Visit(EvalExpr);
  2154. }
  2155. protected:
  2156. EvalInfo &Info;
  2157. typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
  2158. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  2159. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  2160. return Info.CCEDiag(E->getExprLoc(), D);
  2161. }
  2162. /// Report an evaluation error. This should only be called when an error is
  2163. /// first discovered. When propagating an error, just return false.
  2164. bool Error(const Expr *E, diag::kind D) {
  2165. Info.Diag(E->getExprLoc(), D);
  2166. return false;
  2167. }
  2168. bool Error(const Expr *E) {
  2169. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  2170. }
  2171. RetTy ZeroInitialization(const Expr *E) { return Error(E); }
  2172. public:
  2173. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  2174. RetTy VisitStmt(const Stmt *) {
  2175. llvm_unreachable("Expression evaluator should not be called on stmts");
  2176. }
  2177. RetTy VisitExpr(const Expr *E) {
  2178. return Error(E);
  2179. }
  2180. RetTy VisitParenExpr(const ParenExpr *E)
  2181. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2182. RetTy VisitUnaryExtension(const UnaryOperator *E)
  2183. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2184. RetTy VisitUnaryPlus(const UnaryOperator *E)
  2185. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2186. RetTy VisitChooseExpr(const ChooseExpr *E)
  2187. { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
  2188. RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  2189. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  2190. RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  2191. { return StmtVisitorTy::Visit(E->getReplacement()); }
  2192. RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
  2193. { return StmtVisitorTy::Visit(E->getExpr()); }
  2194. // We cannot create any objects for which cleanups are required, so there is
  2195. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  2196. RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
  2197. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  2198. RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  2199. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  2200. return static_cast<Derived*>(this)->VisitCastExpr(E);
  2201. }
  2202. RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  2203. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  2204. return static_cast<Derived*>(this)->VisitCastExpr(E);
  2205. }
  2206. RetTy VisitBinaryOperator(const BinaryOperator *E) {
  2207. switch (E->getOpcode()) {
  2208. default:
  2209. return Error(E);
  2210. case BO_Comma:
  2211. VisitIgnoredValue(E->getLHS());
  2212. return StmtVisitorTy::Visit(E->getRHS());
  2213. case BO_PtrMemD:
  2214. case BO_PtrMemI: {
  2215. LValue Obj;
  2216. if (!HandleMemberPointerAccess(Info, E, Obj))
  2217. return false;
  2218. APValue Result;
  2219. if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  2220. return false;
  2221. return DerivedSuccess(Result, E);
  2222. }
  2223. }
  2224. }
  2225. RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  2226. // Cache the value of the common expression.
  2227. OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
  2228. if (opaque.hasError())
  2229. return false;
  2230. return HandleConditionalOperator(E);
  2231. }
  2232. RetTy VisitConditionalOperator(const ConditionalOperator *E) {
  2233. bool IsBcpCall = false;
  2234. // If the condition (ignoring parens) is a __builtin_constant_p call,
  2235. // the result is a constant expression if it can be folded without
  2236. // side-effects. This is an important GNU extension. See GCC PR38377
  2237. // for discussion.
  2238. if (const CallExpr *CallCE =
  2239. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  2240. if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
  2241. IsBcpCall = true;
  2242. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  2243. // constant expression; we can't check whether it's potentially foldable.
  2244. if (Info.CheckingPotentialConstantExpression && IsBcpCall)
  2245. return false;
  2246. FoldConstant Fold(Info);
  2247. if (!HandleConditionalOperator(E))
  2248. return false;
  2249. if (IsBcpCall)
  2250. Fold.Fold(Info);
  2251. return true;
  2252. }
  2253. RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  2254. const APValue *Value = Info.getOpaqueValue(E);
  2255. if (!Value) {
  2256. const Expr *Source = E->getSourceExpr();
  2257. if (!Source)
  2258. return Error(E);
  2259. if (Source == E) { // sanity checking.
  2260. assert(0 && "OpaqueValueExpr recursively refers to itself");
  2261. return Error(E);
  2262. }
  2263. return StmtVisitorTy::Visit(Source);
  2264. }
  2265. return DerivedSuccess(*Value, E);
  2266. }
  2267. RetTy VisitCallExpr(const CallExpr *E) {
  2268. const Expr *Callee = E->getCallee()->IgnoreParens();
  2269. QualType CalleeType = Callee->getType();
  2270. const FunctionDecl *FD = 0;
  2271. LValue *This = 0, ThisVal;
  2272. llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
  2273. bool HasQualifier = false;
  2274. // Extract function decl and 'this' pointer from the callee.
  2275. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  2276. const ValueDecl *Member = 0;
  2277. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  2278. // Explicit bound member calls, such as x.f() or p->g();
  2279. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  2280. return false;
  2281. Member = ME->getMemberDecl();
  2282. This = &ThisVal;
  2283. HasQualifier = ME->hasQualifier();
  2284. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  2285. // Indirect bound member calls ('.*' or '->*').
  2286. Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
  2287. if (!Member) return false;
  2288. This = &ThisVal;
  2289. } else
  2290. return Error(Callee);
  2291. FD = dyn_cast<FunctionDecl>(Member);
  2292. if (!FD)
  2293. return Error(Callee);
  2294. } else if (CalleeType->isFunctionPointerType()) {
  2295. LValue Call;
  2296. if (!EvaluatePointer(Callee, Call, Info))
  2297. return false;
  2298. if (!Call.getLValueOffset().isZero())
  2299. return Error(Callee);
  2300. FD = dyn_cast_or_null<FunctionDecl>(
  2301. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  2302. if (!FD)
  2303. return Error(Callee);
  2304. // Overloaded operator calls to member functions are represented as normal
  2305. // calls with '*this' as the first argument.
  2306. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  2307. if (MD && !MD->isStatic()) {
  2308. // FIXME: When selecting an implicit conversion for an overloaded
  2309. // operator delete, we sometimes try to evaluate calls to conversion
  2310. // operators without a 'this' parameter!
  2311. if (Args.empty())
  2312. return Error(E);
  2313. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  2314. return false;
  2315. This = &ThisVal;
  2316. Args = Args.slice(1);
  2317. }
  2318. // Don't call function pointers which have been cast to some other type.
  2319. if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
  2320. return Error(E);
  2321. } else
  2322. return Error(E);
  2323. if (This && !This->checkSubobject(Info, E, CSK_This))
  2324. return false;
  2325. // DR1358 allows virtual constexpr functions in some cases. Don't allow
  2326. // calls to such functions in constant expressions.
  2327. if (This && !HasQualifier &&
  2328. isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
  2329. return Error(E, diag::note_constexpr_virtual_call);
  2330. const FunctionDecl *Definition = 0;
  2331. Stmt *Body = FD->getBody(Definition);
  2332. APValue Result;
  2333. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
  2334. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
  2335. Info, Result))
  2336. return false;
  2337. return DerivedSuccess(Result, E);
  2338. }
  2339. RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2340. return StmtVisitorTy::Visit(E->getInitializer());
  2341. }
  2342. RetTy VisitInitListExpr(const InitListExpr *E) {
  2343. if (E->getNumInits() == 0)
  2344. return DerivedZeroInitialization(E);
  2345. if (E->getNumInits() == 1)
  2346. return StmtVisitorTy::Visit(E->getInit(0));
  2347. return Error(E);
  2348. }
  2349. RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  2350. return DerivedZeroInitialization(E);
  2351. }
  2352. RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  2353. return DerivedZeroInitialization(E);
  2354. }
  2355. RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  2356. return DerivedZeroInitialization(E);
  2357. }
  2358. /// A member expression where the object is a prvalue is itself a prvalue.
  2359. RetTy VisitMemberExpr(const MemberExpr *E) {
  2360. assert(!E->isArrow() && "missing call to bound member function?");
  2361. APValue Val;
  2362. if (!Evaluate(Val, Info, E->getBase()))
  2363. return false;
  2364. QualType BaseTy = E->getBase()->getType();
  2365. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2366. if (!FD) return Error(E);
  2367. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  2368. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  2369. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  2370. SubobjectDesignator Designator(BaseTy);
  2371. Designator.addDeclUnchecked(FD);
  2372. return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
  2373. DerivedSuccess(Val, E);
  2374. }
  2375. RetTy VisitCastExpr(const CastExpr *E) {
  2376. switch (E->getCastKind()) {
  2377. default:
  2378. break;
  2379. case CK_AtomicToNonAtomic:
  2380. case CK_NonAtomicToAtomic:
  2381. case CK_NoOp:
  2382. case CK_UserDefinedConversion:
  2383. return StmtVisitorTy::Visit(E->getSubExpr());
  2384. case CK_LValueToRValue: {
  2385. LValue LVal;
  2386. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  2387. return false;
  2388. APValue RVal;
  2389. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  2390. if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  2391. LVal, RVal))
  2392. return false;
  2393. return DerivedSuccess(RVal, E);
  2394. }
  2395. }
  2396. return Error(E);
  2397. }
  2398. /// Visit a value which is evaluated, but whose value is ignored.
  2399. void VisitIgnoredValue(const Expr *E) {
  2400. APValue Scratch;
  2401. if (!Evaluate(Scratch, Info, E))
  2402. Info.EvalStatus.HasSideEffects = true;
  2403. }
  2404. };
  2405. }
  2406. //===----------------------------------------------------------------------===//
  2407. // Common base class for lvalue and temporary evaluation.
  2408. //===----------------------------------------------------------------------===//
  2409. namespace {
  2410. template<class Derived>
  2411. class LValueExprEvaluatorBase
  2412. : public ExprEvaluatorBase<Derived, bool> {
  2413. protected:
  2414. LValue &Result;
  2415. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  2416. typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
  2417. bool Success(APValue::LValueBase B) {
  2418. Result.set(B);
  2419. return true;
  2420. }
  2421. public:
  2422. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
  2423. ExprEvaluatorBaseTy(Info), Result(Result) {}
  2424. bool Success(const APValue &V, const Expr *E) {
  2425. Result.setFrom(this->Info.Ctx, V);
  2426. return true;
  2427. }
  2428. bool VisitMemberExpr(const MemberExpr *E) {
  2429. // Handle non-static data members.
  2430. QualType BaseTy;
  2431. if (E->isArrow()) {
  2432. if (!EvaluatePointer(E->getBase(), Result, this->Info))
  2433. return false;
  2434. BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
  2435. } else if (E->getBase()->isRValue()) {
  2436. assert(E->getBase()->getType()->isRecordType());
  2437. if (!EvaluateTemporary(E->getBase(), Result, this->Info))
  2438. return false;
  2439. BaseTy = E->getBase()->getType();
  2440. } else {
  2441. if (!this->Visit(E->getBase()))
  2442. return false;
  2443. BaseTy = E->getBase()->getType();
  2444. }
  2445. const ValueDecl *MD = E->getMemberDecl();
  2446. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  2447. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  2448. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  2449. (void)BaseTy;
  2450. HandleLValueMember(this->Info, E, Result, FD);
  2451. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  2452. HandleLValueIndirectMember(this->Info, E, Result, IFD);
  2453. } else
  2454. return this->Error(E);
  2455. if (MD->getType()->isReferenceType()) {
  2456. APValue RefValue;
  2457. if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  2458. RefValue))
  2459. return false;
  2460. return Success(RefValue, E);
  2461. }
  2462. return true;
  2463. }
  2464. bool VisitBinaryOperator(const BinaryOperator *E) {
  2465. switch (E->getOpcode()) {
  2466. default:
  2467. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  2468. case BO_PtrMemD:
  2469. case BO_PtrMemI:
  2470. return HandleMemberPointerAccess(this->Info, E, Result);
  2471. }
  2472. }
  2473. bool VisitCastExpr(const CastExpr *E) {
  2474. switch (E->getCastKind()) {
  2475. default:
  2476. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2477. case CK_DerivedToBase:
  2478. case CK_UncheckedDerivedToBase: {
  2479. if (!this->Visit(E->getSubExpr()))
  2480. return false;
  2481. // Now figure out the necessary offset to add to the base LV to get from
  2482. // the derived class to the base class.
  2483. QualType Type = E->getSubExpr()->getType();
  2484. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2485. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2486. if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
  2487. *PathI))
  2488. return false;
  2489. Type = (*PathI)->getType();
  2490. }
  2491. return true;
  2492. }
  2493. }
  2494. }
  2495. };
  2496. }
  2497. //===----------------------------------------------------------------------===//
  2498. // LValue Evaluation
  2499. //
  2500. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  2501. // function designators (in C), decl references to void objects (in C), and
  2502. // temporaries (if building with -Wno-address-of-temporary).
  2503. //
  2504. // LValue evaluation produces values comprising a base expression of one of the
  2505. // following types:
  2506. // - Declarations
  2507. // * VarDecl
  2508. // * FunctionDecl
  2509. // - Literals
  2510. // * CompoundLiteralExpr in C
  2511. // * StringLiteral
  2512. // * CXXTypeidExpr
  2513. // * PredefinedExpr
  2514. // * ObjCStringLiteralExpr
  2515. // * ObjCEncodeExpr
  2516. // * AddrLabelExpr
  2517. // * BlockExpr
  2518. // * CallExpr for a MakeStringConstant builtin
  2519. // - Locals and temporaries
  2520. // * Any Expr, with a CallIndex indicating the function in which the temporary
  2521. // was evaluated.
  2522. // plus an offset in bytes.
  2523. //===----------------------------------------------------------------------===//
  2524. namespace {
  2525. class LValueExprEvaluator
  2526. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  2527. public:
  2528. LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
  2529. LValueExprEvaluatorBaseTy(Info, Result) {}
  2530. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  2531. bool VisitDeclRefExpr(const DeclRefExpr *E);
  2532. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  2533. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2534. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  2535. bool VisitMemberExpr(const MemberExpr *E);
  2536. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  2537. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  2538. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  2539. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  2540. bool VisitUnaryDeref(const UnaryOperator *E);
  2541. bool VisitUnaryReal(const UnaryOperator *E);
  2542. bool VisitUnaryImag(const UnaryOperator *E);
  2543. bool VisitCastExpr(const CastExpr *E) {
  2544. switch (E->getCastKind()) {
  2545. default:
  2546. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  2547. case CK_LValueBitCast:
  2548. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2549. if (!Visit(E->getSubExpr()))
  2550. return false;
  2551. Result.Designator.setInvalid();
  2552. return true;
  2553. case CK_BaseToDerived:
  2554. if (!Visit(E->getSubExpr()))
  2555. return false;
  2556. return HandleBaseToDerivedCast(Info, E, Result);
  2557. }
  2558. }
  2559. };
  2560. } // end anonymous namespace
  2561. /// Evaluate an expression as an lvalue. This can be legitimately called on
  2562. /// expressions which are not glvalues, in a few cases:
  2563. /// * function designators in C,
  2564. /// * "extern void" objects,
  2565. /// * temporaries, if building with -Wno-address-of-temporary.
  2566. static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
  2567. assert((E->isGLValue() || E->getType()->isFunctionType() ||
  2568. E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
  2569. "can't evaluate expression as an lvalue");
  2570. return LValueExprEvaluator(Info, Result).Visit(E);
  2571. }
  2572. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  2573. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  2574. return Success(FD);
  2575. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  2576. return VisitVarDecl(E, VD);
  2577. return Error(E);
  2578. }
  2579. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  2580. if (!VD->getType()->isReferenceType()) {
  2581. if (isa<ParmVarDecl>(VD)) {
  2582. Result.set(VD, Info.CurrentCall->Index);
  2583. return true;
  2584. }
  2585. return Success(VD);
  2586. }
  2587. APValue V;
  2588. if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
  2589. return false;
  2590. return Success(V, E);
  2591. }
  2592. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  2593. const MaterializeTemporaryExpr *E) {
  2594. if (E->GetTemporaryExpr()->isRValue()) {
  2595. if (E->getType()->isRecordType())
  2596. return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
  2597. Result.set(E, Info.CurrentCall->Index);
  2598. return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
  2599. Result, E->GetTemporaryExpr());
  2600. }
  2601. // Materialization of an lvalue temporary occurs when we need to force a copy
  2602. // (for instance, if it's a bitfield).
  2603. // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
  2604. if (!Visit(E->GetTemporaryExpr()))
  2605. return false;
  2606. if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
  2607. Info.CurrentCall->Temporaries[E]))
  2608. return false;
  2609. Result.set(E, Info.CurrentCall->Index);
  2610. return true;
  2611. }
  2612. bool
  2613. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2614. assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
  2615. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  2616. // only see this when folding in C, so there's no standard to follow here.
  2617. return Success(E);
  2618. }
  2619. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  2620. if (E->isTypeOperand())
  2621. return Success(E);
  2622. CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
  2623. if (RD && RD->isPolymorphic()) {
  2624. Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
  2625. << E->getExprOperand()->getType()
  2626. << E->getExprOperand()->getSourceRange();
  2627. return false;
  2628. }
  2629. return Success(E);
  2630. }
  2631. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  2632. // Handle static data members.
  2633. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  2634. VisitIgnoredValue(E->getBase());
  2635. return VisitVarDecl(E, VD);
  2636. }
  2637. // Handle static member functions.
  2638. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  2639. if (MD->isStatic()) {
  2640. VisitIgnoredValue(E->getBase());
  2641. return Success(MD);
  2642. }
  2643. }
  2644. // Handle non-static data members.
  2645. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  2646. }
  2647. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  2648. // FIXME: Deal with vectors as array subscript bases.
  2649. if (E->getBase()->getType()->isVectorType())
  2650. return Error(E);
  2651. if (!EvaluatePointer(E->getBase(), Result, Info))
  2652. return false;
  2653. APSInt Index;
  2654. if (!EvaluateInteger(E->getIdx(), Index, Info))
  2655. return false;
  2656. int64_t IndexValue
  2657. = Index.isSigned() ? Index.getSExtValue()
  2658. : static_cast<int64_t>(Index.getZExtValue());
  2659. return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
  2660. }
  2661. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  2662. return EvaluatePointer(E->getSubExpr(), Result, Info);
  2663. }
  2664. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  2665. if (!Visit(E->getSubExpr()))
  2666. return false;
  2667. // __real is a no-op on scalar lvalues.
  2668. if (E->getSubExpr()->getType()->isAnyComplexType())
  2669. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  2670. return true;
  2671. }
  2672. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  2673. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  2674. "lvalue __imag__ on scalar?");
  2675. if (!Visit(E->getSubExpr()))
  2676. return false;
  2677. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  2678. return true;
  2679. }
  2680. //===----------------------------------------------------------------------===//
  2681. // Pointer Evaluation
  2682. //===----------------------------------------------------------------------===//
  2683. namespace {
  2684. class PointerExprEvaluator
  2685. : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
  2686. LValue &Result;
  2687. bool Success(const Expr *E) {
  2688. Result.set(E);
  2689. return true;
  2690. }
  2691. public:
  2692. PointerExprEvaluator(EvalInfo &info, LValue &Result)
  2693. : ExprEvaluatorBaseTy(info), Result(Result) {}
  2694. bool Success(const APValue &V, const Expr *E) {
  2695. Result.setFrom(Info.Ctx, V);
  2696. return true;
  2697. }
  2698. bool ZeroInitialization(const Expr *E) {
  2699. return Success((Expr*)0);
  2700. }
  2701. bool VisitBinaryOperator(const BinaryOperator *E);
  2702. bool VisitCastExpr(const CastExpr* E);
  2703. bool VisitUnaryAddrOf(const UnaryOperator *E);
  2704. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  2705. { return Success(E); }
  2706. bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
  2707. { return Success(E); }
  2708. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  2709. { return Success(E); }
  2710. bool VisitCallExpr(const CallExpr *E);
  2711. bool VisitBlockExpr(const BlockExpr *E) {
  2712. if (!E->getBlockDecl()->hasCaptures())
  2713. return Success(E);
  2714. return Error(E);
  2715. }
  2716. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  2717. if (!Info.CurrentCall->This)
  2718. return Error(E);
  2719. Result = *Info.CurrentCall->This;
  2720. return true;
  2721. }
  2722. // FIXME: Missing: @protocol, @selector
  2723. };
  2724. } // end anonymous namespace
  2725. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
  2726. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  2727. return PointerExprEvaluator(Info, Result).Visit(E);
  2728. }
  2729. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  2730. if (E->getOpcode() != BO_Add &&
  2731. E->getOpcode() != BO_Sub)
  2732. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  2733. const Expr *PExp = E->getLHS();
  2734. const Expr *IExp = E->getRHS();
  2735. if (IExp->getType()->isPointerType())
  2736. std::swap(PExp, IExp);
  2737. bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
  2738. if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
  2739. return false;
  2740. llvm::APSInt Offset;
  2741. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  2742. return false;
  2743. int64_t AdditionalOffset
  2744. = Offset.isSigned() ? Offset.getSExtValue()
  2745. : static_cast<int64_t>(Offset.getZExtValue());
  2746. if (E->getOpcode() == BO_Sub)
  2747. AdditionalOffset = -AdditionalOffset;
  2748. QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
  2749. return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
  2750. AdditionalOffset);
  2751. }
  2752. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  2753. return EvaluateLValue(E->getSubExpr(), Result, Info);
  2754. }
  2755. bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  2756. const Expr* SubExpr = E->getSubExpr();
  2757. switch (E->getCastKind()) {
  2758. default:
  2759. break;
  2760. case CK_BitCast:
  2761. case CK_CPointerToObjCPointerCast:
  2762. case CK_BlockPointerToObjCPointerCast:
  2763. case CK_AnyPointerToBlockPointerCast:
  2764. if (!Visit(SubExpr))
  2765. return false;
  2766. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  2767. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  2768. // also static_casts, but we disallow them as a resolution to DR1312.
  2769. if (!E->getType()->isVoidPointerType()) {
  2770. Result.Designator.setInvalid();
  2771. if (SubExpr->getType()->isVoidPointerType())
  2772. CCEDiag(E, diag::note_constexpr_invalid_cast)
  2773. << 3 << SubExpr->getType();
  2774. else
  2775. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2776. }
  2777. return true;
  2778. case CK_DerivedToBase:
  2779. case CK_UncheckedDerivedToBase: {
  2780. if (!EvaluatePointer(E->getSubExpr(), Result, Info))
  2781. return false;
  2782. if (!Result.Base && Result.Offset.isZero())
  2783. return true;
  2784. // Now figure out the necessary offset to add to the base LV to get from
  2785. // the derived class to the base class.
  2786. QualType Type =
  2787. E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2788. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2789. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2790. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2791. *PathI))
  2792. return false;
  2793. Type = (*PathI)->getType();
  2794. }
  2795. return true;
  2796. }
  2797. case CK_BaseToDerived:
  2798. if (!Visit(E->getSubExpr()))
  2799. return false;
  2800. if (!Result.Base && Result.Offset.isZero())
  2801. return true;
  2802. return HandleBaseToDerivedCast(Info, E, Result);
  2803. case CK_NullToPointer:
  2804. return ZeroInitialization(E);
  2805. case CK_IntegralToPointer: {
  2806. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  2807. APValue Value;
  2808. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  2809. break;
  2810. if (Value.isInt()) {
  2811. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  2812. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  2813. Result.Base = (Expr*)0;
  2814. Result.Offset = CharUnits::fromQuantity(N);
  2815. Result.CallIndex = 0;
  2816. Result.Designator.setInvalid();
  2817. return true;
  2818. } else {
  2819. // Cast is of an lvalue, no need to change value.
  2820. Result.setFrom(Info.Ctx, Value);
  2821. return true;
  2822. }
  2823. }
  2824. case CK_ArrayToPointerDecay:
  2825. if (SubExpr->isGLValue()) {
  2826. if (!EvaluateLValue(SubExpr, Result, Info))
  2827. return false;
  2828. } else {
  2829. Result.set(SubExpr, Info.CurrentCall->Index);
  2830. if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
  2831. Info, Result, SubExpr))
  2832. return false;
  2833. }
  2834. // The result is a pointer to the first element of the array.
  2835. if (const ConstantArrayType *CAT
  2836. = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
  2837. Result.addArray(Info, E, CAT);
  2838. else
  2839. Result.Designator.setInvalid();
  2840. return true;
  2841. case CK_FunctionToPointerDecay:
  2842. return EvaluateLValue(SubExpr, Result, Info);
  2843. }
  2844. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2845. }
  2846. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  2847. if (IsStringLiteralCall(E))
  2848. return Success(E);
  2849. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  2850. }
  2851. //===----------------------------------------------------------------------===//
  2852. // Member Pointer Evaluation
  2853. //===----------------------------------------------------------------------===//
  2854. namespace {
  2855. class MemberPointerExprEvaluator
  2856. : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
  2857. MemberPtr &Result;
  2858. bool Success(const ValueDecl *D) {
  2859. Result = MemberPtr(D);
  2860. return true;
  2861. }
  2862. public:
  2863. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  2864. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  2865. bool Success(const APValue &V, const Expr *E) {
  2866. Result.setFrom(V);
  2867. return true;
  2868. }
  2869. bool ZeroInitialization(const Expr *E) {
  2870. return Success((const ValueDecl*)0);
  2871. }
  2872. bool VisitCastExpr(const CastExpr *E);
  2873. bool VisitUnaryAddrOf(const UnaryOperator *E);
  2874. };
  2875. } // end anonymous namespace
  2876. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  2877. EvalInfo &Info) {
  2878. assert(E->isRValue() && E->getType()->isMemberPointerType());
  2879. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  2880. }
  2881. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  2882. switch (E->getCastKind()) {
  2883. default:
  2884. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  2885. case CK_NullToMemberPointer:
  2886. return ZeroInitialization(E);
  2887. case CK_BaseToDerivedMemberPointer: {
  2888. if (!Visit(E->getSubExpr()))
  2889. return false;
  2890. if (E->path_empty())
  2891. return true;
  2892. // Base-to-derived member pointer casts store the path in derived-to-base
  2893. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  2894. // the wrong end of the derived->base arc, so stagger the path by one class.
  2895. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  2896. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  2897. PathI != PathE; ++PathI) {
  2898. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  2899. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  2900. if (!Result.castToDerived(Derived))
  2901. return Error(E);
  2902. }
  2903. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  2904. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  2905. return Error(E);
  2906. return true;
  2907. }
  2908. case CK_DerivedToBaseMemberPointer:
  2909. if (!Visit(E->getSubExpr()))
  2910. return false;
  2911. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2912. PathE = E->path_end(); PathI != PathE; ++PathI) {
  2913. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  2914. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  2915. if (!Result.castToBase(Base))
  2916. return Error(E);
  2917. }
  2918. return true;
  2919. }
  2920. }
  2921. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  2922. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  2923. // member can be formed.
  2924. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  2925. }
  2926. //===----------------------------------------------------------------------===//
  2927. // Record Evaluation
  2928. //===----------------------------------------------------------------------===//
  2929. namespace {
  2930. class RecordExprEvaluator
  2931. : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
  2932. const LValue &This;
  2933. APValue &Result;
  2934. public:
  2935. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  2936. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  2937. bool Success(const APValue &V, const Expr *E) {
  2938. Result = V;
  2939. return true;
  2940. }
  2941. bool ZeroInitialization(const Expr *E);
  2942. bool VisitCastExpr(const CastExpr *E);
  2943. bool VisitInitListExpr(const InitListExpr *E);
  2944. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  2945. };
  2946. }
  2947. /// Perform zero-initialization on an object of non-union class type.
  2948. /// C++11 [dcl.init]p5:
  2949. /// To zero-initialize an object or reference of type T means:
  2950. /// [...]
  2951. /// -- if T is a (possibly cv-qualified) non-union class type,
  2952. /// each non-static data member and each base-class subobject is
  2953. /// zero-initialized
  2954. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  2955. const RecordDecl *RD,
  2956. const LValue &This, APValue &Result) {
  2957. assert(!RD->isUnion() && "Expected non-union class type");
  2958. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  2959. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  2960. std::distance(RD->field_begin(), RD->field_end()));
  2961. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2962. if (CD) {
  2963. unsigned Index = 0;
  2964. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  2965. End = CD->bases_end(); I != End; ++I, ++Index) {
  2966. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  2967. LValue Subobject = This;
  2968. HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
  2969. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  2970. Result.getStructBase(Index)))
  2971. return false;
  2972. }
  2973. }
  2974. for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
  2975. I != End; ++I) {
  2976. // -- if T is a reference type, no initialization is performed.
  2977. if ((*I)->getType()->isReferenceType())
  2978. continue;
  2979. LValue Subobject = This;
  2980. HandleLValueMember(Info, E, Subobject, *I, &Layout);
  2981. ImplicitValueInitExpr VIE((*I)->getType());
  2982. if (!EvaluateInPlace(
  2983. Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
  2984. return false;
  2985. }
  2986. return true;
  2987. }
  2988. bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
  2989. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  2990. if (RD->isUnion()) {
  2991. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  2992. // object's first non-static named data member is zero-initialized
  2993. RecordDecl::field_iterator I = RD->field_begin();
  2994. if (I == RD->field_end()) {
  2995. Result = APValue((const FieldDecl*)0);
  2996. return true;
  2997. }
  2998. LValue Subobject = This;
  2999. HandleLValueMember(Info, E, Subobject, *I);
  3000. Result = APValue(*I);
  3001. ImplicitValueInitExpr VIE((*I)->getType());
  3002. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  3003. }
  3004. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  3005. Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
  3006. return false;
  3007. }
  3008. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  3009. }
  3010. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  3011. switch (E->getCastKind()) {
  3012. default:
  3013. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  3014. case CK_ConstructorConversion:
  3015. return Visit(E->getSubExpr());
  3016. case CK_DerivedToBase:
  3017. case CK_UncheckedDerivedToBase: {
  3018. APValue DerivedObject;
  3019. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  3020. return false;
  3021. if (!DerivedObject.isStruct())
  3022. return Error(E->getSubExpr());
  3023. // Derived-to-base rvalue conversion: just slice off the derived part.
  3024. APValue *Value = &DerivedObject;
  3025. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  3026. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  3027. PathE = E->path_end(); PathI != PathE; ++PathI) {
  3028. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  3029. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  3030. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  3031. RD = Base;
  3032. }
  3033. Result = *Value;
  3034. return true;
  3035. }
  3036. }
  3037. }
  3038. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3039. // Cannot constant-evaluate std::initializer_list inits.
  3040. if (E->initializesStdInitializerList())
  3041. return false;
  3042. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  3043. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  3044. if (RD->isUnion()) {
  3045. const FieldDecl *Field = E->getInitializedFieldInUnion();
  3046. Result = APValue(Field);
  3047. if (!Field)
  3048. return true;
  3049. // If the initializer list for a union does not contain any elements, the
  3050. // first element of the union is value-initialized.
  3051. ImplicitValueInitExpr VIE(Field->getType());
  3052. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  3053. LValue Subobject = This;
  3054. HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
  3055. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  3056. }
  3057. assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
  3058. "initializer list for class with base classes");
  3059. Result = APValue(APValue::UninitStruct(), 0,
  3060. std::distance(RD->field_begin(), RD->field_end()));
  3061. unsigned ElementNo = 0;
  3062. bool Success = true;
  3063. for (RecordDecl::field_iterator Field = RD->field_begin(),
  3064. FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
  3065. // Anonymous bit-fields are not considered members of the class for
  3066. // purposes of aggregate initialization.
  3067. if (Field->isUnnamedBitfield())
  3068. continue;
  3069. LValue Subobject = This;
  3070. bool HaveInit = ElementNo < E->getNumInits();
  3071. // FIXME: Diagnostics here should point to the end of the initializer
  3072. // list, not the start.
  3073. HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
  3074. *Field, &Layout);
  3075. // Perform an implicit value-initialization for members beyond the end of
  3076. // the initializer list.
  3077. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  3078. if (!EvaluateInPlace(
  3079. Result.getStructField((*Field)->getFieldIndex()),
  3080. Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
  3081. if (!Info.keepEvaluatingAfterFailure())
  3082. return false;
  3083. Success = false;
  3084. }
  3085. }
  3086. return Success;
  3087. }
  3088. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3089. const CXXConstructorDecl *FD = E->getConstructor();
  3090. bool ZeroInit = E->requiresZeroInitialization();
  3091. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  3092. // If we've already performed zero-initialization, we're already done.
  3093. if (!Result.isUninit())
  3094. return true;
  3095. if (ZeroInit)
  3096. return ZeroInitialization(E);
  3097. const CXXRecordDecl *RD = FD->getParent();
  3098. if (RD->isUnion())
  3099. Result = APValue((FieldDecl*)0);
  3100. else
  3101. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  3102. std::distance(RD->field_begin(), RD->field_end()));
  3103. return true;
  3104. }
  3105. const FunctionDecl *Definition = 0;
  3106. FD->getBody(Definition);
  3107. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  3108. return false;
  3109. // Avoid materializing a temporary for an elidable copy/move constructor.
  3110. if (E->isElidable() && !ZeroInit)
  3111. if (const MaterializeTemporaryExpr *ME
  3112. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  3113. return Visit(ME->GetTemporaryExpr());
  3114. if (ZeroInit && !ZeroInitialization(E))
  3115. return false;
  3116. llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
  3117. return HandleConstructorCall(E->getExprLoc(), This, Args,
  3118. cast<CXXConstructorDecl>(Definition), Info,
  3119. Result);
  3120. }
  3121. static bool EvaluateRecord(const Expr *E, const LValue &This,
  3122. APValue &Result, EvalInfo &Info) {
  3123. assert(E->isRValue() && E->getType()->isRecordType() &&
  3124. "can't evaluate expression as a record rvalue");
  3125. return RecordExprEvaluator(Info, This, Result).Visit(E);
  3126. }
  3127. //===----------------------------------------------------------------------===//
  3128. // Temporary Evaluation
  3129. //
  3130. // Temporaries are represented in the AST as rvalues, but generally behave like
  3131. // lvalues. The full-object of which the temporary is a subobject is implicitly
  3132. // materialized so that a reference can bind to it.
  3133. //===----------------------------------------------------------------------===//
  3134. namespace {
  3135. class TemporaryExprEvaluator
  3136. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  3137. public:
  3138. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  3139. LValueExprEvaluatorBaseTy(Info, Result) {}
  3140. /// Visit an expression which constructs the value of this temporary.
  3141. bool VisitConstructExpr(const Expr *E) {
  3142. Result.set(E, Info.CurrentCall->Index);
  3143. return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
  3144. }
  3145. bool VisitCastExpr(const CastExpr *E) {
  3146. switch (E->getCastKind()) {
  3147. default:
  3148. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  3149. case CK_ConstructorConversion:
  3150. return VisitConstructExpr(E->getSubExpr());
  3151. }
  3152. }
  3153. bool VisitInitListExpr(const InitListExpr *E) {
  3154. return VisitConstructExpr(E);
  3155. }
  3156. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3157. return VisitConstructExpr(E);
  3158. }
  3159. bool VisitCallExpr(const CallExpr *E) {
  3160. return VisitConstructExpr(E);
  3161. }
  3162. };
  3163. } // end anonymous namespace
  3164. /// Evaluate an expression of record type as a temporary.
  3165. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  3166. assert(E->isRValue() && E->getType()->isRecordType());
  3167. return TemporaryExprEvaluator(Info, Result).Visit(E);
  3168. }
  3169. //===----------------------------------------------------------------------===//
  3170. // Vector Evaluation
  3171. //===----------------------------------------------------------------------===//
  3172. namespace {
  3173. class VectorExprEvaluator
  3174. : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
  3175. APValue &Result;
  3176. public:
  3177. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  3178. : ExprEvaluatorBaseTy(info), Result(Result) {}
  3179. bool Success(const ArrayRef<APValue> &V, const Expr *E) {
  3180. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  3181. // FIXME: remove this APValue copy.
  3182. Result = APValue(V.data(), V.size());
  3183. return true;
  3184. }
  3185. bool Success(const APValue &V, const Expr *E) {
  3186. assert(V.isVector());
  3187. Result = V;
  3188. return true;
  3189. }
  3190. bool ZeroInitialization(const Expr *E);
  3191. bool VisitUnaryReal(const UnaryOperator *E)
  3192. { return Visit(E->getSubExpr()); }
  3193. bool VisitCastExpr(const CastExpr* E);
  3194. bool VisitInitListExpr(const InitListExpr *E);
  3195. bool VisitUnaryImag(const UnaryOperator *E);
  3196. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  3197. // binary comparisons, binary and/or/xor,
  3198. // shufflevector, ExtVectorElementExpr
  3199. };
  3200. } // end anonymous namespace
  3201. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  3202. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  3203. return VectorExprEvaluator(Info, Result).Visit(E);
  3204. }
  3205. bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
  3206. const VectorType *VTy = E->getType()->castAs<VectorType>();
  3207. unsigned NElts = VTy->getNumElements();
  3208. const Expr *SE = E->getSubExpr();
  3209. QualType SETy = SE->getType();
  3210. switch (E->getCastKind()) {
  3211. case CK_VectorSplat: {
  3212. APValue Val = APValue();
  3213. if (SETy->isIntegerType()) {
  3214. APSInt IntResult;
  3215. if (!EvaluateInteger(SE, IntResult, Info))
  3216. return false;
  3217. Val = APValue(IntResult);
  3218. } else if (SETy->isRealFloatingType()) {
  3219. APFloat F(0.0);
  3220. if (!EvaluateFloat(SE, F, Info))
  3221. return false;
  3222. Val = APValue(F);
  3223. } else {
  3224. return Error(E);
  3225. }
  3226. // Splat and create vector APValue.
  3227. SmallVector<APValue, 4> Elts(NElts, Val);
  3228. return Success(Elts, E);
  3229. }
  3230. case CK_BitCast: {
  3231. // Evaluate the operand into an APInt we can extract from.
  3232. llvm::APInt SValInt;
  3233. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  3234. return false;
  3235. // Extract the elements
  3236. QualType EltTy = VTy->getElementType();
  3237. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  3238. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  3239. SmallVector<APValue, 4> Elts;
  3240. if (EltTy->isRealFloatingType()) {
  3241. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  3242. bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
  3243. unsigned FloatEltSize = EltSize;
  3244. if (&Sem == &APFloat::x87DoubleExtended)
  3245. FloatEltSize = 80;
  3246. for (unsigned i = 0; i < NElts; i++) {
  3247. llvm::APInt Elt;
  3248. if (BigEndian)
  3249. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  3250. else
  3251. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  3252. Elts.push_back(APValue(APFloat(Elt, isIEESem)));
  3253. }
  3254. } else if (EltTy->isIntegerType()) {
  3255. for (unsigned i = 0; i < NElts; i++) {
  3256. llvm::APInt Elt;
  3257. if (BigEndian)
  3258. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  3259. else
  3260. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  3261. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  3262. }
  3263. } else {
  3264. return Error(E);
  3265. }
  3266. return Success(Elts, E);
  3267. }
  3268. default:
  3269. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  3270. }
  3271. }
  3272. bool
  3273. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3274. const VectorType *VT = E->getType()->castAs<VectorType>();
  3275. unsigned NumInits = E->getNumInits();
  3276. unsigned NumElements = VT->getNumElements();
  3277. QualType EltTy = VT->getElementType();
  3278. SmallVector<APValue, 4> Elements;
  3279. // The number of initializers can be less than the number of
  3280. // vector elements. For OpenCL, this can be due to nested vector
  3281. // initialization. For GCC compatibility, missing trailing elements
  3282. // should be initialized with zeroes.
  3283. unsigned CountInits = 0, CountElts = 0;
  3284. while (CountElts < NumElements) {
  3285. // Handle nested vector initialization.
  3286. if (CountInits < NumInits
  3287. && E->getInit(CountInits)->getType()->isExtVectorType()) {
  3288. APValue v;
  3289. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  3290. return Error(E);
  3291. unsigned vlen = v.getVectorLength();
  3292. for (unsigned j = 0; j < vlen; j++)
  3293. Elements.push_back(v.getVectorElt(j));
  3294. CountElts += vlen;
  3295. } else if (EltTy->isIntegerType()) {
  3296. llvm::APSInt sInt(32);
  3297. if (CountInits < NumInits) {
  3298. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  3299. return Error(E);
  3300. } else // trailing integer zero.
  3301. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  3302. Elements.push_back(APValue(sInt));
  3303. CountElts++;
  3304. } else {
  3305. llvm::APFloat f(0.0);
  3306. if (CountInits < NumInits) {
  3307. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  3308. return Error(E);
  3309. } else // trailing float zero.
  3310. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  3311. Elements.push_back(APValue(f));
  3312. CountElts++;
  3313. }
  3314. CountInits++;
  3315. }
  3316. return Success(Elements, E);
  3317. }
  3318. bool
  3319. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  3320. const VectorType *VT = E->getType()->getAs<VectorType>();
  3321. QualType EltTy = VT->getElementType();
  3322. APValue ZeroElement;
  3323. if (EltTy->isIntegerType())
  3324. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  3325. else
  3326. ZeroElement =
  3327. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  3328. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  3329. return Success(Elements, E);
  3330. }
  3331. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  3332. VisitIgnoredValue(E->getSubExpr());
  3333. return ZeroInitialization(E);
  3334. }
  3335. //===----------------------------------------------------------------------===//
  3336. // Array Evaluation
  3337. //===----------------------------------------------------------------------===//
  3338. namespace {
  3339. class ArrayExprEvaluator
  3340. : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
  3341. const LValue &This;
  3342. APValue &Result;
  3343. public:
  3344. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  3345. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  3346. bool Success(const APValue &V, const Expr *E) {
  3347. assert((V.isArray() || V.isLValue()) &&
  3348. "expected array or string literal");
  3349. Result = V;
  3350. return true;
  3351. }
  3352. bool ZeroInitialization(const Expr *E) {
  3353. const ConstantArrayType *CAT =
  3354. Info.Ctx.getAsConstantArrayType(E->getType());
  3355. if (!CAT)
  3356. return Error(E);
  3357. Result = APValue(APValue::UninitArray(), 0,
  3358. CAT->getSize().getZExtValue());
  3359. if (!Result.hasArrayFiller()) return true;
  3360. // Zero-initialize all elements.
  3361. LValue Subobject = This;
  3362. Subobject.addArray(Info, E, CAT);
  3363. ImplicitValueInitExpr VIE(CAT->getElementType());
  3364. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  3365. }
  3366. bool VisitInitListExpr(const InitListExpr *E);
  3367. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  3368. };
  3369. } // end anonymous namespace
  3370. static bool EvaluateArray(const Expr *E, const LValue &This,
  3371. APValue &Result, EvalInfo &Info) {
  3372. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  3373. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  3374. }
  3375. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  3376. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  3377. if (!CAT)
  3378. return Error(E);
  3379. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  3380. // an appropriately-typed string literal enclosed in braces.
  3381. if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
  3382. Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
  3383. LValue LV;
  3384. if (!EvaluateLValue(E->getInit(0), LV, Info))
  3385. return false;
  3386. APValue Val;
  3387. LV.moveInto(Val);
  3388. return Success(Val, E);
  3389. }
  3390. bool Success = true;
  3391. Result = APValue(APValue::UninitArray(), E->getNumInits(),
  3392. CAT->getSize().getZExtValue());
  3393. LValue Subobject = This;
  3394. Subobject.addArray(Info, E, CAT);
  3395. unsigned Index = 0;
  3396. for (InitListExpr::const_iterator I = E->begin(), End = E->end();
  3397. I != End; ++I, ++Index) {
  3398. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  3399. Info, Subobject, cast<Expr>(*I)) ||
  3400. !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
  3401. CAT->getElementType(), 1)) {
  3402. if (!Info.keepEvaluatingAfterFailure())
  3403. return false;
  3404. Success = false;
  3405. }
  3406. }
  3407. if (!Result.hasArrayFiller()) return Success;
  3408. assert(E->hasArrayFiller() && "no array filler for incomplete init list");
  3409. // FIXME: The Subobject here isn't necessarily right. This rarely matters,
  3410. // but sometimes does:
  3411. // struct S { constexpr S() : p(&p) {} void *p; };
  3412. // S s[10] = {};
  3413. return EvaluateInPlace(Result.getArrayFiller(), Info,
  3414. Subobject, E->getArrayFiller()) && Success;
  3415. }
  3416. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3417. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  3418. if (!CAT)
  3419. return Error(E);
  3420. bool HadZeroInit = !Result.isUninit();
  3421. if (!HadZeroInit)
  3422. Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
  3423. if (!Result.hasArrayFiller())
  3424. return true;
  3425. const CXXConstructorDecl *FD = E->getConstructor();
  3426. bool ZeroInit = E->requiresZeroInitialization();
  3427. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  3428. if (HadZeroInit)
  3429. return true;
  3430. if (ZeroInit) {
  3431. LValue Subobject = This;
  3432. Subobject.addArray(Info, E, CAT);
  3433. ImplicitValueInitExpr VIE(CAT->getElementType());
  3434. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  3435. }
  3436. const CXXRecordDecl *RD = FD->getParent();
  3437. if (RD->isUnion())
  3438. Result.getArrayFiller() = APValue((FieldDecl*)0);
  3439. else
  3440. Result.getArrayFiller() =
  3441. APValue(APValue::UninitStruct(), RD->getNumBases(),
  3442. std::distance(RD->field_begin(), RD->field_end()));
  3443. return true;
  3444. }
  3445. const FunctionDecl *Definition = 0;
  3446. FD->getBody(Definition);
  3447. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
  3448. return false;
  3449. // FIXME: The Subobject here isn't necessarily right. This rarely matters,
  3450. // but sometimes does:
  3451. // struct S { constexpr S() : p(&p) {} void *p; };
  3452. // S s[10];
  3453. LValue Subobject = This;
  3454. Subobject.addArray(Info, E, CAT);
  3455. if (ZeroInit && !HadZeroInit) {
  3456. ImplicitValueInitExpr VIE(CAT->getElementType());
  3457. if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
  3458. return false;
  3459. }
  3460. llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
  3461. return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
  3462. cast<CXXConstructorDecl>(Definition),
  3463. Info, Result.getArrayFiller());
  3464. }
  3465. //===----------------------------------------------------------------------===//
  3466. // Integer Evaluation
  3467. //
  3468. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  3469. // types and back in constant folding. Integer values are thus represented
  3470. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  3471. //===----------------------------------------------------------------------===//
  3472. namespace {
  3473. class IntExprEvaluator
  3474. : public ExprEvaluatorBase<IntExprEvaluator, bool> {
  3475. APValue &Result;
  3476. public:
  3477. IntExprEvaluator(EvalInfo &info, APValue &result)
  3478. : ExprEvaluatorBaseTy(info), Result(result) {}
  3479. bool Success(const llvm::APSInt &SI, const Expr *E) {
  3480. assert(E->getType()->isIntegralOrEnumerationType() &&
  3481. "Invalid evaluation result.");
  3482. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  3483. "Invalid evaluation result.");
  3484. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  3485. "Invalid evaluation result.");
  3486. Result = APValue(SI);
  3487. return true;
  3488. }
  3489. bool Success(const llvm::APInt &I, const Expr *E) {
  3490. assert(E->getType()->isIntegralOrEnumerationType() &&
  3491. "Invalid evaluation result.");
  3492. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  3493. "Invalid evaluation result.");
  3494. Result = APValue(APSInt(I));
  3495. Result.getInt().setIsUnsigned(
  3496. E->getType()->isUnsignedIntegerOrEnumerationType());
  3497. return true;
  3498. }
  3499. bool Success(uint64_t Value, const Expr *E) {
  3500. assert(E->getType()->isIntegralOrEnumerationType() &&
  3501. "Invalid evaluation result.");
  3502. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  3503. return true;
  3504. }
  3505. bool Success(CharUnits Size, const Expr *E) {
  3506. return Success(Size.getQuantity(), E);
  3507. }
  3508. bool Success(const APValue &V, const Expr *E) {
  3509. if (V.isLValue() || V.isAddrLabelDiff()) {
  3510. Result = V;
  3511. return true;
  3512. }
  3513. return Success(V.getInt(), E);
  3514. }
  3515. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  3516. // FIXME: See EvalInfo::IntExprEvaluatorDepth.
  3517. bool Visit(const Expr *E) {
  3518. SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
  3519. Info.IntExprEvaluatorDepth+1);
  3520. const unsigned MaxDepth = 512;
  3521. if (Depth.get() > MaxDepth) {
  3522. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  3523. diag::err_intexpr_depth_limit_exceeded);
  3524. return false;
  3525. }
  3526. return ExprEvaluatorBaseTy::Visit(E);
  3527. }
  3528. //===--------------------------------------------------------------------===//
  3529. // Visitor Methods
  3530. //===--------------------------------------------------------------------===//
  3531. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  3532. return Success(E->getValue(), E);
  3533. }
  3534. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  3535. return Success(E->getValue(), E);
  3536. }
  3537. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  3538. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  3539. if (CheckReferencedDecl(E, E->getDecl()))
  3540. return true;
  3541. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  3542. }
  3543. bool VisitMemberExpr(const MemberExpr *E) {
  3544. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  3545. VisitIgnoredValue(E->getBase());
  3546. return true;
  3547. }
  3548. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  3549. }
  3550. bool VisitCallExpr(const CallExpr *E);
  3551. bool VisitBinaryOperator(const BinaryOperator *E);
  3552. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  3553. bool VisitUnaryOperator(const UnaryOperator *E);
  3554. bool VisitCastExpr(const CastExpr* E);
  3555. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  3556. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  3557. return Success(E->getValue(), E);
  3558. }
  3559. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  3560. return Success(E->getValue(), E);
  3561. }
  3562. // Note, GNU defines __null as an integer, not a pointer.
  3563. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  3564. return ZeroInitialization(E);
  3565. }
  3566. bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
  3567. return Success(E->getValue(), E);
  3568. }
  3569. bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
  3570. return Success(E->getValue(), E);
  3571. }
  3572. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  3573. return Success(E->getValue(), E);
  3574. }
  3575. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  3576. return Success(E->getValue(), E);
  3577. }
  3578. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  3579. return Success(E->getValue(), E);
  3580. }
  3581. bool VisitUnaryReal(const UnaryOperator *E);
  3582. bool VisitUnaryImag(const UnaryOperator *E);
  3583. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  3584. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  3585. private:
  3586. CharUnits GetAlignOfExpr(const Expr *E);
  3587. CharUnits GetAlignOfType(QualType T);
  3588. static QualType GetObjectType(APValue::LValueBase B);
  3589. bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
  3590. // FIXME: Missing: array subscript of vector, member of vector
  3591. };
  3592. } // end anonymous namespace
  3593. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  3594. /// produce either the integer value or a pointer.
  3595. ///
  3596. /// GCC has a heinous extension which folds casts between pointer types and
  3597. /// pointer-sized integral types. We support this by allowing the evaluation of
  3598. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  3599. /// Some simple arithmetic on such values is supported (they are treated much
  3600. /// like char*).
  3601. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  3602. EvalInfo &Info) {
  3603. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  3604. return IntExprEvaluator(Info, Result).Visit(E);
  3605. }
  3606. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  3607. APValue Val;
  3608. if (!EvaluateIntegerOrLValue(E, Val, Info))
  3609. return false;
  3610. if (!Val.isInt()) {
  3611. // FIXME: It would be better to produce the diagnostic for casting
  3612. // a pointer to an integer.
  3613. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  3614. return false;
  3615. }
  3616. Result = Val.getInt();
  3617. return true;
  3618. }
  3619. /// Check whether the given declaration can be directly converted to an integral
  3620. /// rvalue. If not, no diagnostic is produced; there are other things we can
  3621. /// try.
  3622. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  3623. // Enums are integer constant exprs.
  3624. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  3625. // Check for signedness/width mismatches between E type and ECD value.
  3626. bool SameSign = (ECD->getInitVal().isSigned()
  3627. == E->getType()->isSignedIntegerOrEnumerationType());
  3628. bool SameWidth = (ECD->getInitVal().getBitWidth()
  3629. == Info.Ctx.getIntWidth(E->getType()));
  3630. if (SameSign && SameWidth)
  3631. return Success(ECD->getInitVal(), E);
  3632. else {
  3633. // Get rid of mismatch (otherwise Success assertions will fail)
  3634. // by computing a new value matching the type of E.
  3635. llvm::APSInt Val = ECD->getInitVal();
  3636. if (!SameSign)
  3637. Val.setIsSigned(!ECD->getInitVal().isSigned());
  3638. if (!SameWidth)
  3639. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  3640. return Success(Val, E);
  3641. }
  3642. }
  3643. return false;
  3644. }
  3645. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  3646. /// as GCC.
  3647. static int EvaluateBuiltinClassifyType(const CallExpr *E) {
  3648. // The following enum mimics the values returned by GCC.
  3649. // FIXME: Does GCC differ between lvalue and rvalue references here?
  3650. enum gcc_type_class {
  3651. no_type_class = -1,
  3652. void_type_class, integer_type_class, char_type_class,
  3653. enumeral_type_class, boolean_type_class,
  3654. pointer_type_class, reference_type_class, offset_type_class,
  3655. real_type_class, complex_type_class,
  3656. function_type_class, method_type_class,
  3657. record_type_class, union_type_class,
  3658. array_type_class, string_type_class,
  3659. lang_type_class
  3660. };
  3661. // If no argument was supplied, default to "no_type_class". This isn't
  3662. // ideal, however it is what gcc does.
  3663. if (E->getNumArgs() == 0)
  3664. return no_type_class;
  3665. QualType ArgTy = E->getArg(0)->getType();
  3666. if (ArgTy->isVoidType())
  3667. return void_type_class;
  3668. else if (ArgTy->isEnumeralType())
  3669. return enumeral_type_class;
  3670. else if (ArgTy->isBooleanType())
  3671. return boolean_type_class;
  3672. else if (ArgTy->isCharType())
  3673. return string_type_class; // gcc doesn't appear to use char_type_class
  3674. else if (ArgTy->isIntegerType())
  3675. return integer_type_class;
  3676. else if (ArgTy->isPointerType())
  3677. return pointer_type_class;
  3678. else if (ArgTy->isReferenceType())
  3679. return reference_type_class;
  3680. else if (ArgTy->isRealType())
  3681. return real_type_class;
  3682. else if (ArgTy->isComplexType())
  3683. return complex_type_class;
  3684. else if (ArgTy->isFunctionType())
  3685. return function_type_class;
  3686. else if (ArgTy->isStructureOrClassType())
  3687. return record_type_class;
  3688. else if (ArgTy->isUnionType())
  3689. return union_type_class;
  3690. else if (ArgTy->isArrayType())
  3691. return array_type_class;
  3692. else if (ArgTy->isUnionType())
  3693. return union_type_class;
  3694. else // FIXME: offset_type_class, method_type_class, & lang_type_class?
  3695. llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
  3696. }
  3697. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  3698. /// __builtin_constant_p when applied to the given lvalue.
  3699. ///
  3700. /// An lvalue is only "constant" if it is a pointer or reference to the first
  3701. /// character of a string literal.
  3702. template<typename LValue>
  3703. static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
  3704. const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
  3705. return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
  3706. }
  3707. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  3708. /// GCC as we can manage.
  3709. static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
  3710. QualType ArgType = Arg->getType();
  3711. // __builtin_constant_p always has one operand. The rules which gcc follows
  3712. // are not precisely documented, but are as follows:
  3713. //
  3714. // - If the operand is of integral, floating, complex or enumeration type,
  3715. // and can be folded to a known value of that type, it returns 1.
  3716. // - If the operand and can be folded to a pointer to the first character
  3717. // of a string literal (or such a pointer cast to an integral type), it
  3718. // returns 1.
  3719. //
  3720. // Otherwise, it returns 0.
  3721. //
  3722. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  3723. // its support for this does not currently work.
  3724. if (ArgType->isIntegralOrEnumerationType()) {
  3725. Expr::EvalResult Result;
  3726. if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
  3727. return false;
  3728. APValue &V = Result.Val;
  3729. if (V.getKind() == APValue::Int)
  3730. return true;
  3731. return EvaluateBuiltinConstantPForLValue(V);
  3732. } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
  3733. return Arg->isEvaluatable(Ctx);
  3734. } else if (ArgType->isPointerType() || Arg->isGLValue()) {
  3735. LValue LV;
  3736. Expr::EvalStatus Status;
  3737. EvalInfo Info(Ctx, Status);
  3738. if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
  3739. : EvaluatePointer(Arg, LV, Info)) &&
  3740. !Status.HasSideEffects)
  3741. return EvaluateBuiltinConstantPForLValue(LV);
  3742. }
  3743. // Anything else isn't considered to be sufficiently constant.
  3744. return false;
  3745. }
  3746. /// Retrieves the "underlying object type" of the given expression,
  3747. /// as used by __builtin_object_size.
  3748. QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
  3749. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  3750. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3751. return VD->getType();
  3752. } else if (const Expr *E = B.get<const Expr*>()) {
  3753. if (isa<CompoundLiteralExpr>(E))
  3754. return E->getType();
  3755. }
  3756. return QualType();
  3757. }
  3758. bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
  3759. // TODO: Perhaps we should let LLVM lower this?
  3760. LValue Base;
  3761. if (!EvaluatePointer(E->getArg(0), Base, Info))
  3762. return false;
  3763. // If we can prove the base is null, lower to zero now.
  3764. if (!Base.getLValueBase()) return Success(0, E);
  3765. QualType T = GetObjectType(Base.getLValueBase());
  3766. if (T.isNull() ||
  3767. T->isIncompleteType() ||
  3768. T->isFunctionType() ||
  3769. T->isVariablyModifiedType() ||
  3770. T->isDependentType())
  3771. return Error(E);
  3772. CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
  3773. CharUnits Offset = Base.getLValueOffset();
  3774. if (!Offset.isNegative() && Offset <= Size)
  3775. Size -= Offset;
  3776. else
  3777. Size = CharUnits::Zero();
  3778. return Success(Size, E);
  3779. }
  3780. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  3781. switch (E->isBuiltinCall()) {
  3782. default:
  3783. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  3784. case Builtin::BI__builtin_object_size: {
  3785. if (TryEvaluateBuiltinObjectSize(E))
  3786. return true;
  3787. // If evaluating the argument has side-effects we can't determine
  3788. // the size of the object and lower it to unknown now.
  3789. if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
  3790. if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
  3791. return Success(-1ULL, E);
  3792. return Success(0, E);
  3793. }
  3794. return Error(E);
  3795. }
  3796. case Builtin::BI__builtin_classify_type:
  3797. return Success(EvaluateBuiltinClassifyType(E), E);
  3798. case Builtin::BI__builtin_constant_p:
  3799. return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
  3800. case Builtin::BI__builtin_eh_return_data_regno: {
  3801. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  3802. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  3803. return Success(Operand, E);
  3804. }
  3805. case Builtin::BI__builtin_expect:
  3806. return Visit(E->getArg(0));
  3807. case Builtin::BIstrlen:
  3808. // A call to strlen is not a constant expression.
  3809. if (Info.getLangOpts().CPlusPlus0x)
  3810. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
  3811. << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
  3812. else
  3813. Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  3814. // Fall through.
  3815. case Builtin::BI__builtin_strlen:
  3816. // As an extension, we support strlen() and __builtin_strlen() as constant
  3817. // expressions when the argument is a string literal.
  3818. if (const StringLiteral *S
  3819. = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
  3820. // The string literal may have embedded null characters. Find the first
  3821. // one and truncate there.
  3822. StringRef Str = S->getString();
  3823. StringRef::size_type Pos = Str.find(0);
  3824. if (Pos != StringRef::npos)
  3825. Str = Str.substr(0, Pos);
  3826. return Success(Str.size(), E);
  3827. }
  3828. return Error(E);
  3829. case Builtin::BI__atomic_is_lock_free: {
  3830. APSInt SizeVal;
  3831. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  3832. return false;
  3833. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  3834. // of two less than the maximum inline atomic width, we know it is
  3835. // lock-free. If the size isn't a power of two, or greater than the
  3836. // maximum alignment where we promote atomics, we know it is not lock-free
  3837. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  3838. // the answer can only be determined at runtime; for example, 16-byte
  3839. // atomics have lock-free implementations on some, but not all,
  3840. // x86-64 processors.
  3841. // Check power-of-two.
  3842. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  3843. if (!Size.isPowerOfTwo())
  3844. #if 0
  3845. // FIXME: Suppress this folding until the ABI for the promotion width
  3846. // settles.
  3847. return Success(0, E);
  3848. #else
  3849. return Error(E);
  3850. #endif
  3851. #if 0
  3852. // Check against promotion width.
  3853. // FIXME: Suppress this folding until the ABI for the promotion width
  3854. // settles.
  3855. unsigned PromoteWidthBits =
  3856. Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
  3857. if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
  3858. return Success(0, E);
  3859. #endif
  3860. // Check against inlining width.
  3861. unsigned InlineWidthBits =
  3862. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  3863. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
  3864. return Success(1, E);
  3865. return Error(E);
  3866. }
  3867. }
  3868. }
  3869. static bool HasSameBase(const LValue &A, const LValue &B) {
  3870. if (!A.getLValueBase())
  3871. return !B.getLValueBase();
  3872. if (!B.getLValueBase())
  3873. return false;
  3874. if (A.getLValueBase().getOpaqueValue() !=
  3875. B.getLValueBase().getOpaqueValue()) {
  3876. const Decl *ADecl = GetLValueBaseDecl(A);
  3877. if (!ADecl)
  3878. return false;
  3879. const Decl *BDecl = GetLValueBaseDecl(B);
  3880. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  3881. return false;
  3882. }
  3883. return IsGlobalLValue(A.getLValueBase()) ||
  3884. A.getLValueCallIndex() == B.getLValueCallIndex();
  3885. }
  3886. /// Perform the given integer operation, which is known to need at most BitWidth
  3887. /// bits, and check for overflow in the original type (if that type was not an
  3888. /// unsigned type).
  3889. template<typename Operation>
  3890. static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  3891. const APSInt &LHS, const APSInt &RHS,
  3892. unsigned BitWidth, Operation Op) {
  3893. if (LHS.isUnsigned())
  3894. return Op(LHS, RHS);
  3895. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  3896. APSInt Result = Value.trunc(LHS.getBitWidth());
  3897. if (Result.extend(BitWidth) != Value)
  3898. HandleOverflow(Info, E, Value, E->getType());
  3899. return Result;
  3900. }
  3901. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  3902. if (E->isAssignmentOp())
  3903. return Error(E);
  3904. if (E->getOpcode() == BO_Comma) {
  3905. VisitIgnoredValue(E->getLHS());
  3906. return Visit(E->getRHS());
  3907. }
  3908. if (E->isLogicalOp()) {
  3909. // These need to be handled specially because the operands aren't
  3910. // necessarily integral nor evaluated.
  3911. bool lhsResult, rhsResult;
  3912. if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
  3913. // We were able to evaluate the LHS, see if we can get away with not
  3914. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  3915. if (lhsResult == (E->getOpcode() == BO_LOr))
  3916. return Success(lhsResult, E);
  3917. if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
  3918. if (E->getOpcode() == BO_LOr)
  3919. return Success(lhsResult || rhsResult, E);
  3920. else
  3921. return Success(lhsResult && rhsResult, E);
  3922. }
  3923. } else {
  3924. // Since we weren't able to evaluate the left hand side, it
  3925. // must have had side effects.
  3926. Info.EvalStatus.HasSideEffects = true;
  3927. // Suppress diagnostics from this arm.
  3928. SpeculativeEvaluationRAII Speculative(Info);
  3929. if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
  3930. // We can't evaluate the LHS; however, sometimes the result
  3931. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  3932. if (rhsResult == (E->getOpcode() == BO_LOr))
  3933. return Success(rhsResult, E);
  3934. }
  3935. }
  3936. return false;
  3937. }
  3938. QualType LHSTy = E->getLHS()->getType();
  3939. QualType RHSTy = E->getRHS()->getType();
  3940. if (LHSTy->isAnyComplexType()) {
  3941. assert(RHSTy->isAnyComplexType() && "Invalid comparison");
  3942. ComplexValue LHS, RHS;
  3943. bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  3944. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  3945. return false;
  3946. if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  3947. return false;
  3948. if (LHS.isComplexFloat()) {
  3949. APFloat::cmpResult CR_r =
  3950. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  3951. APFloat::cmpResult CR_i =
  3952. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  3953. if (E->getOpcode() == BO_EQ)
  3954. return Success((CR_r == APFloat::cmpEqual &&
  3955. CR_i == APFloat::cmpEqual), E);
  3956. else {
  3957. assert(E->getOpcode() == BO_NE &&
  3958. "Invalid complex comparison.");
  3959. return Success(((CR_r == APFloat::cmpGreaterThan ||
  3960. CR_r == APFloat::cmpLessThan ||
  3961. CR_r == APFloat::cmpUnordered) ||
  3962. (CR_i == APFloat::cmpGreaterThan ||
  3963. CR_i == APFloat::cmpLessThan ||
  3964. CR_i == APFloat::cmpUnordered)), E);
  3965. }
  3966. } else {
  3967. if (E->getOpcode() == BO_EQ)
  3968. return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  3969. LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
  3970. else {
  3971. assert(E->getOpcode() == BO_NE &&
  3972. "Invalid compex comparison.");
  3973. return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
  3974. LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
  3975. }
  3976. }
  3977. }
  3978. if (LHSTy->isRealFloatingType() &&
  3979. RHSTy->isRealFloatingType()) {
  3980. APFloat RHS(0.0), LHS(0.0);
  3981. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  3982. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  3983. return false;
  3984. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  3985. return false;
  3986. APFloat::cmpResult CR = LHS.compare(RHS);
  3987. switch (E->getOpcode()) {
  3988. default:
  3989. llvm_unreachable("Invalid binary operator!");
  3990. case BO_LT:
  3991. return Success(CR == APFloat::cmpLessThan, E);
  3992. case BO_GT:
  3993. return Success(CR == APFloat::cmpGreaterThan, E);
  3994. case BO_LE:
  3995. return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
  3996. case BO_GE:
  3997. return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
  3998. E);
  3999. case BO_EQ:
  4000. return Success(CR == APFloat::cmpEqual, E);
  4001. case BO_NE:
  4002. return Success(CR == APFloat::cmpGreaterThan
  4003. || CR == APFloat::cmpLessThan
  4004. || CR == APFloat::cmpUnordered, E);
  4005. }
  4006. }
  4007. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  4008. if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
  4009. LValue LHSValue, RHSValue;
  4010. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  4011. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  4012. return false;
  4013. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  4014. return false;
  4015. // Reject differing bases from the normal codepath; we special-case
  4016. // comparisons to null.
  4017. if (!HasSameBase(LHSValue, RHSValue)) {
  4018. if (E->getOpcode() == BO_Sub) {
  4019. // Handle &&A - &&B.
  4020. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  4021. return false;
  4022. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  4023. const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
  4024. if (!LHSExpr || !RHSExpr)
  4025. return false;
  4026. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  4027. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  4028. if (!LHSAddrExpr || !RHSAddrExpr)
  4029. return false;
  4030. // Make sure both labels come from the same function.
  4031. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  4032. RHSAddrExpr->getLabel()->getDeclContext())
  4033. return false;
  4034. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  4035. return true;
  4036. }
  4037. // Inequalities and subtractions between unrelated pointers have
  4038. // unspecified or undefined behavior.
  4039. if (!E->isEqualityOp())
  4040. return Error(E);
  4041. // A constant address may compare equal to the address of a symbol.
  4042. // The one exception is that address of an object cannot compare equal
  4043. // to a null pointer constant.
  4044. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  4045. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  4046. return Error(E);
  4047. // It's implementation-defined whether distinct literals will have
  4048. // distinct addresses. In clang, the result of such a comparison is
  4049. // unspecified, so it is not a constant expression. However, we do know
  4050. // that the address of a literal will be non-null.
  4051. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  4052. LHSValue.Base && RHSValue.Base)
  4053. return Error(E);
  4054. // We can't tell whether weak symbols will end up pointing to the same
  4055. // object.
  4056. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  4057. return Error(E);
  4058. // Pointers with different bases cannot represent the same object.
  4059. // (Note that clang defaults to -fmerge-all-constants, which can
  4060. // lead to inconsistent results for comparisons involving the address
  4061. // of a constant; this generally doesn't matter in practice.)
  4062. return Success(E->getOpcode() == BO_NE, E);
  4063. }
  4064. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  4065. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  4066. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  4067. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  4068. if (E->getOpcode() == BO_Sub) {
  4069. // C++11 [expr.add]p6:
  4070. // Unless both pointers point to elements of the same array object, or
  4071. // one past the last element of the array object, the behavior is
  4072. // undefined.
  4073. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  4074. !AreElementsOfSameArray(getType(LHSValue.Base),
  4075. LHSDesignator, RHSDesignator))
  4076. CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  4077. QualType Type = E->getLHS()->getType();
  4078. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  4079. CharUnits ElementSize;
  4080. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  4081. return false;
  4082. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  4083. // and produce incorrect results when it overflows. Such behavior
  4084. // appears to be non-conforming, but is common, so perhaps we should
  4085. // assume the standard intended for such cases to be undefined behavior
  4086. // and check for them.
  4087. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  4088. // overflow in the final conversion to ptrdiff_t.
  4089. APSInt LHS(
  4090. llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  4091. APSInt RHS(
  4092. llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  4093. APSInt ElemSize(
  4094. llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
  4095. APSInt TrueResult = (LHS - RHS) / ElemSize;
  4096. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  4097. if (Result.extend(65) != TrueResult)
  4098. HandleOverflow(Info, E, TrueResult, E->getType());
  4099. return Success(Result, E);
  4100. }
  4101. // C++11 [expr.rel]p3:
  4102. // Pointers to void (after pointer conversions) can be compared, with a
  4103. // result defined as follows: If both pointers represent the same
  4104. // address or are both the null pointer value, the result is true if the
  4105. // operator is <= or >= and false otherwise; otherwise the result is
  4106. // unspecified.
  4107. // We interpret this as applying to pointers to *cv* void.
  4108. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
  4109. E->isRelationalOp())
  4110. CCEDiag(E, diag::note_constexpr_void_comparison);
  4111. // C++11 [expr.rel]p2:
  4112. // - If two pointers point to non-static data members of the same object,
  4113. // or to subobjects or array elements fo such members, recursively, the
  4114. // pointer to the later declared member compares greater provided the
  4115. // two members have the same access control and provided their class is
  4116. // not a union.
  4117. // [...]
  4118. // - Otherwise pointer comparisons are unspecified.
  4119. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  4120. E->isRelationalOp()) {
  4121. bool WasArrayIndex;
  4122. unsigned Mismatch =
  4123. FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
  4124. RHSDesignator, WasArrayIndex);
  4125. // At the point where the designators diverge, the comparison has a
  4126. // specified value if:
  4127. // - we are comparing array indices
  4128. // - we are comparing fields of a union, or fields with the same access
  4129. // Otherwise, the result is unspecified and thus the comparison is not a
  4130. // constant expression.
  4131. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  4132. Mismatch < RHSDesignator.Entries.size()) {
  4133. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  4134. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  4135. if (!LF && !RF)
  4136. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  4137. else if (!LF)
  4138. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  4139. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  4140. << RF->getParent() << RF;
  4141. else if (!RF)
  4142. CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  4143. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  4144. << LF->getParent() << LF;
  4145. else if (!LF->getParent()->isUnion() &&
  4146. LF->getAccess() != RF->getAccess())
  4147. CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
  4148. << LF << LF->getAccess() << RF << RF->getAccess()
  4149. << LF->getParent();
  4150. }
  4151. }
  4152. switch (E->getOpcode()) {
  4153. default: llvm_unreachable("missing comparison operator");
  4154. case BO_LT: return Success(LHSOffset < RHSOffset, E);
  4155. case BO_GT: return Success(LHSOffset > RHSOffset, E);
  4156. case BO_LE: return Success(LHSOffset <= RHSOffset, E);
  4157. case BO_GE: return Success(LHSOffset >= RHSOffset, E);
  4158. case BO_EQ: return Success(LHSOffset == RHSOffset, E);
  4159. case BO_NE: return Success(LHSOffset != RHSOffset, E);
  4160. }
  4161. }
  4162. }
  4163. if (LHSTy->isMemberPointerType()) {
  4164. assert(E->isEqualityOp() && "unexpected member pointer operation");
  4165. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  4166. MemberPtr LHSValue, RHSValue;
  4167. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  4168. if (!LHSOK && Info.keepEvaluatingAfterFailure())
  4169. return false;
  4170. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  4171. return false;
  4172. // C++11 [expr.eq]p2:
  4173. // If both operands are null, they compare equal. Otherwise if only one is
  4174. // null, they compare unequal.
  4175. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  4176. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  4177. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  4178. }
  4179. // Otherwise if either is a pointer to a virtual member function, the
  4180. // result is unspecified.
  4181. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  4182. if (MD->isVirtual())
  4183. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  4184. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  4185. if (MD->isVirtual())
  4186. CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  4187. // Otherwise they compare equal if and only if they would refer to the
  4188. // same member of the same most derived object or the same subobject if
  4189. // they were dereferenced with a hypothetical object of the associated
  4190. // class type.
  4191. bool Equal = LHSValue == RHSValue;
  4192. return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
  4193. }
  4194. if (LHSTy->isNullPtrType()) {
  4195. assert(E->isComparisonOp() && "unexpected nullptr operation");
  4196. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  4197. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  4198. // are compared, the result is true of the operator is <=, >= or ==, and
  4199. // false otherwise.
  4200. BinaryOperator::Opcode Opcode = E->getOpcode();
  4201. return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
  4202. }
  4203. if (!LHSTy->isIntegralOrEnumerationType() ||
  4204. !RHSTy->isIntegralOrEnumerationType()) {
  4205. // We can't continue from here for non-integral types.
  4206. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4207. }
  4208. // The LHS of a constant expr is always evaluated and needed.
  4209. APValue LHSVal;
  4210. bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
  4211. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4212. return false;
  4213. if (!Visit(E->getRHS()) || !LHSOK)
  4214. return false;
  4215. APValue &RHSVal = Result;
  4216. // Handle cases like (unsigned long)&a + 4.
  4217. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  4218. CharUnits AdditionalOffset = CharUnits::fromQuantity(
  4219. RHSVal.getInt().getZExtValue());
  4220. if (E->getOpcode() == BO_Add)
  4221. LHSVal.getLValueOffset() += AdditionalOffset;
  4222. else
  4223. LHSVal.getLValueOffset() -= AdditionalOffset;
  4224. Result = LHSVal;
  4225. return true;
  4226. }
  4227. // Handle cases like 4 + (unsigned long)&a
  4228. if (E->getOpcode() == BO_Add &&
  4229. RHSVal.isLValue() && LHSVal.isInt()) {
  4230. RHSVal.getLValueOffset() += CharUnits::fromQuantity(
  4231. LHSVal.getInt().getZExtValue());
  4232. // Note that RHSVal is Result.
  4233. return true;
  4234. }
  4235. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  4236. // Handle (intptr_t)&&A - (intptr_t)&&B.
  4237. if (!LHSVal.getLValueOffset().isZero() ||
  4238. !RHSVal.getLValueOffset().isZero())
  4239. return false;
  4240. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  4241. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  4242. if (!LHSExpr || !RHSExpr)
  4243. return false;
  4244. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  4245. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  4246. if (!LHSAddrExpr || !RHSAddrExpr)
  4247. return false;
  4248. // Make sure both labels come from the same function.
  4249. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  4250. RHSAddrExpr->getLabel()->getDeclContext())
  4251. return false;
  4252. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  4253. return true;
  4254. }
  4255. // All the following cases expect both operands to be an integer
  4256. if (!LHSVal.isInt() || !RHSVal.isInt())
  4257. return Error(E);
  4258. APSInt &LHS = LHSVal.getInt();
  4259. APSInt &RHS = RHSVal.getInt();
  4260. switch (E->getOpcode()) {
  4261. default:
  4262. return Error(E);
  4263. case BO_Mul:
  4264. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4265. LHS.getBitWidth() * 2,
  4266. std::multiplies<APSInt>()), E);
  4267. case BO_Add:
  4268. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4269. LHS.getBitWidth() + 1,
  4270. std::plus<APSInt>()), E);
  4271. case BO_Sub:
  4272. return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
  4273. LHS.getBitWidth() + 1,
  4274. std::minus<APSInt>()), E);
  4275. case BO_And: return Success(LHS & RHS, E);
  4276. case BO_Xor: return Success(LHS ^ RHS, E);
  4277. case BO_Or: return Success(LHS | RHS, E);
  4278. case BO_Div:
  4279. case BO_Rem:
  4280. if (RHS == 0)
  4281. return Error(E, diag::note_expr_divide_by_zero);
  4282. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
  4283. // actually undefined behavior in C++11 due to a language defect.
  4284. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  4285. LHS.isSigned() && LHS.isMinSignedValue())
  4286. HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
  4287. return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
  4288. case BO_Shl: {
  4289. // During constant-folding, a negative shift is an opposite shift. Such a
  4290. // shift is not a constant expression.
  4291. if (RHS.isSigned() && RHS.isNegative()) {
  4292. CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  4293. RHS = -RHS;
  4294. goto shift_right;
  4295. }
  4296. shift_left:
  4297. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  4298. // shifted type.
  4299. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  4300. if (SA != RHS) {
  4301. CCEDiag(E, diag::note_constexpr_large_shift)
  4302. << RHS << E->getType() << LHS.getBitWidth();
  4303. } else if (LHS.isSigned()) {
  4304. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  4305. // operand, and must not overflow the corresponding unsigned type.
  4306. if (LHS.isNegative())
  4307. CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  4308. else if (LHS.countLeadingZeros() < SA)
  4309. CCEDiag(E, diag::note_constexpr_lshift_discards);
  4310. }
  4311. return Success(LHS << SA, E);
  4312. }
  4313. case BO_Shr: {
  4314. // During constant-folding, a negative shift is an opposite shift. Such a
  4315. // shift is not a constant expression.
  4316. if (RHS.isSigned() && RHS.isNegative()) {
  4317. CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  4318. RHS = -RHS;
  4319. goto shift_left;
  4320. }
  4321. shift_right:
  4322. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  4323. // shifted type.
  4324. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  4325. if (SA != RHS)
  4326. CCEDiag(E, diag::note_constexpr_large_shift)
  4327. << RHS << E->getType() << LHS.getBitWidth();
  4328. return Success(LHS >> SA, E);
  4329. }
  4330. case BO_LT: return Success(LHS < RHS, E);
  4331. case BO_GT: return Success(LHS > RHS, E);
  4332. case BO_LE: return Success(LHS <= RHS, E);
  4333. case BO_GE: return Success(LHS >= RHS, E);
  4334. case BO_EQ: return Success(LHS == RHS, E);
  4335. case BO_NE: return Success(LHS != RHS, E);
  4336. }
  4337. }
  4338. CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
  4339. // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
  4340. // result shall be the alignment of the referenced type."
  4341. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  4342. T = Ref->getPointeeType();
  4343. // __alignof is defined to return the preferred alignment.
  4344. return Info.Ctx.toCharUnitsFromBits(
  4345. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  4346. }
  4347. CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
  4348. E = E->IgnoreParens();
  4349. // alignof decl is always accepted, even if it doesn't make sense: we default
  4350. // to 1 in those cases.
  4351. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4352. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  4353. /*RefAsPointee*/true);
  4354. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  4355. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  4356. /*RefAsPointee*/true);
  4357. return GetAlignOfType(E->getType());
  4358. }
  4359. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  4360. /// a result as the expression's type.
  4361. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  4362. const UnaryExprOrTypeTraitExpr *E) {
  4363. switch(E->getKind()) {
  4364. case UETT_AlignOf: {
  4365. if (E->isArgumentType())
  4366. return Success(GetAlignOfType(E->getArgumentType()), E);
  4367. else
  4368. return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
  4369. }
  4370. case UETT_VecStep: {
  4371. QualType Ty = E->getTypeOfArgument();
  4372. if (Ty->isVectorType()) {
  4373. unsigned n = Ty->getAs<VectorType>()->getNumElements();
  4374. // The vec_step built-in functions that take a 3-component
  4375. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  4376. if (n == 3)
  4377. n = 4;
  4378. return Success(n, E);
  4379. } else
  4380. return Success(1, E);
  4381. }
  4382. case UETT_SizeOf: {
  4383. QualType SrcTy = E->getTypeOfArgument();
  4384. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  4385. // the result is the size of the referenced type."
  4386. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  4387. SrcTy = Ref->getPointeeType();
  4388. CharUnits Sizeof;
  4389. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  4390. return false;
  4391. return Success(Sizeof, E);
  4392. }
  4393. }
  4394. llvm_unreachable("unknown expr/type trait");
  4395. }
  4396. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  4397. CharUnits Result;
  4398. unsigned n = OOE->getNumComponents();
  4399. if (n == 0)
  4400. return Error(OOE);
  4401. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  4402. for (unsigned i = 0; i != n; ++i) {
  4403. OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
  4404. switch (ON.getKind()) {
  4405. case OffsetOfExpr::OffsetOfNode::Array: {
  4406. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  4407. APSInt IdxResult;
  4408. if (!EvaluateInteger(Idx, IdxResult, Info))
  4409. return false;
  4410. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  4411. if (!AT)
  4412. return Error(OOE);
  4413. CurrentType = AT->getElementType();
  4414. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  4415. Result += IdxResult.getSExtValue() * ElementSize;
  4416. break;
  4417. }
  4418. case OffsetOfExpr::OffsetOfNode::Field: {
  4419. FieldDecl *MemberDecl = ON.getField();
  4420. const RecordType *RT = CurrentType->getAs<RecordType>();
  4421. if (!RT)
  4422. return Error(OOE);
  4423. RecordDecl *RD = RT->getDecl();
  4424. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  4425. unsigned i = MemberDecl->getFieldIndex();
  4426. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  4427. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  4428. CurrentType = MemberDecl->getType().getNonReferenceType();
  4429. break;
  4430. }
  4431. case OffsetOfExpr::OffsetOfNode::Identifier:
  4432. llvm_unreachable("dependent __builtin_offsetof");
  4433. case OffsetOfExpr::OffsetOfNode::Base: {
  4434. CXXBaseSpecifier *BaseSpec = ON.getBase();
  4435. if (BaseSpec->isVirtual())
  4436. return Error(OOE);
  4437. // Find the layout of the class whose base we are looking into.
  4438. const RecordType *RT = CurrentType->getAs<RecordType>();
  4439. if (!RT)
  4440. return Error(OOE);
  4441. RecordDecl *RD = RT->getDecl();
  4442. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  4443. // Find the base class itself.
  4444. CurrentType = BaseSpec->getType();
  4445. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  4446. if (!BaseRT)
  4447. return Error(OOE);
  4448. // Add the offset to the base.
  4449. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  4450. break;
  4451. }
  4452. }
  4453. }
  4454. return Success(Result, OOE);
  4455. }
  4456. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4457. switch (E->getOpcode()) {
  4458. default:
  4459. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  4460. // See C99 6.6p3.
  4461. return Error(E);
  4462. case UO_Extension:
  4463. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  4464. // If so, we could clear the diagnostic ID.
  4465. return Visit(E->getSubExpr());
  4466. case UO_Plus:
  4467. // The result is just the value.
  4468. return Visit(E->getSubExpr());
  4469. case UO_Minus: {
  4470. if (!Visit(E->getSubExpr()))
  4471. return false;
  4472. if (!Result.isInt()) return Error(E);
  4473. const APSInt &Value = Result.getInt();
  4474. if (Value.isSigned() && Value.isMinSignedValue())
  4475. HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  4476. E->getType());
  4477. return Success(-Value, E);
  4478. }
  4479. case UO_Not: {
  4480. if (!Visit(E->getSubExpr()))
  4481. return false;
  4482. if (!Result.isInt()) return Error(E);
  4483. return Success(~Result.getInt(), E);
  4484. }
  4485. case UO_LNot: {
  4486. bool bres;
  4487. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  4488. return false;
  4489. return Success(!bres, E);
  4490. }
  4491. }
  4492. }
  4493. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  4494. /// result type is integer.
  4495. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4496. const Expr *SubExpr = E->getSubExpr();
  4497. QualType DestType = E->getType();
  4498. QualType SrcType = SubExpr->getType();
  4499. switch (E->getCastKind()) {
  4500. case CK_BaseToDerived:
  4501. case CK_DerivedToBase:
  4502. case CK_UncheckedDerivedToBase:
  4503. case CK_Dynamic:
  4504. case CK_ToUnion:
  4505. case CK_ArrayToPointerDecay:
  4506. case CK_FunctionToPointerDecay:
  4507. case CK_NullToPointer:
  4508. case CK_NullToMemberPointer:
  4509. case CK_BaseToDerivedMemberPointer:
  4510. case CK_DerivedToBaseMemberPointer:
  4511. case CK_ReinterpretMemberPointer:
  4512. case CK_ConstructorConversion:
  4513. case CK_IntegralToPointer:
  4514. case CK_ToVoid:
  4515. case CK_VectorSplat:
  4516. case CK_IntegralToFloating:
  4517. case CK_FloatingCast:
  4518. case CK_CPointerToObjCPointerCast:
  4519. case CK_BlockPointerToObjCPointerCast:
  4520. case CK_AnyPointerToBlockPointerCast:
  4521. case CK_ObjCObjectLValueCast:
  4522. case CK_FloatingRealToComplex:
  4523. case CK_FloatingComplexToReal:
  4524. case CK_FloatingComplexCast:
  4525. case CK_FloatingComplexToIntegralComplex:
  4526. case CK_IntegralRealToComplex:
  4527. case CK_IntegralComplexCast:
  4528. case CK_IntegralComplexToFloatingComplex:
  4529. llvm_unreachable("invalid cast kind for integral value");
  4530. case CK_BitCast:
  4531. case CK_Dependent:
  4532. case CK_LValueBitCast:
  4533. case CK_ARCProduceObject:
  4534. case CK_ARCConsumeObject:
  4535. case CK_ARCReclaimReturnedObject:
  4536. case CK_ARCExtendBlockObject:
  4537. case CK_CopyAndAutoreleaseBlockObject:
  4538. return Error(E);
  4539. case CK_UserDefinedConversion:
  4540. case CK_LValueToRValue:
  4541. case CK_AtomicToNonAtomic:
  4542. case CK_NonAtomicToAtomic:
  4543. case CK_NoOp:
  4544. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4545. case CK_MemberPointerToBoolean:
  4546. case CK_PointerToBoolean:
  4547. case CK_IntegralToBoolean:
  4548. case CK_FloatingToBoolean:
  4549. case CK_FloatingComplexToBoolean:
  4550. case CK_IntegralComplexToBoolean: {
  4551. bool BoolResult;
  4552. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  4553. return false;
  4554. return Success(BoolResult, E);
  4555. }
  4556. case CK_IntegralCast: {
  4557. if (!Visit(SubExpr))
  4558. return false;
  4559. if (!Result.isInt()) {
  4560. // Allow casts of address-of-label differences if they are no-ops
  4561. // or narrowing. (The narrowing case isn't actually guaranteed to
  4562. // be constant-evaluatable except in some narrow cases which are hard
  4563. // to detect here. We let it through on the assumption the user knows
  4564. // what they are doing.)
  4565. if (Result.isAddrLabelDiff())
  4566. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  4567. // Only allow casts of lvalues if they are lossless.
  4568. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  4569. }
  4570. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  4571. Result.getInt()), E);
  4572. }
  4573. case CK_PointerToIntegral: {
  4574. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  4575. LValue LV;
  4576. if (!EvaluatePointer(SubExpr, LV, Info))
  4577. return false;
  4578. if (LV.getLValueBase()) {
  4579. // Only allow based lvalue casts if they are lossless.
  4580. // FIXME: Allow a larger integer size than the pointer size, and allow
  4581. // narrowing back down to pointer width in subsequent integral casts.
  4582. // FIXME: Check integer type's active bits, not its type size.
  4583. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  4584. return Error(E);
  4585. LV.Designator.setInvalid();
  4586. LV.moveInto(Result);
  4587. return true;
  4588. }
  4589. APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
  4590. SrcType);
  4591. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  4592. }
  4593. case CK_IntegralComplexToReal: {
  4594. ComplexValue C;
  4595. if (!EvaluateComplex(SubExpr, C, Info))
  4596. return false;
  4597. return Success(C.getComplexIntReal(), E);
  4598. }
  4599. case CK_FloatingToIntegral: {
  4600. APFloat F(0.0);
  4601. if (!EvaluateFloat(SubExpr, F, Info))
  4602. return false;
  4603. APSInt Value;
  4604. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  4605. return false;
  4606. return Success(Value, E);
  4607. }
  4608. }
  4609. llvm_unreachable("unknown cast resulting in integral value");
  4610. }
  4611. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4612. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4613. ComplexValue LV;
  4614. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  4615. return false;
  4616. if (!LV.isComplexInt())
  4617. return Error(E);
  4618. return Success(LV.getComplexIntReal(), E);
  4619. }
  4620. return Visit(E->getSubExpr());
  4621. }
  4622. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4623. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  4624. ComplexValue LV;
  4625. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  4626. return false;
  4627. if (!LV.isComplexInt())
  4628. return Error(E);
  4629. return Success(LV.getComplexIntImag(), E);
  4630. }
  4631. VisitIgnoredValue(E->getSubExpr());
  4632. return Success(0, E);
  4633. }
  4634. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  4635. return Success(E->getPackLength(), E);
  4636. }
  4637. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  4638. return Success(E->getValue(), E);
  4639. }
  4640. //===----------------------------------------------------------------------===//
  4641. // Float Evaluation
  4642. //===----------------------------------------------------------------------===//
  4643. namespace {
  4644. class FloatExprEvaluator
  4645. : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
  4646. APFloat &Result;
  4647. public:
  4648. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  4649. : ExprEvaluatorBaseTy(info), Result(result) {}
  4650. bool Success(const APValue &V, const Expr *e) {
  4651. Result = V.getFloat();
  4652. return true;
  4653. }
  4654. bool ZeroInitialization(const Expr *E) {
  4655. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  4656. return true;
  4657. }
  4658. bool VisitCallExpr(const CallExpr *E);
  4659. bool VisitUnaryOperator(const UnaryOperator *E);
  4660. bool VisitBinaryOperator(const BinaryOperator *E);
  4661. bool VisitFloatingLiteral(const FloatingLiteral *E);
  4662. bool VisitCastExpr(const CastExpr *E);
  4663. bool VisitUnaryReal(const UnaryOperator *E);
  4664. bool VisitUnaryImag(const UnaryOperator *E);
  4665. // FIXME: Missing: array subscript of vector, member of vector
  4666. };
  4667. } // end anonymous namespace
  4668. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  4669. assert(E->isRValue() && E->getType()->isRealFloatingType());
  4670. return FloatExprEvaluator(Info, Result).Visit(E);
  4671. }
  4672. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  4673. QualType ResultTy,
  4674. const Expr *Arg,
  4675. bool SNaN,
  4676. llvm::APFloat &Result) {
  4677. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  4678. if (!S) return false;
  4679. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  4680. llvm::APInt fill;
  4681. // Treat empty strings as if they were zero.
  4682. if (S->getString().empty())
  4683. fill = llvm::APInt(32, 0);
  4684. else if (S->getString().getAsInteger(0, fill))
  4685. return false;
  4686. if (SNaN)
  4687. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  4688. else
  4689. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  4690. return true;
  4691. }
  4692. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  4693. switch (E->isBuiltinCall()) {
  4694. default:
  4695. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  4696. case Builtin::BI__builtin_huge_val:
  4697. case Builtin::BI__builtin_huge_valf:
  4698. case Builtin::BI__builtin_huge_vall:
  4699. case Builtin::BI__builtin_inf:
  4700. case Builtin::BI__builtin_inff:
  4701. case Builtin::BI__builtin_infl: {
  4702. const llvm::fltSemantics &Sem =
  4703. Info.Ctx.getFloatTypeSemantics(E->getType());
  4704. Result = llvm::APFloat::getInf(Sem);
  4705. return true;
  4706. }
  4707. case Builtin::BI__builtin_nans:
  4708. case Builtin::BI__builtin_nansf:
  4709. case Builtin::BI__builtin_nansl:
  4710. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  4711. true, Result))
  4712. return Error(E);
  4713. return true;
  4714. case Builtin::BI__builtin_nan:
  4715. case Builtin::BI__builtin_nanf:
  4716. case Builtin::BI__builtin_nanl:
  4717. // If this is __builtin_nan() turn this into a nan, otherwise we
  4718. // can't constant fold it.
  4719. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  4720. false, Result))
  4721. return Error(E);
  4722. return true;
  4723. case Builtin::BI__builtin_fabs:
  4724. case Builtin::BI__builtin_fabsf:
  4725. case Builtin::BI__builtin_fabsl:
  4726. if (!EvaluateFloat(E->getArg(0), Result, Info))
  4727. return false;
  4728. if (Result.isNegative())
  4729. Result.changeSign();
  4730. return true;
  4731. case Builtin::BI__builtin_copysign:
  4732. case Builtin::BI__builtin_copysignf:
  4733. case Builtin::BI__builtin_copysignl: {
  4734. APFloat RHS(0.);
  4735. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  4736. !EvaluateFloat(E->getArg(1), RHS, Info))
  4737. return false;
  4738. Result.copySign(RHS);
  4739. return true;
  4740. }
  4741. }
  4742. }
  4743. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  4744. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4745. ComplexValue CV;
  4746. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  4747. return false;
  4748. Result = CV.FloatReal;
  4749. return true;
  4750. }
  4751. return Visit(E->getSubExpr());
  4752. }
  4753. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  4754. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  4755. ComplexValue CV;
  4756. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  4757. return false;
  4758. Result = CV.FloatImag;
  4759. return true;
  4760. }
  4761. VisitIgnoredValue(E->getSubExpr());
  4762. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  4763. Result = llvm::APFloat::getZero(Sem);
  4764. return true;
  4765. }
  4766. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  4767. switch (E->getOpcode()) {
  4768. default: return Error(E);
  4769. case UO_Plus:
  4770. return EvaluateFloat(E->getSubExpr(), Result, Info);
  4771. case UO_Minus:
  4772. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  4773. return false;
  4774. Result.changeSign();
  4775. return true;
  4776. }
  4777. }
  4778. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  4779. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  4780. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  4781. APFloat RHS(0.0);
  4782. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  4783. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  4784. return false;
  4785. if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
  4786. return false;
  4787. switch (E->getOpcode()) {
  4788. default: return Error(E);
  4789. case BO_Mul:
  4790. Result.multiply(RHS, APFloat::rmNearestTiesToEven);
  4791. break;
  4792. case BO_Add:
  4793. Result.add(RHS, APFloat::rmNearestTiesToEven);
  4794. break;
  4795. case BO_Sub:
  4796. Result.subtract(RHS, APFloat::rmNearestTiesToEven);
  4797. break;
  4798. case BO_Div:
  4799. Result.divide(RHS, APFloat::rmNearestTiesToEven);
  4800. break;
  4801. }
  4802. if (Result.isInfinity() || Result.isNaN())
  4803. CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
  4804. return true;
  4805. }
  4806. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  4807. Result = E->getValue();
  4808. return true;
  4809. }
  4810. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4811. const Expr* SubExpr = E->getSubExpr();
  4812. switch (E->getCastKind()) {
  4813. default:
  4814. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4815. case CK_IntegralToFloating: {
  4816. APSInt IntResult;
  4817. return EvaluateInteger(SubExpr, IntResult, Info) &&
  4818. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  4819. E->getType(), Result);
  4820. }
  4821. case CK_FloatingCast: {
  4822. if (!Visit(SubExpr))
  4823. return false;
  4824. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  4825. Result);
  4826. }
  4827. case CK_FloatingComplexToReal: {
  4828. ComplexValue V;
  4829. if (!EvaluateComplex(SubExpr, V, Info))
  4830. return false;
  4831. Result = V.getComplexFloatReal();
  4832. return true;
  4833. }
  4834. }
  4835. }
  4836. //===----------------------------------------------------------------------===//
  4837. // Complex Evaluation (for float and integer)
  4838. //===----------------------------------------------------------------------===//
  4839. namespace {
  4840. class ComplexExprEvaluator
  4841. : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
  4842. ComplexValue &Result;
  4843. public:
  4844. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  4845. : ExprEvaluatorBaseTy(info), Result(Result) {}
  4846. bool Success(const APValue &V, const Expr *e) {
  4847. Result.setFrom(V);
  4848. return true;
  4849. }
  4850. bool ZeroInitialization(const Expr *E);
  4851. //===--------------------------------------------------------------------===//
  4852. // Visitor Methods
  4853. //===--------------------------------------------------------------------===//
  4854. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  4855. bool VisitCastExpr(const CastExpr *E);
  4856. bool VisitBinaryOperator(const BinaryOperator *E);
  4857. bool VisitUnaryOperator(const UnaryOperator *E);
  4858. bool VisitInitListExpr(const InitListExpr *E);
  4859. };
  4860. } // end anonymous namespace
  4861. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  4862. EvalInfo &Info) {
  4863. assert(E->isRValue() && E->getType()->isAnyComplexType());
  4864. return ComplexExprEvaluator(Info, Result).Visit(E);
  4865. }
  4866. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  4867. QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
  4868. if (ElemTy->isRealFloatingType()) {
  4869. Result.makeComplexFloat();
  4870. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  4871. Result.FloatReal = Zero;
  4872. Result.FloatImag = Zero;
  4873. } else {
  4874. Result.makeComplexInt();
  4875. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  4876. Result.IntReal = Zero;
  4877. Result.IntImag = Zero;
  4878. }
  4879. return true;
  4880. }
  4881. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  4882. const Expr* SubExpr = E->getSubExpr();
  4883. if (SubExpr->getType()->isRealFloatingType()) {
  4884. Result.makeComplexFloat();
  4885. APFloat &Imag = Result.FloatImag;
  4886. if (!EvaluateFloat(SubExpr, Imag, Info))
  4887. return false;
  4888. Result.FloatReal = APFloat(Imag.getSemantics());
  4889. return true;
  4890. } else {
  4891. assert(SubExpr->getType()->isIntegerType() &&
  4892. "Unexpected imaginary literal.");
  4893. Result.makeComplexInt();
  4894. APSInt &Imag = Result.IntImag;
  4895. if (!EvaluateInteger(SubExpr, Imag, Info))
  4896. return false;
  4897. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  4898. return true;
  4899. }
  4900. }
  4901. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  4902. switch (E->getCastKind()) {
  4903. case CK_BitCast:
  4904. case CK_BaseToDerived:
  4905. case CK_DerivedToBase:
  4906. case CK_UncheckedDerivedToBase:
  4907. case CK_Dynamic:
  4908. case CK_ToUnion:
  4909. case CK_ArrayToPointerDecay:
  4910. case CK_FunctionToPointerDecay:
  4911. case CK_NullToPointer:
  4912. case CK_NullToMemberPointer:
  4913. case CK_BaseToDerivedMemberPointer:
  4914. case CK_DerivedToBaseMemberPointer:
  4915. case CK_MemberPointerToBoolean:
  4916. case CK_ReinterpretMemberPointer:
  4917. case CK_ConstructorConversion:
  4918. case CK_IntegralToPointer:
  4919. case CK_PointerToIntegral:
  4920. case CK_PointerToBoolean:
  4921. case CK_ToVoid:
  4922. case CK_VectorSplat:
  4923. case CK_IntegralCast:
  4924. case CK_IntegralToBoolean:
  4925. case CK_IntegralToFloating:
  4926. case CK_FloatingToIntegral:
  4927. case CK_FloatingToBoolean:
  4928. case CK_FloatingCast:
  4929. case CK_CPointerToObjCPointerCast:
  4930. case CK_BlockPointerToObjCPointerCast:
  4931. case CK_AnyPointerToBlockPointerCast:
  4932. case CK_ObjCObjectLValueCast:
  4933. case CK_FloatingComplexToReal:
  4934. case CK_FloatingComplexToBoolean:
  4935. case CK_IntegralComplexToReal:
  4936. case CK_IntegralComplexToBoolean:
  4937. case CK_ARCProduceObject:
  4938. case CK_ARCConsumeObject:
  4939. case CK_ARCReclaimReturnedObject:
  4940. case CK_ARCExtendBlockObject:
  4941. case CK_CopyAndAutoreleaseBlockObject:
  4942. llvm_unreachable("invalid cast kind for complex value");
  4943. case CK_LValueToRValue:
  4944. case CK_AtomicToNonAtomic:
  4945. case CK_NonAtomicToAtomic:
  4946. case CK_NoOp:
  4947. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  4948. case CK_Dependent:
  4949. case CK_LValueBitCast:
  4950. case CK_UserDefinedConversion:
  4951. return Error(E);
  4952. case CK_FloatingRealToComplex: {
  4953. APFloat &Real = Result.FloatReal;
  4954. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  4955. return false;
  4956. Result.makeComplexFloat();
  4957. Result.FloatImag = APFloat(Real.getSemantics());
  4958. return true;
  4959. }
  4960. case CK_FloatingComplexCast: {
  4961. if (!Visit(E->getSubExpr()))
  4962. return false;
  4963. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4964. QualType From
  4965. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4966. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  4967. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  4968. }
  4969. case CK_FloatingComplexToIntegralComplex: {
  4970. if (!Visit(E->getSubExpr()))
  4971. return false;
  4972. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4973. QualType From
  4974. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4975. Result.makeComplexInt();
  4976. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  4977. To, Result.IntReal) &&
  4978. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  4979. To, Result.IntImag);
  4980. }
  4981. case CK_IntegralRealToComplex: {
  4982. APSInt &Real = Result.IntReal;
  4983. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  4984. return false;
  4985. Result.makeComplexInt();
  4986. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  4987. return true;
  4988. }
  4989. case CK_IntegralComplexCast: {
  4990. if (!Visit(E->getSubExpr()))
  4991. return false;
  4992. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  4993. QualType From
  4994. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  4995. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  4996. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  4997. return true;
  4998. }
  4999. case CK_IntegralComplexToFloatingComplex: {
  5000. if (!Visit(E->getSubExpr()))
  5001. return false;
  5002. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  5003. QualType From
  5004. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  5005. Result.makeComplexFloat();
  5006. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  5007. To, Result.FloatReal) &&
  5008. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  5009. To, Result.FloatImag);
  5010. }
  5011. }
  5012. llvm_unreachable("unknown cast resulting in complex value");
  5013. }
  5014. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5015. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  5016. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5017. bool LHSOK = Visit(E->getLHS());
  5018. if (!LHSOK && !Info.keepEvaluatingAfterFailure())
  5019. return false;
  5020. ComplexValue RHS;
  5021. if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  5022. return false;
  5023. assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
  5024. "Invalid operands to binary operator.");
  5025. switch (E->getOpcode()) {
  5026. default: return Error(E);
  5027. case BO_Add:
  5028. if (Result.isComplexFloat()) {
  5029. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  5030. APFloat::rmNearestTiesToEven);
  5031. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  5032. APFloat::rmNearestTiesToEven);
  5033. } else {
  5034. Result.getComplexIntReal() += RHS.getComplexIntReal();
  5035. Result.getComplexIntImag() += RHS.getComplexIntImag();
  5036. }
  5037. break;
  5038. case BO_Sub:
  5039. if (Result.isComplexFloat()) {
  5040. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  5041. APFloat::rmNearestTiesToEven);
  5042. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  5043. APFloat::rmNearestTiesToEven);
  5044. } else {
  5045. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  5046. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  5047. }
  5048. break;
  5049. case BO_Mul:
  5050. if (Result.isComplexFloat()) {
  5051. ComplexValue LHS = Result;
  5052. APFloat &LHS_r = LHS.getComplexFloatReal();
  5053. APFloat &LHS_i = LHS.getComplexFloatImag();
  5054. APFloat &RHS_r = RHS.getComplexFloatReal();
  5055. APFloat &RHS_i = RHS.getComplexFloatImag();
  5056. APFloat Tmp = LHS_r;
  5057. Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5058. Result.getComplexFloatReal() = Tmp;
  5059. Tmp = LHS_i;
  5060. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5061. Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
  5062. Tmp = LHS_r;
  5063. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5064. Result.getComplexFloatImag() = Tmp;
  5065. Tmp = LHS_i;
  5066. Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5067. Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
  5068. } else {
  5069. ComplexValue LHS = Result;
  5070. Result.getComplexIntReal() =
  5071. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  5072. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  5073. Result.getComplexIntImag() =
  5074. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  5075. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  5076. }
  5077. break;
  5078. case BO_Div:
  5079. if (Result.isComplexFloat()) {
  5080. ComplexValue LHS = Result;
  5081. APFloat &LHS_r = LHS.getComplexFloatReal();
  5082. APFloat &LHS_i = LHS.getComplexFloatImag();
  5083. APFloat &RHS_r = RHS.getComplexFloatReal();
  5084. APFloat &RHS_i = RHS.getComplexFloatImag();
  5085. APFloat &Res_r = Result.getComplexFloatReal();
  5086. APFloat &Res_i = Result.getComplexFloatImag();
  5087. APFloat Den = RHS_r;
  5088. Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5089. APFloat Tmp = RHS_i;
  5090. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5091. Den.add(Tmp, APFloat::rmNearestTiesToEven);
  5092. Res_r = LHS_r;
  5093. Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5094. Tmp = LHS_i;
  5095. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5096. Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
  5097. Res_r.divide(Den, APFloat::rmNearestTiesToEven);
  5098. Res_i = LHS_i;
  5099. Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
  5100. Tmp = LHS_r;
  5101. Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
  5102. Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
  5103. Res_i.divide(Den, APFloat::rmNearestTiesToEven);
  5104. } else {
  5105. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  5106. return Error(E, diag::note_expr_divide_by_zero);
  5107. ComplexValue LHS = Result;
  5108. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  5109. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  5110. Result.getComplexIntReal() =
  5111. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  5112. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  5113. Result.getComplexIntImag() =
  5114. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  5115. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  5116. }
  5117. break;
  5118. }
  5119. return true;
  5120. }
  5121. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  5122. // Get the operand value into 'Result'.
  5123. if (!Visit(E->getSubExpr()))
  5124. return false;
  5125. switch (E->getOpcode()) {
  5126. default:
  5127. return Error(E);
  5128. case UO_Extension:
  5129. return true;
  5130. case UO_Plus:
  5131. // The result is always just the subexpr.
  5132. return true;
  5133. case UO_Minus:
  5134. if (Result.isComplexFloat()) {
  5135. Result.getComplexFloatReal().changeSign();
  5136. Result.getComplexFloatImag().changeSign();
  5137. }
  5138. else {
  5139. Result.getComplexIntReal() = -Result.getComplexIntReal();
  5140. Result.getComplexIntImag() = -Result.getComplexIntImag();
  5141. }
  5142. return true;
  5143. case UO_Not:
  5144. if (Result.isComplexFloat())
  5145. Result.getComplexFloatImag().changeSign();
  5146. else
  5147. Result.getComplexIntImag() = -Result.getComplexIntImag();
  5148. return true;
  5149. }
  5150. }
  5151. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  5152. if (E->getNumInits() == 2) {
  5153. if (E->getType()->isComplexType()) {
  5154. Result.makeComplexFloat();
  5155. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  5156. return false;
  5157. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  5158. return false;
  5159. } else {
  5160. Result.makeComplexInt();
  5161. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  5162. return false;
  5163. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  5164. return false;
  5165. }
  5166. return true;
  5167. }
  5168. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  5169. }
  5170. //===----------------------------------------------------------------------===//
  5171. // Void expression evaluation, primarily for a cast to void on the LHS of a
  5172. // comma operator
  5173. //===----------------------------------------------------------------------===//
  5174. namespace {
  5175. class VoidExprEvaluator
  5176. : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
  5177. public:
  5178. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  5179. bool Success(const APValue &V, const Expr *e) { return true; }
  5180. bool VisitCastExpr(const CastExpr *E) {
  5181. switch (E->getCastKind()) {
  5182. default:
  5183. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5184. case CK_ToVoid:
  5185. VisitIgnoredValue(E->getSubExpr());
  5186. return true;
  5187. }
  5188. }
  5189. };
  5190. } // end anonymous namespace
  5191. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  5192. assert(E->isRValue() && E->getType()->isVoidType());
  5193. return VoidExprEvaluator(Info).Visit(E);
  5194. }
  5195. //===----------------------------------------------------------------------===//
  5196. // Top level Expr::EvaluateAsRValue method.
  5197. //===----------------------------------------------------------------------===//
  5198. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  5199. // In C, function designators are not lvalues, but we evaluate them as if they
  5200. // are.
  5201. if (E->isGLValue() || E->getType()->isFunctionType()) {
  5202. LValue LV;
  5203. if (!EvaluateLValue(E, LV, Info))
  5204. return false;
  5205. LV.moveInto(Result);
  5206. } else if (E->getType()->isVectorType()) {
  5207. if (!EvaluateVector(E, Result, Info))
  5208. return false;
  5209. } else if (E->getType()->isIntegralOrEnumerationType()) {
  5210. if (!IntExprEvaluator(Info, Result).Visit(E))
  5211. return false;
  5212. } else if (E->getType()->hasPointerRepresentation()) {
  5213. LValue LV;
  5214. if (!EvaluatePointer(E, LV, Info))
  5215. return false;
  5216. LV.moveInto(Result);
  5217. } else if (E->getType()->isRealFloatingType()) {
  5218. llvm::APFloat F(0.0);
  5219. if (!EvaluateFloat(E, F, Info))
  5220. return false;
  5221. Result = APValue(F);
  5222. } else if (E->getType()->isAnyComplexType()) {
  5223. ComplexValue C;
  5224. if (!EvaluateComplex(E, C, Info))
  5225. return false;
  5226. C.moveInto(Result);
  5227. } else if (E->getType()->isMemberPointerType()) {
  5228. MemberPtr P;
  5229. if (!EvaluateMemberPointer(E, P, Info))
  5230. return false;
  5231. P.moveInto(Result);
  5232. return true;
  5233. } else if (E->getType()->isArrayType()) {
  5234. LValue LV;
  5235. LV.set(E, Info.CurrentCall->Index);
  5236. if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
  5237. return false;
  5238. Result = Info.CurrentCall->Temporaries[E];
  5239. } else if (E->getType()->isRecordType()) {
  5240. LValue LV;
  5241. LV.set(E, Info.CurrentCall->Index);
  5242. if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
  5243. return false;
  5244. Result = Info.CurrentCall->Temporaries[E];
  5245. } else if (E->getType()->isVoidType()) {
  5246. if (Info.getLangOpts().CPlusPlus0x)
  5247. Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
  5248. << E->getType();
  5249. else
  5250. Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  5251. if (!EvaluateVoid(E, Info))
  5252. return false;
  5253. } else if (Info.getLangOpts().CPlusPlus0x) {
  5254. Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
  5255. return false;
  5256. } else {
  5257. Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
  5258. return false;
  5259. }
  5260. return true;
  5261. }
  5262. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  5263. /// cases, the in-place evaluation is essential, since later initializers for
  5264. /// an object can indirectly refer to subobjects which were initialized earlier.
  5265. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  5266. const Expr *E, CheckConstantExpressionKind CCEK,
  5267. bool AllowNonLiteralTypes) {
  5268. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
  5269. return false;
  5270. if (E->isRValue()) {
  5271. // Evaluate arrays and record types in-place, so that later initializers can
  5272. // refer to earlier-initialized members of the object.
  5273. if (E->getType()->isArrayType())
  5274. return EvaluateArray(E, This, Result, Info);
  5275. else if (E->getType()->isRecordType())
  5276. return EvaluateRecord(E, This, Result, Info);
  5277. }
  5278. // For any other type, in-place evaluation is unimportant.
  5279. return Evaluate(Result, Info, E);
  5280. }
  5281. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  5282. /// lvalue-to-rvalue cast if it is an lvalue.
  5283. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  5284. if (!CheckLiteralType(Info, E))
  5285. return false;
  5286. if (!::Evaluate(Result, Info, E))
  5287. return false;
  5288. if (E->isGLValue()) {
  5289. LValue LV;
  5290. LV.setFrom(Info.Ctx, Result);
  5291. if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  5292. return false;
  5293. }
  5294. // Check this core constant expression is a constant expression.
  5295. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  5296. }
  5297. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  5298. /// any crazy technique (that has nothing to do with language standards) that
  5299. /// we want to. If this function returns true, it returns the folded constant
  5300. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  5301. /// will be applied to the result.
  5302. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
  5303. // Fast-path evaluations of integer literals, since we sometimes see files
  5304. // containing vast quantities of these.
  5305. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
  5306. Result.Val = APValue(APSInt(L->getValue(),
  5307. L->getType()->isUnsignedIntegerType()));
  5308. return true;
  5309. }
  5310. // FIXME: Evaluating values of large array and record types can cause
  5311. // performance problems. Only do so in C++11 for now.
  5312. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  5313. !Ctx.getLangOpts().CPlusPlus0x)
  5314. return false;
  5315. EvalInfo Info(Ctx, Result);
  5316. return ::EvaluateAsRValue(Info, this, Result.Val);
  5317. }
  5318. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  5319. const ASTContext &Ctx) const {
  5320. EvalResult Scratch;
  5321. return EvaluateAsRValue(Scratch, Ctx) &&
  5322. HandleConversionToBool(Scratch.Val, Result);
  5323. }
  5324. bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
  5325. SideEffectsKind AllowSideEffects) const {
  5326. if (!getType()->isIntegralOrEnumerationType())
  5327. return false;
  5328. EvalResult ExprResult;
  5329. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
  5330. (!AllowSideEffects && ExprResult.HasSideEffects))
  5331. return false;
  5332. Result = ExprResult.Val.getInt();
  5333. return true;
  5334. }
  5335. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  5336. EvalInfo Info(Ctx, Result);
  5337. LValue LV;
  5338. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  5339. !CheckLValueConstantExpression(Info, getExprLoc(),
  5340. Ctx.getLValueReferenceType(getType()), LV))
  5341. return false;
  5342. LV.moveInto(Result.Val);
  5343. return true;
  5344. }
  5345. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  5346. const VarDecl *VD,
  5347. llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  5348. // FIXME: Evaluating initializers for large array and record types can cause
  5349. // performance problems. Only do so in C++11 for now.
  5350. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  5351. !Ctx.getLangOpts().CPlusPlus0x)
  5352. return false;
  5353. Expr::EvalStatus EStatus;
  5354. EStatus.Diag = &Notes;
  5355. EvalInfo InitInfo(Ctx, EStatus);
  5356. InitInfo.setEvaluatingDecl(VD, Value);
  5357. LValue LVal;
  5358. LVal.set(VD);
  5359. // C++11 [basic.start.init]p2:
  5360. // Variables with static storage duration or thread storage duration shall be
  5361. // zero-initialized before any other initialization takes place.
  5362. // This behavior is not present in C.
  5363. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  5364. !VD->getType()->isReferenceType()) {
  5365. ImplicitValueInitExpr VIE(VD->getType());
  5366. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
  5367. /*AllowNonLiteralTypes=*/true))
  5368. return false;
  5369. }
  5370. if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
  5371. /*AllowNonLiteralTypes=*/true) ||
  5372. EStatus.HasSideEffects)
  5373. return false;
  5374. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  5375. Value);
  5376. }
  5377. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  5378. /// constant folded, but discard the result.
  5379. bool Expr::isEvaluatable(const ASTContext &Ctx) const {
  5380. EvalResult Result;
  5381. return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
  5382. }
  5383. bool Expr::HasSideEffects(const ASTContext &Ctx) const {
  5384. return HasSideEffect(Ctx).Visit(this);
  5385. }
  5386. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
  5387. EvalResult EvalResult;
  5388. bool Result = EvaluateAsRValue(EvalResult, Ctx);
  5389. (void)Result;
  5390. assert(Result && "Could not evaluate expression");
  5391. assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
  5392. return EvalResult.Val.getInt();
  5393. }
  5394. bool Expr::EvalResult::isGlobalLValue() const {
  5395. assert(Val.isLValue());
  5396. return IsGlobalLValue(Val.getLValueBase());
  5397. }
  5398. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  5399. /// an integer constant expression.
  5400. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  5401. /// comma, etc
  5402. ///
  5403. /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
  5404. /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
  5405. /// cast+dereference.
  5406. // CheckICE - This function does the fundamental ICE checking: the returned
  5407. // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
  5408. // Note that to reduce code duplication, this helper does no evaluation
  5409. // itself; the caller checks whether the expression is evaluatable, and
  5410. // in the rare cases where CheckICE actually cares about the evaluated
  5411. // value, it calls into Evalute.
  5412. //
  5413. // Meanings of Val:
  5414. // 0: This expression is an ICE.
  5415. // 1: This expression is not an ICE, but if it isn't evaluated, it's
  5416. // a legal subexpression for an ICE. This return value is used to handle
  5417. // the comma operator in C99 mode.
  5418. // 2: This expression is not an ICE, and is not a legal subexpression for one.
  5419. namespace {
  5420. struct ICEDiag {
  5421. unsigned Val;
  5422. SourceLocation Loc;
  5423. public:
  5424. ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
  5425. ICEDiag() : Val(0) {}
  5426. };
  5427. }
  5428. static ICEDiag NoDiag() { return ICEDiag(); }
  5429. static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
  5430. Expr::EvalResult EVResult;
  5431. if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
  5432. !EVResult.Val.isInt()) {
  5433. return ICEDiag(2, E->getLocStart());
  5434. }
  5435. return NoDiag();
  5436. }
  5437. static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
  5438. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  5439. if (!E->getType()->isIntegralOrEnumerationType()) {
  5440. return ICEDiag(2, E->getLocStart());
  5441. }
  5442. switch (E->getStmtClass()) {
  5443. #define ABSTRACT_STMT(Node)
  5444. #define STMT(Node, Base) case Expr::Node##Class:
  5445. #define EXPR(Node, Base)
  5446. #include "clang/AST/StmtNodes.inc"
  5447. case Expr::PredefinedExprClass:
  5448. case Expr::FloatingLiteralClass:
  5449. case Expr::ImaginaryLiteralClass:
  5450. case Expr::StringLiteralClass:
  5451. case Expr::ArraySubscriptExprClass:
  5452. case Expr::MemberExprClass:
  5453. case Expr::CompoundAssignOperatorClass:
  5454. case Expr::CompoundLiteralExprClass:
  5455. case Expr::ExtVectorElementExprClass:
  5456. case Expr::DesignatedInitExprClass:
  5457. case Expr::ImplicitValueInitExprClass:
  5458. case Expr::ParenListExprClass:
  5459. case Expr::VAArgExprClass:
  5460. case Expr::AddrLabelExprClass:
  5461. case Expr::StmtExprClass:
  5462. case Expr::CXXMemberCallExprClass:
  5463. case Expr::CUDAKernelCallExprClass:
  5464. case Expr::CXXDynamicCastExprClass:
  5465. case Expr::CXXTypeidExprClass:
  5466. case Expr::CXXUuidofExprClass:
  5467. case Expr::CXXNullPtrLiteralExprClass:
  5468. case Expr::UserDefinedLiteralClass:
  5469. case Expr::CXXThisExprClass:
  5470. case Expr::CXXThrowExprClass:
  5471. case Expr::CXXNewExprClass:
  5472. case Expr::CXXDeleteExprClass:
  5473. case Expr::CXXPseudoDestructorExprClass:
  5474. case Expr::UnresolvedLookupExprClass:
  5475. case Expr::DependentScopeDeclRefExprClass:
  5476. case Expr::CXXConstructExprClass:
  5477. case Expr::CXXBindTemporaryExprClass:
  5478. case Expr::ExprWithCleanupsClass:
  5479. case Expr::CXXTemporaryObjectExprClass:
  5480. case Expr::CXXUnresolvedConstructExprClass:
  5481. case Expr::CXXDependentScopeMemberExprClass:
  5482. case Expr::UnresolvedMemberExprClass:
  5483. case Expr::ObjCStringLiteralClass:
  5484. case Expr::ObjCNumericLiteralClass:
  5485. case Expr::ObjCArrayLiteralClass:
  5486. case Expr::ObjCDictionaryLiteralClass:
  5487. case Expr::ObjCEncodeExprClass:
  5488. case Expr::ObjCMessageExprClass:
  5489. case Expr::ObjCSelectorExprClass:
  5490. case Expr::ObjCProtocolExprClass:
  5491. case Expr::ObjCIvarRefExprClass:
  5492. case Expr::ObjCPropertyRefExprClass:
  5493. case Expr::ObjCSubscriptRefExprClass:
  5494. case Expr::ObjCIsaExprClass:
  5495. case Expr::ShuffleVectorExprClass:
  5496. case Expr::BlockExprClass:
  5497. case Expr::NoStmtClass:
  5498. case Expr::OpaqueValueExprClass:
  5499. case Expr::PackExpansionExprClass:
  5500. case Expr::SubstNonTypeTemplateParmPackExprClass:
  5501. case Expr::AsTypeExprClass:
  5502. case Expr::ObjCIndirectCopyRestoreExprClass:
  5503. case Expr::MaterializeTemporaryExprClass:
  5504. case Expr::PseudoObjectExprClass:
  5505. case Expr::AtomicExprClass:
  5506. case Expr::InitListExprClass:
  5507. case Expr::LambdaExprClass:
  5508. return ICEDiag(2, E->getLocStart());
  5509. case Expr::SizeOfPackExprClass:
  5510. case Expr::GNUNullExprClass:
  5511. // GCC considers the GNU __null value to be an integral constant expression.
  5512. return NoDiag();
  5513. case Expr::SubstNonTypeTemplateParmExprClass:
  5514. return
  5515. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  5516. case Expr::ParenExprClass:
  5517. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  5518. case Expr::GenericSelectionExprClass:
  5519. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  5520. case Expr::IntegerLiteralClass:
  5521. case Expr::CharacterLiteralClass:
  5522. case Expr::ObjCBoolLiteralExprClass:
  5523. case Expr::CXXBoolLiteralExprClass:
  5524. case Expr::CXXScalarValueInitExprClass:
  5525. case Expr::UnaryTypeTraitExprClass:
  5526. case Expr::BinaryTypeTraitExprClass:
  5527. case Expr::TypeTraitExprClass:
  5528. case Expr::ArrayTypeTraitExprClass:
  5529. case Expr::ExpressionTraitExprClass:
  5530. case Expr::CXXNoexceptExprClass:
  5531. return NoDiag();
  5532. case Expr::CallExprClass:
  5533. case Expr::CXXOperatorCallExprClass: {
  5534. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  5535. // constant expressions, but they can never be ICEs because an ICE cannot
  5536. // contain an operand of (pointer to) function type.
  5537. const CallExpr *CE = cast<CallExpr>(E);
  5538. if (CE->isBuiltinCall())
  5539. return CheckEvalInICE(E, Ctx);
  5540. return ICEDiag(2, E->getLocStart());
  5541. }
  5542. case Expr::DeclRefExprClass: {
  5543. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  5544. return NoDiag();
  5545. const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
  5546. if (Ctx.getLangOpts().CPlusPlus &&
  5547. D && IsConstNonVolatile(D->getType())) {
  5548. // Parameter variables are never constants. Without this check,
  5549. // getAnyInitializer() can find a default argument, which leads
  5550. // to chaos.
  5551. if (isa<ParmVarDecl>(D))
  5552. return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
  5553. // C++ 7.1.5.1p2
  5554. // A variable of non-volatile const-qualified integral or enumeration
  5555. // type initialized by an ICE can be used in ICEs.
  5556. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  5557. if (!Dcl->getType()->isIntegralOrEnumerationType())
  5558. return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
  5559. const VarDecl *VD;
  5560. // Look for a declaration of this variable that has an initializer, and
  5561. // check whether it is an ICE.
  5562. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  5563. return NoDiag();
  5564. else
  5565. return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
  5566. }
  5567. }
  5568. return ICEDiag(2, E->getLocStart());
  5569. }
  5570. case Expr::UnaryOperatorClass: {
  5571. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  5572. switch (Exp->getOpcode()) {
  5573. case UO_PostInc:
  5574. case UO_PostDec:
  5575. case UO_PreInc:
  5576. case UO_PreDec:
  5577. case UO_AddrOf:
  5578. case UO_Deref:
  5579. // C99 6.6/3 allows increment and decrement within unevaluated
  5580. // subexpressions of constant expressions, but they can never be ICEs
  5581. // because an ICE cannot contain an lvalue operand.
  5582. return ICEDiag(2, E->getLocStart());
  5583. case UO_Extension:
  5584. case UO_LNot:
  5585. case UO_Plus:
  5586. case UO_Minus:
  5587. case UO_Not:
  5588. case UO_Real:
  5589. case UO_Imag:
  5590. return CheckICE(Exp->getSubExpr(), Ctx);
  5591. }
  5592. // OffsetOf falls through here.
  5593. }
  5594. case Expr::OffsetOfExprClass: {
  5595. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  5596. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  5597. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  5598. // compliance: we should warn earlier for offsetof expressions with
  5599. // array subscripts that aren't ICEs, and if the array subscripts
  5600. // are ICEs, the value of the offsetof must be an integer constant.
  5601. return CheckEvalInICE(E, Ctx);
  5602. }
  5603. case Expr::UnaryExprOrTypeTraitExprClass: {
  5604. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  5605. if ((Exp->getKind() == UETT_SizeOf) &&
  5606. Exp->getTypeOfArgument()->isVariableArrayType())
  5607. return ICEDiag(2, E->getLocStart());
  5608. return NoDiag();
  5609. }
  5610. case Expr::BinaryOperatorClass: {
  5611. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  5612. switch (Exp->getOpcode()) {
  5613. case BO_PtrMemD:
  5614. case BO_PtrMemI:
  5615. case BO_Assign:
  5616. case BO_MulAssign:
  5617. case BO_DivAssign:
  5618. case BO_RemAssign:
  5619. case BO_AddAssign:
  5620. case BO_SubAssign:
  5621. case BO_ShlAssign:
  5622. case BO_ShrAssign:
  5623. case BO_AndAssign:
  5624. case BO_XorAssign:
  5625. case BO_OrAssign:
  5626. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  5627. // constant expressions, but they can never be ICEs because an ICE cannot
  5628. // contain an lvalue operand.
  5629. return ICEDiag(2, E->getLocStart());
  5630. case BO_Mul:
  5631. case BO_Div:
  5632. case BO_Rem:
  5633. case BO_Add:
  5634. case BO_Sub:
  5635. case BO_Shl:
  5636. case BO_Shr:
  5637. case BO_LT:
  5638. case BO_GT:
  5639. case BO_LE:
  5640. case BO_GE:
  5641. case BO_EQ:
  5642. case BO_NE:
  5643. case BO_And:
  5644. case BO_Xor:
  5645. case BO_Or:
  5646. case BO_Comma: {
  5647. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  5648. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  5649. if (Exp->getOpcode() == BO_Div ||
  5650. Exp->getOpcode() == BO_Rem) {
  5651. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  5652. // we don't evaluate one.
  5653. if (LHSResult.Val == 0 && RHSResult.Val == 0) {
  5654. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  5655. if (REval == 0)
  5656. return ICEDiag(1, E->getLocStart());
  5657. if (REval.isSigned() && REval.isAllOnesValue()) {
  5658. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  5659. if (LEval.isMinSignedValue())
  5660. return ICEDiag(1, E->getLocStart());
  5661. }
  5662. }
  5663. }
  5664. if (Exp->getOpcode() == BO_Comma) {
  5665. if (Ctx.getLangOpts().C99) {
  5666. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  5667. // if it isn't evaluated.
  5668. if (LHSResult.Val == 0 && RHSResult.Val == 0)
  5669. return ICEDiag(1, E->getLocStart());
  5670. } else {
  5671. // In both C89 and C++, commas in ICEs are illegal.
  5672. return ICEDiag(2, E->getLocStart());
  5673. }
  5674. }
  5675. if (LHSResult.Val >= RHSResult.Val)
  5676. return LHSResult;
  5677. return RHSResult;
  5678. }
  5679. case BO_LAnd:
  5680. case BO_LOr: {
  5681. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  5682. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  5683. if (LHSResult.Val == 0 && RHSResult.Val == 1) {
  5684. // Rare case where the RHS has a comma "side-effect"; we need
  5685. // to actually check the condition to see whether the side
  5686. // with the comma is evaluated.
  5687. if ((Exp->getOpcode() == BO_LAnd) !=
  5688. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  5689. return RHSResult;
  5690. return NoDiag();
  5691. }
  5692. if (LHSResult.Val >= RHSResult.Val)
  5693. return LHSResult;
  5694. return RHSResult;
  5695. }
  5696. }
  5697. }
  5698. case Expr::ImplicitCastExprClass:
  5699. case Expr::CStyleCastExprClass:
  5700. case Expr::CXXFunctionalCastExprClass:
  5701. case Expr::CXXStaticCastExprClass:
  5702. case Expr::CXXReinterpretCastExprClass:
  5703. case Expr::CXXConstCastExprClass:
  5704. case Expr::ObjCBridgedCastExprClass: {
  5705. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  5706. if (isa<ExplicitCastExpr>(E)) {
  5707. if (const FloatingLiteral *FL
  5708. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  5709. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  5710. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  5711. APSInt IgnoredVal(DestWidth, !DestSigned);
  5712. bool Ignored;
  5713. // If the value does not fit in the destination type, the behavior is
  5714. // undefined, so we are not required to treat it as a constant
  5715. // expression.
  5716. if (FL->getValue().convertToInteger(IgnoredVal,
  5717. llvm::APFloat::rmTowardZero,
  5718. &Ignored) & APFloat::opInvalidOp)
  5719. return ICEDiag(2, E->getLocStart());
  5720. return NoDiag();
  5721. }
  5722. }
  5723. switch (cast<CastExpr>(E)->getCastKind()) {
  5724. case CK_LValueToRValue:
  5725. case CK_AtomicToNonAtomic:
  5726. case CK_NonAtomicToAtomic:
  5727. case CK_NoOp:
  5728. case CK_IntegralToBoolean:
  5729. case CK_IntegralCast:
  5730. return CheckICE(SubExpr, Ctx);
  5731. default:
  5732. return ICEDiag(2, E->getLocStart());
  5733. }
  5734. }
  5735. case Expr::BinaryConditionalOperatorClass: {
  5736. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  5737. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  5738. if (CommonResult.Val == 2) return CommonResult;
  5739. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  5740. if (FalseResult.Val == 2) return FalseResult;
  5741. if (CommonResult.Val == 1) return CommonResult;
  5742. if (FalseResult.Val == 1 &&
  5743. Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
  5744. return FalseResult;
  5745. }
  5746. case Expr::ConditionalOperatorClass: {
  5747. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  5748. // If the condition (ignoring parens) is a __builtin_constant_p call,
  5749. // then only the true side is actually considered in an integer constant
  5750. // expression, and it is fully evaluated. This is an important GNU
  5751. // extension. See GCC PR38377 for discussion.
  5752. if (const CallExpr *CallCE
  5753. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  5754. if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
  5755. return CheckEvalInICE(E, Ctx);
  5756. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  5757. if (CondResult.Val == 2)
  5758. return CondResult;
  5759. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  5760. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  5761. if (TrueResult.Val == 2)
  5762. return TrueResult;
  5763. if (FalseResult.Val == 2)
  5764. return FalseResult;
  5765. if (CondResult.Val == 1)
  5766. return CondResult;
  5767. if (TrueResult.Val == 0 && FalseResult.Val == 0)
  5768. return NoDiag();
  5769. // Rare case where the diagnostics depend on which side is evaluated
  5770. // Note that if we get here, CondResult is 0, and at least one of
  5771. // TrueResult and FalseResult is non-zero.
  5772. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
  5773. return FalseResult;
  5774. }
  5775. return TrueResult;
  5776. }
  5777. case Expr::CXXDefaultArgExprClass:
  5778. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  5779. case Expr::ChooseExprClass: {
  5780. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
  5781. }
  5782. }
  5783. llvm_unreachable("Invalid StmtClass!");
  5784. }
  5785. /// Evaluate an expression as a C++11 integral constant expression.
  5786. static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
  5787. const Expr *E,
  5788. llvm::APSInt *Value,
  5789. SourceLocation *Loc) {
  5790. if (!E->getType()->isIntegralOrEnumerationType()) {
  5791. if (Loc) *Loc = E->getExprLoc();
  5792. return false;
  5793. }
  5794. APValue Result;
  5795. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  5796. return false;
  5797. assert(Result.isInt() && "pointer cast to int is not an ICE");
  5798. if (Value) *Value = Result.getInt();
  5799. return true;
  5800. }
  5801. bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
  5802. if (Ctx.getLangOpts().CPlusPlus0x)
  5803. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
  5804. ICEDiag d = CheckICE(this, Ctx);
  5805. if (d.Val != 0) {
  5806. if (Loc) *Loc = d.Loc;
  5807. return false;
  5808. }
  5809. return true;
  5810. }
  5811. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
  5812. SourceLocation *Loc, bool isEvaluated) const {
  5813. if (Ctx.getLangOpts().CPlusPlus0x)
  5814. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  5815. if (!isIntegerConstantExpr(Ctx, Loc))
  5816. return false;
  5817. if (!EvaluateAsInt(Value, Ctx))
  5818. llvm_unreachable("ICE cannot be evaluated!");
  5819. return true;
  5820. }
  5821. bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
  5822. return CheckICE(this, Ctx).Val == 0;
  5823. }
  5824. bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
  5825. SourceLocation *Loc) const {
  5826. // We support this checking in C++98 mode in order to diagnose compatibility
  5827. // issues.
  5828. assert(Ctx.getLangOpts().CPlusPlus);
  5829. // Build evaluation settings.
  5830. Expr::EvalStatus Status;
  5831. llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
  5832. Status.Diag = &Diags;
  5833. EvalInfo Info(Ctx, Status);
  5834. APValue Scratch;
  5835. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  5836. if (!Diags.empty()) {
  5837. IsConstExpr = false;
  5838. if (Loc) *Loc = Diags[0].first;
  5839. } else if (!IsConstExpr) {
  5840. // FIXME: This shouldn't happen.
  5841. if (Loc) *Loc = getExprLoc();
  5842. }
  5843. return IsConstExpr;
  5844. }
  5845. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  5846. llvm::SmallVectorImpl<
  5847. PartialDiagnosticAt> &Diags) {
  5848. // FIXME: It would be useful to check constexpr function templates, but at the
  5849. // moment the constant expression evaluator cannot cope with the non-rigorous
  5850. // ASTs which we build for dependent expressions.
  5851. if (FD->isDependentContext())
  5852. return true;
  5853. Expr::EvalStatus Status;
  5854. Status.Diag = &Diags;
  5855. EvalInfo Info(FD->getASTContext(), Status);
  5856. Info.CheckingPotentialConstantExpression = true;
  5857. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5858. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
  5859. // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
  5860. // is a temporary being used as the 'this' pointer.
  5861. LValue This;
  5862. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  5863. This.set(&VIE, Info.CurrentCall->Index);
  5864. ArrayRef<const Expr*> Args;
  5865. SourceLocation Loc = FD->getLocation();
  5866. APValue Scratch;
  5867. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  5868. HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
  5869. else
  5870. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
  5871. Args, FD->getBody(), Info, Scratch);
  5872. return Diags.empty();
  5873. }