ExprConstant.cpp 325 KB

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