ExprConstant.cpp 440 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392
  1. //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr constant evaluator.
  10. //
  11. // Constant expression evaluation produces four main results:
  12. //
  13. // * A success/failure flag indicating whether constant folding was successful.
  14. // This is the 'bool' return value used by most of the code in this file. A
  15. // 'false' return value indicates that constant folding has failed, and any
  16. // appropriate diagnostic has already been produced.
  17. //
  18. // * An evaluated result, valid only if constant folding has not failed.
  19. //
  20. // * A flag indicating if evaluation encountered (unevaluated) side-effects.
  21. // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
  22. // where it is possible to determine the evaluated result regardless.
  23. //
  24. // * A set of notes indicating why the evaluation was not a constant expression
  25. // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
  26. // too, why the expression could not be folded.
  27. //
  28. // If we are checking for a potential constant expression, failure to constant
  29. // fold a potential constant sub-expression will be indicated by a 'false'
  30. // return value (the expression could not be folded) and no diagnostic (the
  31. // expression is not necessarily non-constant).
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include "clang/AST/APValue.h"
  35. #include "clang/AST/ASTContext.h"
  36. #include "clang/AST/ASTDiagnostic.h"
  37. #include "clang/AST/ASTLambda.h"
  38. #include "clang/AST/CharUnits.h"
  39. #include "clang/AST/CXXInheritance.h"
  40. #include "clang/AST/Expr.h"
  41. #include "clang/AST/OSLog.h"
  42. #include "clang/AST/RecordLayout.h"
  43. #include "clang/AST/StmtVisitor.h"
  44. #include "clang/AST/TypeLoc.h"
  45. #include "clang/Basic/Builtins.h"
  46. #include "clang/Basic/FixedPoint.h"
  47. #include "clang/Basic/TargetInfo.h"
  48. #include "llvm/Support/SaveAndRestore.h"
  49. #include "llvm/Support/raw_ostream.h"
  50. #include <cstring>
  51. #include <functional>
  52. #define DEBUG_TYPE "exprconstant"
  53. using namespace clang;
  54. using llvm::APSInt;
  55. using llvm::APFloat;
  56. static bool IsGlobalLValue(APValue::LValueBase B);
  57. namespace {
  58. struct LValue;
  59. struct CallStackFrame;
  60. struct EvalInfo;
  61. static QualType getType(APValue::LValueBase B) {
  62. if (!B) return QualType();
  63. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  64. // FIXME: It's unclear where we're supposed to take the type from, and
  65. // this actually matters for arrays of unknown bound. Eg:
  66. //
  67. // extern int arr[]; void f() { extern int arr[3]; };
  68. // constexpr int *p = &arr[1]; // valid?
  69. //
  70. // For now, we take the array bound from the most recent declaration.
  71. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  72. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  73. QualType T = Redecl->getType();
  74. if (!T->isIncompleteArrayType())
  75. return T;
  76. }
  77. return D->getType();
  78. }
  79. const Expr *Base = B.get<const Expr*>();
  80. // For a materialized temporary, the type of the temporary we materialized
  81. // may not be the type of the expression.
  82. if (const MaterializeTemporaryExpr *MTE =
  83. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  84. SmallVector<const Expr *, 2> CommaLHSs;
  85. SmallVector<SubobjectAdjustment, 2> Adjustments;
  86. const Expr *Temp = MTE->GetTemporaryExpr();
  87. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  88. Adjustments);
  89. // Keep any cv-qualifiers from the reference if we generated a temporary
  90. // for it directly. Otherwise use the type after adjustment.
  91. if (!Adjustments.empty())
  92. return Inner->getType();
  93. }
  94. return Base->getType();
  95. }
  96. /// Get an LValue path entry, which is known to not be an array index, as a
  97. /// field declaration.
  98. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  99. return dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer());
  100. }
  101. /// Get an LValue path entry, which is known to not be an array index, as a
  102. /// base class declaration.
  103. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  104. return dyn_cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  105. }
  106. /// Determine whether this LValue path entry for a base class names a virtual
  107. /// base class.
  108. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  109. return E.getAsBaseOrMember().getInt();
  110. }
  111. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  112. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  113. const FunctionDecl *Callee = CE->getDirectCallee();
  114. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  115. }
  116. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  117. /// This will look through a single cast.
  118. ///
  119. /// Returns null if we couldn't unwrap a function with alloc_size.
  120. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  121. if (!E->getType()->isPointerType())
  122. return nullptr;
  123. E = E->IgnoreParens();
  124. // If we're doing a variable assignment from e.g. malloc(N), there will
  125. // probably be a cast of some kind. In exotic cases, we might also see a
  126. // top-level ExprWithCleanups. Ignore them either way.
  127. if (const auto *FE = dyn_cast<FullExpr>(E))
  128. E = FE->getSubExpr()->IgnoreParens();
  129. if (const auto *Cast = dyn_cast<CastExpr>(E))
  130. E = Cast->getSubExpr()->IgnoreParens();
  131. if (const auto *CE = dyn_cast<CallExpr>(E))
  132. return getAllocSizeAttr(CE) ? CE : nullptr;
  133. return nullptr;
  134. }
  135. /// Determines whether or not the given Base contains a call to a function
  136. /// with the alloc_size attribute.
  137. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  138. const auto *E = Base.dyn_cast<const Expr *>();
  139. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  140. }
  141. /// The bound to claim that an array of unknown bound has.
  142. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  143. /// to an arbitrary value that's likely to loudly break things if it's used.
  144. static const uint64_t AssumedSizeForUnsizedArray =
  145. std::numeric_limits<uint64_t>::max() / 2;
  146. /// Determines if an LValue with the given LValueBase will have an unsized
  147. /// array in its designator.
  148. /// Find the path length and type of the most-derived subobject in the given
  149. /// path, and find the size of the containing array, if any.
  150. static unsigned
  151. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  152. ArrayRef<APValue::LValuePathEntry> Path,
  153. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  154. bool &FirstEntryIsUnsizedArray) {
  155. // This only accepts LValueBases from APValues, and APValues don't support
  156. // arrays that lack size info.
  157. assert(!isBaseAnAllocSizeCall(Base) &&
  158. "Unsized arrays shouldn't appear here");
  159. unsigned MostDerivedLength = 0;
  160. Type = getType(Base);
  161. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  162. if (Type->isArrayType()) {
  163. const ArrayType *AT = Ctx.getAsArrayType(Type);
  164. Type = AT->getElementType();
  165. MostDerivedLength = I + 1;
  166. IsArray = true;
  167. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  168. ArraySize = CAT->getSize().getZExtValue();
  169. } else {
  170. assert(I == 0 && "unexpected unsized array designator");
  171. FirstEntryIsUnsizedArray = true;
  172. ArraySize = AssumedSizeForUnsizedArray;
  173. }
  174. } else if (Type->isAnyComplexType()) {
  175. const ComplexType *CT = Type->castAs<ComplexType>();
  176. Type = CT->getElementType();
  177. ArraySize = 2;
  178. MostDerivedLength = I + 1;
  179. IsArray = true;
  180. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  181. Type = FD->getType();
  182. ArraySize = 0;
  183. MostDerivedLength = I + 1;
  184. IsArray = false;
  185. } else {
  186. // Path[I] describes a base class.
  187. ArraySize = 0;
  188. IsArray = false;
  189. }
  190. }
  191. return MostDerivedLength;
  192. }
  193. // The order of this enum is important for diagnostics.
  194. enum CheckSubobjectKind {
  195. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  196. CSK_Real, CSK_Imag
  197. };
  198. /// A path from a glvalue to a subobject of that glvalue.
  199. struct SubobjectDesignator {
  200. /// True if the subobject was named in a manner not supported by C++11. Such
  201. /// lvalues can still be folded, but they are not core constant expressions
  202. /// and we cannot perform lvalue-to-rvalue conversions on them.
  203. unsigned Invalid : 1;
  204. /// Is this a pointer one past the end of an object?
  205. unsigned IsOnePastTheEnd : 1;
  206. /// Indicator of whether the first entry is an unsized array.
  207. unsigned FirstEntryIsAnUnsizedArray : 1;
  208. /// Indicator of whether the most-derived object is an array element.
  209. unsigned MostDerivedIsArrayElement : 1;
  210. /// The length of the path to the most-derived object of which this is a
  211. /// subobject.
  212. unsigned MostDerivedPathLength : 28;
  213. /// The size of the array of which the most-derived object is an element.
  214. /// This will always be 0 if the most-derived object is not an array
  215. /// element. 0 is not an indicator of whether or not the most-derived object
  216. /// is an array, however, because 0-length arrays are allowed.
  217. ///
  218. /// If the current array is an unsized array, the value of this is
  219. /// undefined.
  220. uint64_t MostDerivedArraySize;
  221. /// The type of the most derived object referred to by this address.
  222. QualType MostDerivedType;
  223. typedef APValue::LValuePathEntry PathEntry;
  224. /// The entries on the path from the glvalue to the designated subobject.
  225. SmallVector<PathEntry, 8> Entries;
  226. SubobjectDesignator() : Invalid(true) {}
  227. explicit SubobjectDesignator(QualType T)
  228. : Invalid(false), IsOnePastTheEnd(false),
  229. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  230. MostDerivedPathLength(0), MostDerivedArraySize(0),
  231. MostDerivedType(T) {}
  232. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  233. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  234. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  235. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  236. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  237. if (!Invalid) {
  238. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  239. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  240. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  241. if (V.getLValueBase()) {
  242. bool IsArray = false;
  243. bool FirstIsUnsizedArray = false;
  244. MostDerivedPathLength = findMostDerivedSubobject(
  245. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  246. MostDerivedType, IsArray, FirstIsUnsizedArray);
  247. MostDerivedIsArrayElement = IsArray;
  248. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  249. }
  250. }
  251. }
  252. void setInvalid() {
  253. Invalid = true;
  254. Entries.clear();
  255. }
  256. /// Determine whether the most derived subobject is an array without a
  257. /// known bound.
  258. bool isMostDerivedAnUnsizedArray() const {
  259. assert(!Invalid && "Calling this makes no sense on invalid designators");
  260. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  261. }
  262. /// Determine what the most derived array's size is. Results in an assertion
  263. /// failure if the most derived array lacks a size.
  264. uint64_t getMostDerivedArraySize() const {
  265. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  266. return MostDerivedArraySize;
  267. }
  268. /// Determine whether this is a one-past-the-end pointer.
  269. bool isOnePastTheEnd() const {
  270. assert(!Invalid);
  271. if (IsOnePastTheEnd)
  272. return true;
  273. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  274. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  275. MostDerivedArraySize)
  276. return true;
  277. return false;
  278. }
  279. /// Get the range of valid index adjustments in the form
  280. /// {maximum value that can be subtracted from this pointer,
  281. /// maximum value that can be added to this pointer}
  282. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  283. if (Invalid || isMostDerivedAnUnsizedArray())
  284. return {0, 0};
  285. // [expr.add]p4: For the purposes of these operators, a pointer to a
  286. // nonarray object behaves the same as a pointer to the first element of
  287. // an array of length one with the type of the object as its element type.
  288. bool IsArray = MostDerivedPathLength == Entries.size() &&
  289. MostDerivedIsArrayElement;
  290. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  291. : (uint64_t)IsOnePastTheEnd;
  292. uint64_t ArraySize =
  293. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  294. return {ArrayIndex, ArraySize - ArrayIndex};
  295. }
  296. /// Check that this refers to a valid subobject.
  297. bool isValidSubobject() const {
  298. if (Invalid)
  299. return false;
  300. return !isOnePastTheEnd();
  301. }
  302. /// Check that this refers to a valid subobject, and if not, produce a
  303. /// relevant diagnostic and set the designator as invalid.
  304. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  305. /// Get the type of the designated object.
  306. QualType getType(ASTContext &Ctx) const {
  307. assert(!Invalid && "invalid designator has no subobject type");
  308. return MostDerivedPathLength == Entries.size()
  309. ? MostDerivedType
  310. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  311. }
  312. /// Update this designator to refer to the first element within this array.
  313. void addArrayUnchecked(const ConstantArrayType *CAT) {
  314. Entries.push_back(PathEntry::ArrayIndex(0));
  315. // This is a most-derived object.
  316. MostDerivedType = CAT->getElementType();
  317. MostDerivedIsArrayElement = true;
  318. MostDerivedArraySize = CAT->getSize().getZExtValue();
  319. MostDerivedPathLength = Entries.size();
  320. }
  321. /// Update this designator to refer to the first element within the array of
  322. /// elements of type T. This is an array of unknown size.
  323. void addUnsizedArrayUnchecked(QualType ElemTy) {
  324. Entries.push_back(PathEntry::ArrayIndex(0));
  325. MostDerivedType = ElemTy;
  326. MostDerivedIsArrayElement = true;
  327. // The value in MostDerivedArraySize is undefined in this case. So, set it
  328. // to an arbitrary value that's likely to loudly break things if it's
  329. // used.
  330. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  331. MostDerivedPathLength = Entries.size();
  332. }
  333. /// Update this designator to refer to the given base or member of this
  334. /// object.
  335. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  336. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  337. // If this isn't a base class, it's a new most-derived object.
  338. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  339. MostDerivedType = FD->getType();
  340. MostDerivedIsArrayElement = false;
  341. MostDerivedArraySize = 0;
  342. MostDerivedPathLength = Entries.size();
  343. }
  344. }
  345. /// Update this designator to refer to the given complex component.
  346. void addComplexUnchecked(QualType EltTy, bool Imag) {
  347. Entries.push_back(PathEntry::ArrayIndex(Imag));
  348. // This is technically a most-derived object, though in practice this
  349. // is unlikely to matter.
  350. MostDerivedType = EltTy;
  351. MostDerivedIsArrayElement = true;
  352. MostDerivedArraySize = 2;
  353. MostDerivedPathLength = Entries.size();
  354. }
  355. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  356. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  357. const APSInt &N);
  358. /// Add N to the address of this subobject.
  359. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  360. if (Invalid || !N) return;
  361. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  362. if (isMostDerivedAnUnsizedArray()) {
  363. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  364. // Can't verify -- trust that the user is doing the right thing (or if
  365. // not, trust that the caller will catch the bad behavior).
  366. // FIXME: Should we reject if this overflows, at least?
  367. Entries.back() = PathEntry::ArrayIndex(
  368. Entries.back().getAsArrayIndex() + TruncatedN);
  369. return;
  370. }
  371. // [expr.add]p4: For the purposes of these operators, a pointer to a
  372. // nonarray object behaves the same as a pointer to the first element of
  373. // an array of length one with the type of the object as its element type.
  374. bool IsArray = MostDerivedPathLength == Entries.size() &&
  375. MostDerivedIsArrayElement;
  376. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  377. : (uint64_t)IsOnePastTheEnd;
  378. uint64_t ArraySize =
  379. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  380. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  381. // Calculate the actual index in a wide enough type, so we can include
  382. // it in the note.
  383. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  384. (llvm::APInt&)N += ArrayIndex;
  385. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  386. diagnosePointerArithmetic(Info, E, N);
  387. setInvalid();
  388. return;
  389. }
  390. ArrayIndex += TruncatedN;
  391. assert(ArrayIndex <= ArraySize &&
  392. "bounds check succeeded for out-of-bounds index");
  393. if (IsArray)
  394. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  395. else
  396. IsOnePastTheEnd = (ArrayIndex != 0);
  397. }
  398. };
  399. /// A stack frame in the constexpr call stack.
  400. struct CallStackFrame {
  401. EvalInfo &Info;
  402. /// Parent - The caller of this stack frame.
  403. CallStackFrame *Caller;
  404. /// Callee - The function which was called.
  405. const FunctionDecl *Callee;
  406. /// This - The binding for the this pointer in this call, if any.
  407. const LValue *This;
  408. /// Arguments - Parameter bindings for this function call, indexed by
  409. /// parameters' function scope indices.
  410. APValue *Arguments;
  411. // Note that we intentionally use std::map here so that references to
  412. // values are stable.
  413. typedef std::pair<const void *, unsigned> MapKeyTy;
  414. typedef std::map<MapKeyTy, APValue> MapTy;
  415. /// Temporaries - Temporary lvalues materialized within this stack frame.
  416. MapTy Temporaries;
  417. /// CallLoc - The location of the call expression for this call.
  418. SourceLocation CallLoc;
  419. /// Index - The call index of this call.
  420. unsigned Index;
  421. /// The stack of integers for tracking version numbers for temporaries.
  422. SmallVector<unsigned, 2> TempVersionStack = {1};
  423. unsigned CurTempVersion = TempVersionStack.back();
  424. unsigned getTempVersion() const { return TempVersionStack.back(); }
  425. void pushTempVersion() {
  426. TempVersionStack.push_back(++CurTempVersion);
  427. }
  428. void popTempVersion() {
  429. TempVersionStack.pop_back();
  430. }
  431. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  432. // on the overall stack usage of deeply-recursing constexpr evaluations.
  433. // (We should cache this map rather than recomputing it repeatedly.)
  434. // But let's try this and see how it goes; we can look into caching the map
  435. // as a later change.
  436. /// LambdaCaptureFields - Mapping from captured variables/this to
  437. /// corresponding data members in the closure class.
  438. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  439. FieldDecl *LambdaThisCaptureField;
  440. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  441. const FunctionDecl *Callee, const LValue *This,
  442. APValue *Arguments);
  443. ~CallStackFrame();
  444. // Return the temporary for Key whose version number is Version.
  445. APValue *getTemporary(const void *Key, unsigned Version) {
  446. MapKeyTy KV(Key, Version);
  447. auto LB = Temporaries.lower_bound(KV);
  448. if (LB != Temporaries.end() && LB->first == KV)
  449. return &LB->second;
  450. // Pair (Key,Version) wasn't found in the map. Check that no elements
  451. // in the map have 'Key' as their key.
  452. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  453. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  454. "Element with key 'Key' found in map");
  455. return nullptr;
  456. }
  457. // Return the current temporary for Key in the map.
  458. APValue *getCurrentTemporary(const void *Key) {
  459. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  460. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  461. return &std::prev(UB)->second;
  462. return nullptr;
  463. }
  464. // Return the version number of the current temporary for Key.
  465. unsigned getCurrentTemporaryVersion(const void *Key) const {
  466. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  467. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  468. return std::prev(UB)->first.second;
  469. return 0;
  470. }
  471. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  472. };
  473. /// Temporarily override 'this'.
  474. class ThisOverrideRAII {
  475. public:
  476. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  477. : Frame(Frame), OldThis(Frame.This) {
  478. if (Enable)
  479. Frame.This = NewThis;
  480. }
  481. ~ThisOverrideRAII() {
  482. Frame.This = OldThis;
  483. }
  484. private:
  485. CallStackFrame &Frame;
  486. const LValue *OldThis;
  487. };
  488. /// A partial diagnostic which we might know in advance that we are not going
  489. /// to emit.
  490. class OptionalDiagnostic {
  491. PartialDiagnostic *Diag;
  492. public:
  493. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  494. : Diag(Diag) {}
  495. template<typename T>
  496. OptionalDiagnostic &operator<<(const T &v) {
  497. if (Diag)
  498. *Diag << v;
  499. return *this;
  500. }
  501. OptionalDiagnostic &operator<<(const APSInt &I) {
  502. if (Diag) {
  503. SmallVector<char, 32> Buffer;
  504. I.toString(Buffer);
  505. *Diag << StringRef(Buffer.data(), Buffer.size());
  506. }
  507. return *this;
  508. }
  509. OptionalDiagnostic &operator<<(const APFloat &F) {
  510. if (Diag) {
  511. // FIXME: Force the precision of the source value down so we don't
  512. // print digits which are usually useless (we don't really care here if
  513. // we truncate a digit by accident in edge cases). Ideally,
  514. // APFloat::toString would automatically print the shortest
  515. // representation which rounds to the correct value, but it's a bit
  516. // tricky to implement.
  517. unsigned precision =
  518. llvm::APFloat::semanticsPrecision(F.getSemantics());
  519. precision = (precision * 59 + 195) / 196;
  520. SmallVector<char, 32> Buffer;
  521. F.toString(Buffer, precision);
  522. *Diag << StringRef(Buffer.data(), Buffer.size());
  523. }
  524. return *this;
  525. }
  526. OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
  527. if (Diag) {
  528. SmallVector<char, 32> Buffer;
  529. FX.toString(Buffer);
  530. *Diag << StringRef(Buffer.data(), Buffer.size());
  531. }
  532. return *this;
  533. }
  534. };
  535. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  536. class Cleanup {
  537. llvm::PointerIntPair<APValue*, 1, bool> Value;
  538. public:
  539. Cleanup(APValue *Val, bool IsLifetimeExtended)
  540. : Value(Val, IsLifetimeExtended) {}
  541. bool isLifetimeExtended() const { return Value.getInt(); }
  542. void endLifetime() {
  543. *Value.getPointer() = APValue();
  544. }
  545. };
  546. /// A reference to an object whose construction we are currently evaluating.
  547. struct ObjectUnderConstruction {
  548. APValue::LValueBase Base;
  549. ArrayRef<APValue::LValuePathEntry> Path;
  550. friend bool operator==(const ObjectUnderConstruction &LHS,
  551. const ObjectUnderConstruction &RHS) {
  552. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  553. }
  554. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  555. return llvm::hash_combine(Obj.Base, Obj.Path);
  556. }
  557. };
  558. enum class ConstructionPhase { None, Bases, AfterBases };
  559. }
  560. namespace llvm {
  561. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  562. using Base = DenseMapInfo<APValue::LValueBase>;
  563. static ObjectUnderConstruction getEmptyKey() {
  564. return {Base::getEmptyKey(), {}}; }
  565. static ObjectUnderConstruction getTombstoneKey() {
  566. return {Base::getTombstoneKey(), {}};
  567. }
  568. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  569. return hash_value(Object);
  570. }
  571. static bool isEqual(const ObjectUnderConstruction &LHS,
  572. const ObjectUnderConstruction &RHS) {
  573. return LHS == RHS;
  574. }
  575. };
  576. }
  577. namespace {
  578. /// EvalInfo - This is a private struct used by the evaluator to capture
  579. /// information about a subexpression as it is folded. It retains information
  580. /// about the AST context, but also maintains information about the folded
  581. /// expression.
  582. ///
  583. /// If an expression could be evaluated, it is still possible it is not a C
  584. /// "integer constant expression" or constant expression. If not, this struct
  585. /// captures information about how and why not.
  586. ///
  587. /// One bit of information passed *into* the request for constant folding
  588. /// indicates whether the subexpression is "evaluated" or not according to C
  589. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  590. /// evaluate the expression regardless of what the RHS is, but C only allows
  591. /// certain things in certain situations.
  592. struct EvalInfo {
  593. ASTContext &Ctx;
  594. /// EvalStatus - Contains information about the evaluation.
  595. Expr::EvalStatus &EvalStatus;
  596. /// CurrentCall - The top of the constexpr call stack.
  597. CallStackFrame *CurrentCall;
  598. /// CallStackDepth - The number of calls in the call stack right now.
  599. unsigned CallStackDepth;
  600. /// NextCallIndex - The next call index to assign.
  601. unsigned NextCallIndex;
  602. /// StepsLeft - The remaining number of evaluation steps we're permitted
  603. /// to perform. This is essentially a limit for the number of statements
  604. /// we will evaluate.
  605. unsigned StepsLeft;
  606. /// BottomFrame - The frame in which evaluation started. This must be
  607. /// initialized after CurrentCall and CallStackDepth.
  608. CallStackFrame BottomFrame;
  609. /// A stack of values whose lifetimes end at the end of some surrounding
  610. /// evaluation frame.
  611. llvm::SmallVector<Cleanup, 16> CleanupStack;
  612. /// EvaluatingDecl - This is the declaration whose initializer is being
  613. /// evaluated, if any.
  614. APValue::LValueBase EvaluatingDecl;
  615. /// EvaluatingDeclValue - This is the value being constructed for the
  616. /// declaration whose initializer is being evaluated, if any.
  617. APValue *EvaluatingDeclValue;
  618. /// Set of objects that are currently being constructed.
  619. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  620. ObjectsUnderConstruction;
  621. struct EvaluatingConstructorRAII {
  622. EvalInfo &EI;
  623. ObjectUnderConstruction Object;
  624. bool DidInsert;
  625. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  626. bool HasBases)
  627. : EI(EI), Object(Object) {
  628. DidInsert =
  629. EI.ObjectsUnderConstruction
  630. .insert({Object, HasBases ? ConstructionPhase::Bases
  631. : ConstructionPhase::AfterBases})
  632. .second;
  633. }
  634. void finishedConstructingBases() {
  635. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  636. }
  637. ~EvaluatingConstructorRAII() {
  638. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  639. }
  640. };
  641. ConstructionPhase
  642. isEvaluatingConstructor(APValue::LValueBase Base,
  643. ArrayRef<APValue::LValuePathEntry> Path) {
  644. return ObjectsUnderConstruction.lookup({Base, Path});
  645. }
  646. /// If we're currently speculatively evaluating, the outermost call stack
  647. /// depth at which we can mutate state, otherwise 0.
  648. unsigned SpeculativeEvaluationDepth = 0;
  649. /// The current array initialization index, if we're performing array
  650. /// initialization.
  651. uint64_t ArrayInitIndex = -1;
  652. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  653. /// notes attached to it will also be stored, otherwise they will not be.
  654. bool HasActiveDiagnostic;
  655. /// Have we emitted a diagnostic explaining why we couldn't constant
  656. /// fold (not just why it's not strictly a constant expression)?
  657. bool HasFoldFailureDiagnostic;
  658. /// Whether or not we're in a context where the front end requires a
  659. /// constant value.
  660. bool InConstantContext;
  661. enum EvaluationMode {
  662. /// Evaluate as a constant expression. Stop if we find that the expression
  663. /// is not a constant expression.
  664. EM_ConstantExpression,
  665. /// Evaluate as a potential constant expression. Keep going if we hit a
  666. /// construct that we can't evaluate yet (because we don't yet know the
  667. /// value of something) but stop if we hit something that could never be
  668. /// a constant expression.
  669. EM_PotentialConstantExpression,
  670. /// Fold the expression to a constant. Stop if we hit a side-effect that
  671. /// we can't model.
  672. EM_ConstantFold,
  673. /// Evaluate the expression looking for integer overflow and similar
  674. /// issues. Don't worry about side-effects, and try to visit all
  675. /// subexpressions.
  676. EM_EvaluateForOverflow,
  677. /// Evaluate in any way we know how. Don't worry about side-effects that
  678. /// can't be modeled.
  679. EM_IgnoreSideEffects,
  680. /// Evaluate as a constant expression. Stop if we find that the expression
  681. /// is not a constant expression. Some expressions can be retried in the
  682. /// optimizer if we don't constant fold them here, but in an unevaluated
  683. /// context we try to fold them immediately since the optimizer never
  684. /// gets a chance to look at it.
  685. EM_ConstantExpressionUnevaluated,
  686. /// Evaluate as a potential constant expression. Keep going if we hit a
  687. /// construct that we can't evaluate yet (because we don't yet know the
  688. /// value of something) but stop if we hit something that could never be
  689. /// a constant expression. Some expressions can be retried in the
  690. /// optimizer if we don't constant fold them here, but in an unevaluated
  691. /// context we try to fold them immediately since the optimizer never
  692. /// gets a chance to look at it.
  693. EM_PotentialConstantExpressionUnevaluated,
  694. } EvalMode;
  695. /// Are we checking whether the expression is a potential constant
  696. /// expression?
  697. bool checkingPotentialConstantExpression() const {
  698. return EvalMode == EM_PotentialConstantExpression ||
  699. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  700. }
  701. /// Are we checking an expression for overflow?
  702. // FIXME: We should check for any kind of undefined or suspicious behavior
  703. // in such constructs, not just overflow.
  704. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  705. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  706. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  707. CallStackDepth(0), NextCallIndex(1),
  708. StepsLeft(getLangOpts().ConstexprStepLimit),
  709. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  710. EvaluatingDecl((const ValueDecl *)nullptr),
  711. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  712. HasFoldFailureDiagnostic(false),
  713. InConstantContext(false), EvalMode(Mode) {}
  714. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  715. EvaluatingDecl = Base;
  716. EvaluatingDeclValue = &Value;
  717. }
  718. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  719. bool CheckCallLimit(SourceLocation Loc) {
  720. // Don't perform any constexpr calls (other than the call we're checking)
  721. // when checking a potential constant expression.
  722. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  723. return false;
  724. if (NextCallIndex == 0) {
  725. // NextCallIndex has wrapped around.
  726. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  727. return false;
  728. }
  729. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  730. return true;
  731. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  732. << getLangOpts().ConstexprCallDepth;
  733. return false;
  734. }
  735. std::pair<CallStackFrame *, unsigned>
  736. getCallFrameAndDepth(unsigned CallIndex) {
  737. assert(CallIndex && "no call index in getCallFrameAndDepth");
  738. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  739. // be null in this loop.
  740. unsigned Depth = CallStackDepth;
  741. CallStackFrame *Frame = CurrentCall;
  742. while (Frame->Index > CallIndex) {
  743. Frame = Frame->Caller;
  744. --Depth;
  745. }
  746. if (Frame->Index == CallIndex)
  747. return {Frame, Depth};
  748. return {nullptr, 0};
  749. }
  750. bool nextStep(const Stmt *S) {
  751. if (!StepsLeft) {
  752. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  753. return false;
  754. }
  755. --StepsLeft;
  756. return true;
  757. }
  758. private:
  759. /// Add a diagnostic to the diagnostics list.
  760. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  761. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  762. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  763. return EvalStatus.Diag->back().second;
  764. }
  765. /// Add notes containing a call stack to the current point of evaluation.
  766. void addCallStack(unsigned Limit);
  767. private:
  768. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  769. unsigned ExtraNotes, bool IsCCEDiag) {
  770. if (EvalStatus.Diag) {
  771. // If we have a prior diagnostic, it will be noting that the expression
  772. // isn't a constant expression. This diagnostic is more important,
  773. // unless we require this evaluation to produce a constant expression.
  774. //
  775. // FIXME: We might want to show both diagnostics to the user in
  776. // EM_ConstantFold mode.
  777. if (!EvalStatus.Diag->empty()) {
  778. switch (EvalMode) {
  779. case EM_ConstantFold:
  780. case EM_IgnoreSideEffects:
  781. case EM_EvaluateForOverflow:
  782. if (!HasFoldFailureDiagnostic)
  783. break;
  784. // We've already failed to fold something. Keep that diagnostic.
  785. LLVM_FALLTHROUGH;
  786. case EM_ConstantExpression:
  787. case EM_PotentialConstantExpression:
  788. case EM_ConstantExpressionUnevaluated:
  789. case EM_PotentialConstantExpressionUnevaluated:
  790. HasActiveDiagnostic = false;
  791. return OptionalDiagnostic();
  792. }
  793. }
  794. unsigned CallStackNotes = CallStackDepth - 1;
  795. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  796. if (Limit)
  797. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  798. if (checkingPotentialConstantExpression())
  799. CallStackNotes = 0;
  800. HasActiveDiagnostic = true;
  801. HasFoldFailureDiagnostic = !IsCCEDiag;
  802. EvalStatus.Diag->clear();
  803. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  804. addDiag(Loc, DiagId);
  805. if (!checkingPotentialConstantExpression())
  806. addCallStack(Limit);
  807. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  808. }
  809. HasActiveDiagnostic = false;
  810. return OptionalDiagnostic();
  811. }
  812. public:
  813. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  814. OptionalDiagnostic
  815. FFDiag(SourceLocation Loc,
  816. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  817. unsigned ExtraNotes = 0) {
  818. return Diag(Loc, DiagId, ExtraNotes, false);
  819. }
  820. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  821. = diag::note_invalid_subexpr_in_const_expr,
  822. unsigned ExtraNotes = 0) {
  823. if (EvalStatus.Diag)
  824. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  825. HasActiveDiagnostic = false;
  826. return OptionalDiagnostic();
  827. }
  828. /// Diagnose that the evaluation does not produce a C++11 core constant
  829. /// expression.
  830. ///
  831. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  832. /// EM_PotentialConstantExpression mode and we produce one of these.
  833. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  834. = diag::note_invalid_subexpr_in_const_expr,
  835. unsigned ExtraNotes = 0) {
  836. // Don't override a previous diagnostic. Don't bother collecting
  837. // diagnostics if we're evaluating for overflow.
  838. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  839. HasActiveDiagnostic = false;
  840. return OptionalDiagnostic();
  841. }
  842. return Diag(Loc, DiagId, ExtraNotes, true);
  843. }
  844. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  845. = diag::note_invalid_subexpr_in_const_expr,
  846. unsigned ExtraNotes = 0) {
  847. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  848. }
  849. /// Add a note to a prior diagnostic.
  850. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  851. if (!HasActiveDiagnostic)
  852. return OptionalDiagnostic();
  853. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  854. }
  855. /// Add a stack of notes to a prior diagnostic.
  856. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  857. if (HasActiveDiagnostic) {
  858. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  859. Diags.begin(), Diags.end());
  860. }
  861. }
  862. /// Should we continue evaluation after encountering a side-effect that we
  863. /// couldn't model?
  864. bool keepEvaluatingAfterSideEffect() {
  865. switch (EvalMode) {
  866. case EM_PotentialConstantExpression:
  867. case EM_PotentialConstantExpressionUnevaluated:
  868. case EM_EvaluateForOverflow:
  869. case EM_IgnoreSideEffects:
  870. return true;
  871. case EM_ConstantExpression:
  872. case EM_ConstantExpressionUnevaluated:
  873. case EM_ConstantFold:
  874. return false;
  875. }
  876. llvm_unreachable("Missed EvalMode case");
  877. }
  878. /// Note that we have had a side-effect, and determine whether we should
  879. /// keep evaluating.
  880. bool noteSideEffect() {
  881. EvalStatus.HasSideEffects = true;
  882. return keepEvaluatingAfterSideEffect();
  883. }
  884. /// Should we continue evaluation after encountering undefined behavior?
  885. bool keepEvaluatingAfterUndefinedBehavior() {
  886. switch (EvalMode) {
  887. case EM_EvaluateForOverflow:
  888. case EM_IgnoreSideEffects:
  889. case EM_ConstantFold:
  890. return true;
  891. case EM_PotentialConstantExpression:
  892. case EM_PotentialConstantExpressionUnevaluated:
  893. case EM_ConstantExpression:
  894. case EM_ConstantExpressionUnevaluated:
  895. return false;
  896. }
  897. llvm_unreachable("Missed EvalMode case");
  898. }
  899. /// Note that we hit something that was technically undefined behavior, but
  900. /// that we can evaluate past it (such as signed overflow or floating-point
  901. /// division by zero.)
  902. bool noteUndefinedBehavior() {
  903. EvalStatus.HasUndefinedBehavior = true;
  904. return keepEvaluatingAfterUndefinedBehavior();
  905. }
  906. /// Should we continue evaluation as much as possible after encountering a
  907. /// construct which can't be reduced to a value?
  908. bool keepEvaluatingAfterFailure() {
  909. if (!StepsLeft)
  910. return false;
  911. switch (EvalMode) {
  912. case EM_PotentialConstantExpression:
  913. case EM_PotentialConstantExpressionUnevaluated:
  914. case EM_EvaluateForOverflow:
  915. return true;
  916. case EM_ConstantExpression:
  917. case EM_ConstantExpressionUnevaluated:
  918. case EM_ConstantFold:
  919. case EM_IgnoreSideEffects:
  920. return false;
  921. }
  922. llvm_unreachable("Missed EvalMode case");
  923. }
  924. /// Notes that we failed to evaluate an expression that other expressions
  925. /// directly depend on, and determine if we should keep evaluating. This
  926. /// should only be called if we actually intend to keep evaluating.
  927. ///
  928. /// Call noteSideEffect() instead if we may be able to ignore the value that
  929. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  930. ///
  931. /// (Foo(), 1) // use noteSideEffect
  932. /// (Foo() || true) // use noteSideEffect
  933. /// Foo() + 1 // use noteFailure
  934. LLVM_NODISCARD bool noteFailure() {
  935. // Failure when evaluating some expression often means there is some
  936. // subexpression whose evaluation was skipped. Therefore, (because we
  937. // don't track whether we skipped an expression when unwinding after an
  938. // evaluation failure) every evaluation failure that bubbles up from a
  939. // subexpression implies that a side-effect has potentially happened. We
  940. // skip setting the HasSideEffects flag to true until we decide to
  941. // continue evaluating after that point, which happens here.
  942. bool KeepGoing = keepEvaluatingAfterFailure();
  943. EvalStatus.HasSideEffects |= KeepGoing;
  944. return KeepGoing;
  945. }
  946. class ArrayInitLoopIndex {
  947. EvalInfo &Info;
  948. uint64_t OuterIndex;
  949. public:
  950. ArrayInitLoopIndex(EvalInfo &Info)
  951. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  952. Info.ArrayInitIndex = 0;
  953. }
  954. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  955. operator uint64_t&() { return Info.ArrayInitIndex; }
  956. };
  957. };
  958. /// Object used to treat all foldable expressions as constant expressions.
  959. struct FoldConstant {
  960. EvalInfo &Info;
  961. bool Enabled;
  962. bool HadNoPriorDiags;
  963. EvalInfo::EvaluationMode OldMode;
  964. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  965. : Info(Info),
  966. Enabled(Enabled),
  967. HadNoPriorDiags(Info.EvalStatus.Diag &&
  968. Info.EvalStatus.Diag->empty() &&
  969. !Info.EvalStatus.HasSideEffects),
  970. OldMode(Info.EvalMode) {
  971. if (Enabled &&
  972. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  973. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  974. Info.EvalMode = EvalInfo::EM_ConstantFold;
  975. }
  976. void keepDiagnostics() { Enabled = false; }
  977. ~FoldConstant() {
  978. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  979. !Info.EvalStatus.HasSideEffects)
  980. Info.EvalStatus.Diag->clear();
  981. Info.EvalMode = OldMode;
  982. }
  983. };
  984. /// RAII object used to set the current evaluation mode to ignore
  985. /// side-effects.
  986. struct IgnoreSideEffectsRAII {
  987. EvalInfo &Info;
  988. EvalInfo::EvaluationMode OldMode;
  989. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  990. : Info(Info), OldMode(Info.EvalMode) {
  991. if (!Info.checkingPotentialConstantExpression())
  992. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  993. }
  994. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  995. };
  996. /// RAII object used to optionally suppress diagnostics and side-effects from
  997. /// a speculative evaluation.
  998. class SpeculativeEvaluationRAII {
  999. EvalInfo *Info = nullptr;
  1000. Expr::EvalStatus OldStatus;
  1001. unsigned OldSpeculativeEvaluationDepth;
  1002. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1003. Info = Other.Info;
  1004. OldStatus = Other.OldStatus;
  1005. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1006. Other.Info = nullptr;
  1007. }
  1008. void maybeRestoreState() {
  1009. if (!Info)
  1010. return;
  1011. Info->EvalStatus = OldStatus;
  1012. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1013. }
  1014. public:
  1015. SpeculativeEvaluationRAII() = default;
  1016. SpeculativeEvaluationRAII(
  1017. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1018. : Info(&Info), OldStatus(Info.EvalStatus),
  1019. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1020. Info.EvalStatus.Diag = NewDiag;
  1021. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1022. }
  1023. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1024. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1025. moveFromAndCancel(std::move(Other));
  1026. }
  1027. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1028. maybeRestoreState();
  1029. moveFromAndCancel(std::move(Other));
  1030. return *this;
  1031. }
  1032. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1033. };
  1034. /// RAII object wrapping a full-expression or block scope, and handling
  1035. /// the ending of the lifetime of temporaries created within it.
  1036. template<bool IsFullExpression>
  1037. class ScopeRAII {
  1038. EvalInfo &Info;
  1039. unsigned OldStackSize;
  1040. public:
  1041. ScopeRAII(EvalInfo &Info)
  1042. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1043. // Push a new temporary version. This is needed to distinguish between
  1044. // temporaries created in different iterations of a loop.
  1045. Info.CurrentCall->pushTempVersion();
  1046. }
  1047. ~ScopeRAII() {
  1048. // Body moved to a static method to encourage the compiler to inline away
  1049. // instances of this class.
  1050. cleanup(Info, OldStackSize);
  1051. Info.CurrentCall->popTempVersion();
  1052. }
  1053. private:
  1054. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1055. unsigned NewEnd = OldStackSize;
  1056. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1057. I != N; ++I) {
  1058. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1059. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1060. // to do, just move this cleanup to the right place in the stack.
  1061. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1062. ++NewEnd;
  1063. } else {
  1064. // End the lifetime of the object.
  1065. Info.CleanupStack[I].endLifetime();
  1066. }
  1067. }
  1068. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1069. Info.CleanupStack.end());
  1070. }
  1071. };
  1072. typedef ScopeRAII<false> BlockScopeRAII;
  1073. typedef ScopeRAII<true> FullExpressionRAII;
  1074. }
  1075. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1076. CheckSubobjectKind CSK) {
  1077. if (Invalid)
  1078. return false;
  1079. if (isOnePastTheEnd()) {
  1080. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1081. << CSK;
  1082. setInvalid();
  1083. return false;
  1084. }
  1085. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1086. // must actually be at least one array element; even a VLA cannot have a
  1087. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1088. return true;
  1089. }
  1090. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1091. const Expr *E) {
  1092. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1093. // Do not set the designator as invalid: we can represent this situation,
  1094. // and correct handling of __builtin_object_size requires us to do so.
  1095. }
  1096. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1097. const Expr *E,
  1098. const APSInt &N) {
  1099. // If we're complaining, we must be able to statically determine the size of
  1100. // the most derived array.
  1101. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1102. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1103. << N << /*array*/ 0
  1104. << static_cast<unsigned>(getMostDerivedArraySize());
  1105. else
  1106. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1107. << N << /*non-array*/ 1;
  1108. setInvalid();
  1109. }
  1110. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1111. const FunctionDecl *Callee, const LValue *This,
  1112. APValue *Arguments)
  1113. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1114. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1115. Info.CurrentCall = this;
  1116. ++Info.CallStackDepth;
  1117. }
  1118. CallStackFrame::~CallStackFrame() {
  1119. assert(Info.CurrentCall == this && "calls retired out of order");
  1120. --Info.CallStackDepth;
  1121. Info.CurrentCall = Caller;
  1122. }
  1123. APValue &CallStackFrame::createTemporary(const void *Key,
  1124. bool IsLifetimeExtended) {
  1125. unsigned Version = Info.CurrentCall->getTempVersion();
  1126. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1127. assert(Result.isUninit() && "temporary created multiple times");
  1128. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1129. return Result;
  1130. }
  1131. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1132. void EvalInfo::addCallStack(unsigned Limit) {
  1133. // Determine which calls to skip, if any.
  1134. unsigned ActiveCalls = CallStackDepth - 1;
  1135. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1136. if (Limit && Limit < ActiveCalls) {
  1137. SkipStart = Limit / 2 + Limit % 2;
  1138. SkipEnd = ActiveCalls - Limit / 2;
  1139. }
  1140. // Walk the call stack and add the diagnostics.
  1141. unsigned CallIdx = 0;
  1142. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1143. Frame = Frame->Caller, ++CallIdx) {
  1144. // Skip this call?
  1145. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1146. if (CallIdx == SkipStart) {
  1147. // Note that we're skipping calls.
  1148. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1149. << unsigned(ActiveCalls - Limit);
  1150. }
  1151. continue;
  1152. }
  1153. // Use a different note for an inheriting constructor, because from the
  1154. // user's perspective it's not really a function at all.
  1155. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1156. if (CD->isInheritingConstructor()) {
  1157. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1158. << CD->getParent();
  1159. continue;
  1160. }
  1161. }
  1162. SmallVector<char, 128> Buffer;
  1163. llvm::raw_svector_ostream Out(Buffer);
  1164. describeCall(Frame, Out);
  1165. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1166. }
  1167. }
  1168. /// Kinds of access we can perform on an object, for diagnostics. Note that
  1169. /// we consider a member function call to be a kind of access, even though
  1170. /// it is not formally an access of the object, because it has (largely) the
  1171. /// same set of semantic restrictions.
  1172. enum AccessKinds {
  1173. AK_Read,
  1174. AK_Assign,
  1175. AK_Increment,
  1176. AK_Decrement,
  1177. AK_MemberCall,
  1178. AK_DynamicCast,
  1179. };
  1180. static bool isModification(AccessKinds AK) {
  1181. switch (AK) {
  1182. case AK_Read:
  1183. case AK_MemberCall:
  1184. case AK_DynamicCast:
  1185. return false;
  1186. case AK_Assign:
  1187. case AK_Increment:
  1188. case AK_Decrement:
  1189. return true;
  1190. }
  1191. llvm_unreachable("unknown access kind");
  1192. }
  1193. /// Is this an access per the C++ definition?
  1194. static bool isFormalAccess(AccessKinds AK) {
  1195. return AK == AK_Read || isModification(AK);
  1196. }
  1197. namespace {
  1198. struct ComplexValue {
  1199. private:
  1200. bool IsInt;
  1201. public:
  1202. APSInt IntReal, IntImag;
  1203. APFloat FloatReal, FloatImag;
  1204. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1205. void makeComplexFloat() { IsInt = false; }
  1206. bool isComplexFloat() const { return !IsInt; }
  1207. APFloat &getComplexFloatReal() { return FloatReal; }
  1208. APFloat &getComplexFloatImag() { return FloatImag; }
  1209. void makeComplexInt() { IsInt = true; }
  1210. bool isComplexInt() const { return IsInt; }
  1211. APSInt &getComplexIntReal() { return IntReal; }
  1212. APSInt &getComplexIntImag() { return IntImag; }
  1213. void moveInto(APValue &v) const {
  1214. if (isComplexFloat())
  1215. v = APValue(FloatReal, FloatImag);
  1216. else
  1217. v = APValue(IntReal, IntImag);
  1218. }
  1219. void setFrom(const APValue &v) {
  1220. assert(v.isComplexFloat() || v.isComplexInt());
  1221. if (v.isComplexFloat()) {
  1222. makeComplexFloat();
  1223. FloatReal = v.getComplexFloatReal();
  1224. FloatImag = v.getComplexFloatImag();
  1225. } else {
  1226. makeComplexInt();
  1227. IntReal = v.getComplexIntReal();
  1228. IntImag = v.getComplexIntImag();
  1229. }
  1230. }
  1231. };
  1232. struct LValue {
  1233. APValue::LValueBase Base;
  1234. CharUnits Offset;
  1235. SubobjectDesignator Designator;
  1236. bool IsNullPtr : 1;
  1237. bool InvalidBase : 1;
  1238. const APValue::LValueBase getLValueBase() const { return Base; }
  1239. CharUnits &getLValueOffset() { return Offset; }
  1240. const CharUnits &getLValueOffset() const { return Offset; }
  1241. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1242. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1243. bool isNullPointer() const { return IsNullPtr;}
  1244. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1245. unsigned getLValueVersion() const { return Base.getVersion(); }
  1246. void moveInto(APValue &V) const {
  1247. if (Designator.Invalid)
  1248. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1249. else {
  1250. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1251. V = APValue(Base, Offset, Designator.Entries,
  1252. Designator.IsOnePastTheEnd, IsNullPtr);
  1253. }
  1254. }
  1255. void setFrom(ASTContext &Ctx, const APValue &V) {
  1256. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1257. Base = V.getLValueBase();
  1258. Offset = V.getLValueOffset();
  1259. InvalidBase = false;
  1260. Designator = SubobjectDesignator(Ctx, V);
  1261. IsNullPtr = V.isNullPointer();
  1262. }
  1263. void set(APValue::LValueBase B, bool BInvalid = false) {
  1264. #ifndef NDEBUG
  1265. // We only allow a few types of invalid bases. Enforce that here.
  1266. if (BInvalid) {
  1267. const auto *E = B.get<const Expr *>();
  1268. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1269. "Unexpected type of invalid base");
  1270. }
  1271. #endif
  1272. Base = B;
  1273. Offset = CharUnits::fromQuantity(0);
  1274. InvalidBase = BInvalid;
  1275. Designator = SubobjectDesignator(getType(B));
  1276. IsNullPtr = false;
  1277. }
  1278. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1279. Base = (Expr *)nullptr;
  1280. Offset = CharUnits::fromQuantity(TargetVal);
  1281. InvalidBase = false;
  1282. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1283. IsNullPtr = true;
  1284. }
  1285. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1286. set(B, true);
  1287. }
  1288. private:
  1289. // Check that this LValue is not based on a null pointer. If it is, produce
  1290. // a diagnostic and mark the designator as invalid.
  1291. template <typename GenDiagType>
  1292. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1293. if (Designator.Invalid)
  1294. return false;
  1295. if (IsNullPtr) {
  1296. GenDiag();
  1297. Designator.setInvalid();
  1298. return false;
  1299. }
  1300. return true;
  1301. }
  1302. public:
  1303. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1304. CheckSubobjectKind CSK) {
  1305. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1306. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1307. });
  1308. }
  1309. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1310. AccessKinds AK) {
  1311. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1312. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1313. });
  1314. }
  1315. // Check this LValue refers to an object. If not, set the designator to be
  1316. // invalid and emit a diagnostic.
  1317. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1318. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1319. Designator.checkSubobject(Info, E, CSK);
  1320. }
  1321. void addDecl(EvalInfo &Info, const Expr *E,
  1322. const Decl *D, bool Virtual = false) {
  1323. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1324. Designator.addDeclUnchecked(D, Virtual);
  1325. }
  1326. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1327. if (!Designator.Entries.empty()) {
  1328. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1329. Designator.setInvalid();
  1330. return;
  1331. }
  1332. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1333. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1334. Designator.FirstEntryIsAnUnsizedArray = true;
  1335. Designator.addUnsizedArrayUnchecked(ElemTy);
  1336. }
  1337. }
  1338. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1339. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1340. Designator.addArrayUnchecked(CAT);
  1341. }
  1342. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1343. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1344. Designator.addComplexUnchecked(EltTy, Imag);
  1345. }
  1346. void clearIsNullPointer() {
  1347. IsNullPtr = false;
  1348. }
  1349. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1350. const APSInt &Index, CharUnits ElementSize) {
  1351. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1352. // but we're not required to diagnose it and it's valid in C++.)
  1353. if (!Index)
  1354. return;
  1355. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1356. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1357. // offsets.
  1358. uint64_t Offset64 = Offset.getQuantity();
  1359. uint64_t ElemSize64 = ElementSize.getQuantity();
  1360. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1361. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1362. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1363. Designator.adjustIndex(Info, E, Index);
  1364. clearIsNullPointer();
  1365. }
  1366. void adjustOffset(CharUnits N) {
  1367. Offset += N;
  1368. if (N.getQuantity())
  1369. clearIsNullPointer();
  1370. }
  1371. };
  1372. struct MemberPtr {
  1373. MemberPtr() {}
  1374. explicit MemberPtr(const ValueDecl *Decl) :
  1375. DeclAndIsDerivedMember(Decl, false), Path() {}
  1376. /// The member or (direct or indirect) field referred to by this member
  1377. /// pointer, or 0 if this is a null member pointer.
  1378. const ValueDecl *getDecl() const {
  1379. return DeclAndIsDerivedMember.getPointer();
  1380. }
  1381. /// Is this actually a member of some type derived from the relevant class?
  1382. bool isDerivedMember() const {
  1383. return DeclAndIsDerivedMember.getInt();
  1384. }
  1385. /// Get the class which the declaration actually lives in.
  1386. const CXXRecordDecl *getContainingRecord() const {
  1387. return cast<CXXRecordDecl>(
  1388. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1389. }
  1390. void moveInto(APValue &V) const {
  1391. V = APValue(getDecl(), isDerivedMember(), Path);
  1392. }
  1393. void setFrom(const APValue &V) {
  1394. assert(V.isMemberPointer());
  1395. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1396. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1397. Path.clear();
  1398. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1399. Path.insert(Path.end(), P.begin(), P.end());
  1400. }
  1401. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1402. /// whether the member is a member of some class derived from the class type
  1403. /// of the member pointer.
  1404. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1405. /// Path - The path of base/derived classes from the member declaration's
  1406. /// class (exclusive) to the class type of the member pointer (inclusive).
  1407. SmallVector<const CXXRecordDecl*, 4> Path;
  1408. /// Perform a cast towards the class of the Decl (either up or down the
  1409. /// hierarchy).
  1410. bool castBack(const CXXRecordDecl *Class) {
  1411. assert(!Path.empty());
  1412. const CXXRecordDecl *Expected;
  1413. if (Path.size() >= 2)
  1414. Expected = Path[Path.size() - 2];
  1415. else
  1416. Expected = getContainingRecord();
  1417. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1418. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1419. // if B does not contain the original member and is not a base or
  1420. // derived class of the class containing the original member, the result
  1421. // of the cast is undefined.
  1422. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1423. // (D::*). We consider that to be a language defect.
  1424. return false;
  1425. }
  1426. Path.pop_back();
  1427. return true;
  1428. }
  1429. /// Perform a base-to-derived member pointer cast.
  1430. bool castToDerived(const CXXRecordDecl *Derived) {
  1431. if (!getDecl())
  1432. return true;
  1433. if (!isDerivedMember()) {
  1434. Path.push_back(Derived);
  1435. return true;
  1436. }
  1437. if (!castBack(Derived))
  1438. return false;
  1439. if (Path.empty())
  1440. DeclAndIsDerivedMember.setInt(false);
  1441. return true;
  1442. }
  1443. /// Perform a derived-to-base member pointer cast.
  1444. bool castToBase(const CXXRecordDecl *Base) {
  1445. if (!getDecl())
  1446. return true;
  1447. if (Path.empty())
  1448. DeclAndIsDerivedMember.setInt(true);
  1449. if (isDerivedMember()) {
  1450. Path.push_back(Base);
  1451. return true;
  1452. }
  1453. return castBack(Base);
  1454. }
  1455. };
  1456. /// Compare two member pointers, which are assumed to be of the same type.
  1457. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1458. if (!LHS.getDecl() || !RHS.getDecl())
  1459. return !LHS.getDecl() && !RHS.getDecl();
  1460. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1461. return false;
  1462. return LHS.Path == RHS.Path;
  1463. }
  1464. }
  1465. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1466. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1467. const LValue &This, const Expr *E,
  1468. bool AllowNonLiteralTypes = false);
  1469. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1470. bool InvalidBaseOK = false);
  1471. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1472. bool InvalidBaseOK = false);
  1473. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1474. EvalInfo &Info);
  1475. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1476. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1477. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1478. EvalInfo &Info);
  1479. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1480. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1481. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1482. EvalInfo &Info);
  1483. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1484. /// Evaluate an integer or fixed point expression into an APResult.
  1485. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1486. EvalInfo &Info);
  1487. /// Evaluate only a fixed point expression into an APResult.
  1488. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1489. EvalInfo &Info);
  1490. //===----------------------------------------------------------------------===//
  1491. // Misc utilities
  1492. //===----------------------------------------------------------------------===//
  1493. /// A helper function to create a temporary and set an LValue.
  1494. template <class KeyTy>
  1495. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1496. LValue &LV, CallStackFrame &Frame) {
  1497. LV.set({Key, Frame.Info.CurrentCall->Index,
  1498. Frame.Info.CurrentCall->getTempVersion()});
  1499. return Frame.createTemporary(Key, IsLifetimeExtended);
  1500. }
  1501. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1502. /// preserving its value (by extending by up to one bit as needed).
  1503. static void negateAsSigned(APSInt &Int) {
  1504. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1505. Int = Int.extend(Int.getBitWidth() + 1);
  1506. Int.setIsSigned(true);
  1507. }
  1508. Int = -Int;
  1509. }
  1510. /// Produce a string describing the given constexpr call.
  1511. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1512. unsigned ArgIndex = 0;
  1513. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1514. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1515. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1516. if (!IsMemberCall)
  1517. Out << *Frame->Callee << '(';
  1518. if (Frame->This && IsMemberCall) {
  1519. APValue Val;
  1520. Frame->This->moveInto(Val);
  1521. Val.printPretty(Out, Frame->Info.Ctx,
  1522. Frame->This->Designator.MostDerivedType);
  1523. // FIXME: Add parens around Val if needed.
  1524. Out << "->" << *Frame->Callee << '(';
  1525. IsMemberCall = false;
  1526. }
  1527. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1528. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1529. if (ArgIndex > (unsigned)IsMemberCall)
  1530. Out << ", ";
  1531. const ParmVarDecl *Param = *I;
  1532. const APValue &Arg = Frame->Arguments[ArgIndex];
  1533. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1534. if (ArgIndex == 0 && IsMemberCall)
  1535. Out << "->" << *Frame->Callee << '(';
  1536. }
  1537. Out << ')';
  1538. }
  1539. /// Evaluate an expression to see if it had side-effects, and discard its
  1540. /// result.
  1541. /// \return \c true if the caller should keep evaluating.
  1542. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1543. APValue Scratch;
  1544. if (!Evaluate(Scratch, Info, E))
  1545. // We don't need the value, but we might have skipped a side effect here.
  1546. return Info.noteSideEffect();
  1547. return true;
  1548. }
  1549. /// Should this call expression be treated as a string literal?
  1550. static bool IsStringLiteralCall(const CallExpr *E) {
  1551. unsigned Builtin = E->getBuiltinCallee();
  1552. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1553. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1554. }
  1555. static bool IsGlobalLValue(APValue::LValueBase B) {
  1556. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1557. // constant expression of pointer type that evaluates to...
  1558. // ... a null pointer value, or a prvalue core constant expression of type
  1559. // std::nullptr_t.
  1560. if (!B) return true;
  1561. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1562. // ... the address of an object with static storage duration,
  1563. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1564. return VD->hasGlobalStorage();
  1565. // ... the address of a function,
  1566. return isa<FunctionDecl>(D);
  1567. }
  1568. const Expr *E = B.get<const Expr*>();
  1569. switch (E->getStmtClass()) {
  1570. default:
  1571. return false;
  1572. case Expr::CompoundLiteralExprClass: {
  1573. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1574. return CLE->isFileScope() && CLE->isLValue();
  1575. }
  1576. case Expr::MaterializeTemporaryExprClass:
  1577. // A materialized temporary might have been lifetime-extended to static
  1578. // storage duration.
  1579. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1580. // A string literal has static storage duration.
  1581. case Expr::StringLiteralClass:
  1582. case Expr::PredefinedExprClass:
  1583. case Expr::ObjCStringLiteralClass:
  1584. case Expr::ObjCEncodeExprClass:
  1585. case Expr::CXXTypeidExprClass:
  1586. case Expr::CXXUuidofExprClass:
  1587. return true;
  1588. case Expr::ObjCBoxedExprClass:
  1589. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1590. case Expr::CallExprClass:
  1591. return IsStringLiteralCall(cast<CallExpr>(E));
  1592. // For GCC compatibility, &&label has static storage duration.
  1593. case Expr::AddrLabelExprClass:
  1594. return true;
  1595. // A Block literal expression may be used as the initialization value for
  1596. // Block variables at global or local static scope.
  1597. case Expr::BlockExprClass:
  1598. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1599. case Expr::ImplicitValueInitExprClass:
  1600. // FIXME:
  1601. // We can never form an lvalue with an implicit value initialization as its
  1602. // base through expression evaluation, so these only appear in one case: the
  1603. // implicit variable declaration we invent when checking whether a constexpr
  1604. // constructor can produce a constant expression. We must assume that such
  1605. // an expression might be a global lvalue.
  1606. return true;
  1607. }
  1608. }
  1609. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1610. return LVal.Base.dyn_cast<const ValueDecl*>();
  1611. }
  1612. static bool IsLiteralLValue(const LValue &Value) {
  1613. if (Value.getLValueCallIndex())
  1614. return false;
  1615. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1616. return E && !isa<MaterializeTemporaryExpr>(E);
  1617. }
  1618. static bool IsWeakLValue(const LValue &Value) {
  1619. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1620. return Decl && Decl->isWeak();
  1621. }
  1622. static bool isZeroSized(const LValue &Value) {
  1623. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1624. if (Decl && isa<VarDecl>(Decl)) {
  1625. QualType Ty = Decl->getType();
  1626. if (Ty->isArrayType())
  1627. return Ty->isIncompleteType() ||
  1628. Decl->getASTContext().getTypeSize(Ty) == 0;
  1629. }
  1630. return false;
  1631. }
  1632. static bool HasSameBase(const LValue &A, const LValue &B) {
  1633. if (!A.getLValueBase())
  1634. return !B.getLValueBase();
  1635. if (!B.getLValueBase())
  1636. return false;
  1637. if (A.getLValueBase().getOpaqueValue() !=
  1638. B.getLValueBase().getOpaqueValue()) {
  1639. const Decl *ADecl = GetLValueBaseDecl(A);
  1640. if (!ADecl)
  1641. return false;
  1642. const Decl *BDecl = GetLValueBaseDecl(B);
  1643. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1644. return false;
  1645. }
  1646. return IsGlobalLValue(A.getLValueBase()) ||
  1647. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1648. A.getLValueVersion() == B.getLValueVersion());
  1649. }
  1650. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1651. assert(Base && "no location for a null lvalue");
  1652. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1653. if (VD)
  1654. Info.Note(VD->getLocation(), diag::note_declared_at);
  1655. else
  1656. Info.Note(Base.get<const Expr*>()->getExprLoc(),
  1657. diag::note_constexpr_temporary_here);
  1658. }
  1659. /// Check that this reference or pointer core constant expression is a valid
  1660. /// value for an address or reference constant expression. Return true if we
  1661. /// can fold this expression, whether or not it's a constant expression.
  1662. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1663. QualType Type, const LValue &LVal,
  1664. Expr::ConstExprUsage Usage) {
  1665. bool IsReferenceType = Type->isReferenceType();
  1666. APValue::LValueBase Base = LVal.getLValueBase();
  1667. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1668. // Check that the object is a global. Note that the fake 'this' object we
  1669. // manufacture when checking potential constant expressions is conservatively
  1670. // assumed to be global here.
  1671. if (!IsGlobalLValue(Base)) {
  1672. if (Info.getLangOpts().CPlusPlus11) {
  1673. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1674. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1675. << IsReferenceType << !Designator.Entries.empty()
  1676. << !!VD << VD;
  1677. NoteLValueLocation(Info, Base);
  1678. } else {
  1679. Info.FFDiag(Loc);
  1680. }
  1681. // Don't allow references to temporaries to escape.
  1682. return false;
  1683. }
  1684. assert((Info.checkingPotentialConstantExpression() ||
  1685. LVal.getLValueCallIndex() == 0) &&
  1686. "have call index for global lvalue");
  1687. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1688. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1689. // Check if this is a thread-local variable.
  1690. if (Var->getTLSKind())
  1691. return false;
  1692. // A dllimport variable never acts like a constant.
  1693. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1694. return false;
  1695. }
  1696. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1697. // __declspec(dllimport) must be handled very carefully:
  1698. // We must never initialize an expression with the thunk in C++.
  1699. // Doing otherwise would allow the same id-expression to yield
  1700. // different addresses for the same function in different translation
  1701. // units. However, this means that we must dynamically initialize the
  1702. // expression with the contents of the import address table at runtime.
  1703. //
  1704. // The C language has no notion of ODR; furthermore, it has no notion of
  1705. // dynamic initialization. This means that we are permitted to
  1706. // perform initialization with the address of the thunk.
  1707. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1708. FD->hasAttr<DLLImportAttr>())
  1709. return false;
  1710. }
  1711. }
  1712. // Allow address constant expressions to be past-the-end pointers. This is
  1713. // an extension: the standard requires them to point to an object.
  1714. if (!IsReferenceType)
  1715. return true;
  1716. // A reference constant expression must refer to an object.
  1717. if (!Base) {
  1718. // FIXME: diagnostic
  1719. Info.CCEDiag(Loc);
  1720. return true;
  1721. }
  1722. // Does this refer one past the end of some object?
  1723. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1724. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1725. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1726. << !Designator.Entries.empty() << !!VD << VD;
  1727. NoteLValueLocation(Info, Base);
  1728. }
  1729. return true;
  1730. }
  1731. /// Member pointers are constant expressions unless they point to a
  1732. /// non-virtual dllimport member function.
  1733. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1734. SourceLocation Loc,
  1735. QualType Type,
  1736. const APValue &Value,
  1737. Expr::ConstExprUsage Usage) {
  1738. const ValueDecl *Member = Value.getMemberPointerDecl();
  1739. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1740. if (!FD)
  1741. return true;
  1742. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1743. !FD->hasAttr<DLLImportAttr>();
  1744. }
  1745. /// Check that this core constant expression is of literal type, and if not,
  1746. /// produce an appropriate diagnostic.
  1747. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1748. const LValue *This = nullptr) {
  1749. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1750. return true;
  1751. // C++1y: A constant initializer for an object o [...] may also invoke
  1752. // constexpr constructors for o and its subobjects even if those objects
  1753. // are of non-literal class types.
  1754. //
  1755. // C++11 missed this detail for aggregates, so classes like this:
  1756. // struct foo_t { union { int i; volatile int j; } u; };
  1757. // are not (obviously) initializable like so:
  1758. // __attribute__((__require_constant_initialization__))
  1759. // static const foo_t x = {{0}};
  1760. // because "i" is a subobject with non-literal initialization (due to the
  1761. // volatile member of the union). See:
  1762. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1763. // Therefore, we use the C++1y behavior.
  1764. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1765. return true;
  1766. // Prvalue constant expressions must be of literal types.
  1767. if (Info.getLangOpts().CPlusPlus11)
  1768. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1769. << E->getType();
  1770. else
  1771. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1772. return false;
  1773. }
  1774. /// Check that this core constant expression value is a valid value for a
  1775. /// constant expression. If not, report an appropriate diagnostic. Does not
  1776. /// check that the expression is of literal type.
  1777. static bool
  1778. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1779. const APValue &Value,
  1780. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
  1781. if (Value.isUninit()) {
  1782. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1783. << true << Type;
  1784. return false;
  1785. }
  1786. // We allow _Atomic(T) to be initialized from anything that T can be
  1787. // initialized from.
  1788. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1789. Type = AT->getValueType();
  1790. // Core issue 1454: For a literal constant expression of array or class type,
  1791. // each subobject of its value shall have been initialized by a constant
  1792. // expression.
  1793. if (Value.isArray()) {
  1794. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1795. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1796. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1797. Value.getArrayInitializedElt(I), Usage))
  1798. return false;
  1799. }
  1800. if (!Value.hasArrayFiller())
  1801. return true;
  1802. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1803. Usage);
  1804. }
  1805. if (Value.isUnion() && Value.getUnionField()) {
  1806. return CheckConstantExpression(Info, DiagLoc,
  1807. Value.getUnionField()->getType(),
  1808. Value.getUnionValue(), Usage);
  1809. }
  1810. if (Value.isStruct()) {
  1811. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1812. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1813. unsigned BaseIndex = 0;
  1814. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1815. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1816. Value.getStructBase(BaseIndex), Usage))
  1817. return false;
  1818. ++BaseIndex;
  1819. }
  1820. }
  1821. for (const auto *I : RD->fields()) {
  1822. if (I->isUnnamedBitfield())
  1823. continue;
  1824. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1825. Value.getStructField(I->getFieldIndex()),
  1826. Usage))
  1827. return false;
  1828. }
  1829. }
  1830. if (Value.isLValue()) {
  1831. LValue LVal;
  1832. LVal.setFrom(Info.Ctx, Value);
  1833. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1834. }
  1835. if (Value.isMemberPointer())
  1836. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1837. // Everything else is fine.
  1838. return true;
  1839. }
  1840. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1841. // A null base expression indicates a null pointer. These are always
  1842. // evaluatable, and they are false unless the offset is zero.
  1843. if (!Value.getLValueBase()) {
  1844. Result = !Value.getLValueOffset().isZero();
  1845. return true;
  1846. }
  1847. // We have a non-null base. These are generally known to be true, but if it's
  1848. // a weak declaration it can be null at runtime.
  1849. Result = true;
  1850. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1851. return !Decl || !Decl->isWeak();
  1852. }
  1853. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1854. switch (Val.getKind()) {
  1855. case APValue::Uninitialized:
  1856. return false;
  1857. case APValue::Int:
  1858. Result = Val.getInt().getBoolValue();
  1859. return true;
  1860. case APValue::FixedPoint:
  1861. Result = Val.getFixedPoint().getBoolValue();
  1862. return true;
  1863. case APValue::Float:
  1864. Result = !Val.getFloat().isZero();
  1865. return true;
  1866. case APValue::ComplexInt:
  1867. Result = Val.getComplexIntReal().getBoolValue() ||
  1868. Val.getComplexIntImag().getBoolValue();
  1869. return true;
  1870. case APValue::ComplexFloat:
  1871. Result = !Val.getComplexFloatReal().isZero() ||
  1872. !Val.getComplexFloatImag().isZero();
  1873. return true;
  1874. case APValue::LValue:
  1875. return EvalPointerValueAsBool(Val, Result);
  1876. case APValue::MemberPointer:
  1877. Result = Val.getMemberPointerDecl();
  1878. return true;
  1879. case APValue::Vector:
  1880. case APValue::Array:
  1881. case APValue::Struct:
  1882. case APValue::Union:
  1883. case APValue::AddrLabelDiff:
  1884. return false;
  1885. }
  1886. llvm_unreachable("unknown APValue kind");
  1887. }
  1888. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1889. EvalInfo &Info) {
  1890. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1891. APValue Val;
  1892. if (!Evaluate(Val, Info, E))
  1893. return false;
  1894. return HandleConversionToBool(Val, Result);
  1895. }
  1896. template<typename T>
  1897. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1898. const T &SrcValue, QualType DestType) {
  1899. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1900. << SrcValue << DestType;
  1901. return Info.noteUndefinedBehavior();
  1902. }
  1903. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1904. QualType SrcType, const APFloat &Value,
  1905. QualType DestType, APSInt &Result) {
  1906. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1907. // Determine whether we are converting to unsigned or signed.
  1908. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1909. Result = APSInt(DestWidth, !DestSigned);
  1910. bool ignored;
  1911. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1912. & APFloat::opInvalidOp)
  1913. return HandleOverflow(Info, E, Value, DestType);
  1914. return true;
  1915. }
  1916. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1917. QualType SrcType, QualType DestType,
  1918. APFloat &Result) {
  1919. APFloat Value = Result;
  1920. bool ignored;
  1921. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1922. APFloat::rmNearestTiesToEven, &ignored)
  1923. & APFloat::opOverflow)
  1924. return HandleOverflow(Info, E, Value, DestType);
  1925. return true;
  1926. }
  1927. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1928. QualType DestType, QualType SrcType,
  1929. const APSInt &Value) {
  1930. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1931. // Figure out if this is a truncate, extend or noop cast.
  1932. // If the input is signed, do a sign extend, noop, or truncate.
  1933. APSInt Result = Value.extOrTrunc(DestWidth);
  1934. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1935. if (DestType->isBooleanType())
  1936. Result = Value.getBoolValue();
  1937. return Result;
  1938. }
  1939. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1940. QualType SrcType, const APSInt &Value,
  1941. QualType DestType, APFloat &Result) {
  1942. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1943. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1944. APFloat::rmNearestTiesToEven)
  1945. & APFloat::opOverflow)
  1946. return HandleOverflow(Info, E, Value, DestType);
  1947. return true;
  1948. }
  1949. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1950. APValue &Value, const FieldDecl *FD) {
  1951. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1952. if (!Value.isInt()) {
  1953. // Trying to store a pointer-cast-to-integer into a bitfield.
  1954. // FIXME: In this case, we should provide the diagnostic for casting
  1955. // a pointer to an integer.
  1956. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1957. Info.FFDiag(E);
  1958. return false;
  1959. }
  1960. APSInt &Int = Value.getInt();
  1961. unsigned OldBitWidth = Int.getBitWidth();
  1962. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1963. if (NewBitWidth < OldBitWidth)
  1964. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  1965. return true;
  1966. }
  1967. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  1968. llvm::APInt &Res) {
  1969. APValue SVal;
  1970. if (!Evaluate(SVal, Info, E))
  1971. return false;
  1972. if (SVal.isInt()) {
  1973. Res = SVal.getInt();
  1974. return true;
  1975. }
  1976. if (SVal.isFloat()) {
  1977. Res = SVal.getFloat().bitcastToAPInt();
  1978. return true;
  1979. }
  1980. if (SVal.isVector()) {
  1981. QualType VecTy = E->getType();
  1982. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  1983. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  1984. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  1985. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  1986. Res = llvm::APInt::getNullValue(VecSize);
  1987. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  1988. APValue &Elt = SVal.getVectorElt(i);
  1989. llvm::APInt EltAsInt;
  1990. if (Elt.isInt()) {
  1991. EltAsInt = Elt.getInt();
  1992. } else if (Elt.isFloat()) {
  1993. EltAsInt = Elt.getFloat().bitcastToAPInt();
  1994. } else {
  1995. // Don't try to handle vectors of anything other than int or float
  1996. // (not sure if it's possible to hit this case).
  1997. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1998. return false;
  1999. }
  2000. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2001. if (BigEndian)
  2002. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2003. else
  2004. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2005. }
  2006. return true;
  2007. }
  2008. // Give up if the input isn't an int, float, or vector. For example, we
  2009. // reject "(v4i16)(intptr_t)&a".
  2010. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2011. return false;
  2012. }
  2013. /// Perform the given integer operation, which is known to need at most BitWidth
  2014. /// bits, and check for overflow in the original type (if that type was not an
  2015. /// unsigned type).
  2016. template<typename Operation>
  2017. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2018. const APSInt &LHS, const APSInt &RHS,
  2019. unsigned BitWidth, Operation Op,
  2020. APSInt &Result) {
  2021. if (LHS.isUnsigned()) {
  2022. Result = Op(LHS, RHS);
  2023. return true;
  2024. }
  2025. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2026. Result = Value.trunc(LHS.getBitWidth());
  2027. if (Result.extend(BitWidth) != Value) {
  2028. if (Info.checkingForOverflow())
  2029. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2030. diag::warn_integer_constant_overflow)
  2031. << Result.toString(10) << E->getType();
  2032. else
  2033. return HandleOverflow(Info, E, Value, E->getType());
  2034. }
  2035. return true;
  2036. }
  2037. /// Perform the given binary integer operation.
  2038. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2039. BinaryOperatorKind Opcode, APSInt RHS,
  2040. APSInt &Result) {
  2041. switch (Opcode) {
  2042. default:
  2043. Info.FFDiag(E);
  2044. return false;
  2045. case BO_Mul:
  2046. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2047. std::multiplies<APSInt>(), Result);
  2048. case BO_Add:
  2049. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2050. std::plus<APSInt>(), Result);
  2051. case BO_Sub:
  2052. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2053. std::minus<APSInt>(), Result);
  2054. case BO_And: Result = LHS & RHS; return true;
  2055. case BO_Xor: Result = LHS ^ RHS; return true;
  2056. case BO_Or: Result = LHS | RHS; return true;
  2057. case BO_Div:
  2058. case BO_Rem:
  2059. if (RHS == 0) {
  2060. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2061. return false;
  2062. }
  2063. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2064. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2065. // this operation and gives the two's complement result.
  2066. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2067. LHS.isSigned() && LHS.isMinSignedValue())
  2068. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2069. E->getType());
  2070. return true;
  2071. case BO_Shl: {
  2072. if (Info.getLangOpts().OpenCL)
  2073. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2074. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2075. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2076. RHS.isUnsigned());
  2077. else if (RHS.isSigned() && RHS.isNegative()) {
  2078. // During constant-folding, a negative shift is an opposite shift. Such
  2079. // a shift is not a constant expression.
  2080. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2081. RHS = -RHS;
  2082. goto shift_right;
  2083. }
  2084. shift_left:
  2085. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2086. // the shifted type.
  2087. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2088. if (SA != RHS) {
  2089. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2090. << RHS << E->getType() << LHS.getBitWidth();
  2091. } else if (LHS.isSigned()) {
  2092. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2093. // operand, and must not overflow the corresponding unsigned type.
  2094. if (LHS.isNegative())
  2095. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2096. else if (LHS.countLeadingZeros() < SA)
  2097. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2098. }
  2099. Result = LHS << SA;
  2100. return true;
  2101. }
  2102. case BO_Shr: {
  2103. if (Info.getLangOpts().OpenCL)
  2104. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2105. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2106. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2107. RHS.isUnsigned());
  2108. else if (RHS.isSigned() && RHS.isNegative()) {
  2109. // During constant-folding, a negative shift is an opposite shift. Such a
  2110. // shift is not a constant expression.
  2111. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2112. RHS = -RHS;
  2113. goto shift_left;
  2114. }
  2115. shift_right:
  2116. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2117. // shifted type.
  2118. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2119. if (SA != RHS)
  2120. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2121. << RHS << E->getType() << LHS.getBitWidth();
  2122. Result = LHS >> SA;
  2123. return true;
  2124. }
  2125. case BO_LT: Result = LHS < RHS; return true;
  2126. case BO_GT: Result = LHS > RHS; return true;
  2127. case BO_LE: Result = LHS <= RHS; return true;
  2128. case BO_GE: Result = LHS >= RHS; return true;
  2129. case BO_EQ: Result = LHS == RHS; return true;
  2130. case BO_NE: Result = LHS != RHS; return true;
  2131. case BO_Cmp:
  2132. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2133. }
  2134. }
  2135. /// Perform the given binary floating-point operation, in-place, on LHS.
  2136. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2137. APFloat &LHS, BinaryOperatorKind Opcode,
  2138. const APFloat &RHS) {
  2139. switch (Opcode) {
  2140. default:
  2141. Info.FFDiag(E);
  2142. return false;
  2143. case BO_Mul:
  2144. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2145. break;
  2146. case BO_Add:
  2147. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2148. break;
  2149. case BO_Sub:
  2150. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2151. break;
  2152. case BO_Div:
  2153. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2154. break;
  2155. }
  2156. if (LHS.isInfinity() || LHS.isNaN()) {
  2157. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2158. return Info.noteUndefinedBehavior();
  2159. }
  2160. return true;
  2161. }
  2162. /// Cast an lvalue referring to a base subobject to a derived class, by
  2163. /// truncating the lvalue's path to the given length.
  2164. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2165. const RecordDecl *TruncatedType,
  2166. unsigned TruncatedElements) {
  2167. SubobjectDesignator &D = Result.Designator;
  2168. // Check we actually point to a derived class object.
  2169. if (TruncatedElements == D.Entries.size())
  2170. return true;
  2171. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2172. "not casting to a derived class");
  2173. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2174. return false;
  2175. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2176. const RecordDecl *RD = TruncatedType;
  2177. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2178. if (RD->isInvalidDecl()) return false;
  2179. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2180. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2181. if (isVirtualBaseClass(D.Entries[I]))
  2182. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2183. else
  2184. Result.Offset -= Layout.getBaseClassOffset(Base);
  2185. RD = Base;
  2186. }
  2187. D.Entries.resize(TruncatedElements);
  2188. return true;
  2189. }
  2190. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2191. const CXXRecordDecl *Derived,
  2192. const CXXRecordDecl *Base,
  2193. const ASTRecordLayout *RL = nullptr) {
  2194. if (!RL) {
  2195. if (Derived->isInvalidDecl()) return false;
  2196. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2197. }
  2198. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2199. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2200. return true;
  2201. }
  2202. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2203. const CXXRecordDecl *DerivedDecl,
  2204. const CXXBaseSpecifier *Base) {
  2205. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2206. if (!Base->isVirtual())
  2207. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2208. SubobjectDesignator &D = Obj.Designator;
  2209. if (D.Invalid)
  2210. return false;
  2211. // Extract most-derived object and corresponding type.
  2212. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2213. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2214. return false;
  2215. // Find the virtual base class.
  2216. if (DerivedDecl->isInvalidDecl()) return false;
  2217. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2218. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2219. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2220. return true;
  2221. }
  2222. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2223. QualType Type, LValue &Result) {
  2224. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2225. PathE = E->path_end();
  2226. PathI != PathE; ++PathI) {
  2227. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2228. *PathI))
  2229. return false;
  2230. Type = (*PathI)->getType();
  2231. }
  2232. return true;
  2233. }
  2234. /// Cast an lvalue referring to a derived class to a known base subobject.
  2235. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2236. const CXXRecordDecl *DerivedRD,
  2237. const CXXRecordDecl *BaseRD) {
  2238. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2239. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2240. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2241. llvm_unreachable("Class must be derived from the passed in base class!");
  2242. for (CXXBasePathElement &Elem : Paths.front())
  2243. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2244. return false;
  2245. return true;
  2246. }
  2247. /// Update LVal to refer to the given field, which must be a member of the type
  2248. /// currently described by LVal.
  2249. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2250. const FieldDecl *FD,
  2251. const ASTRecordLayout *RL = nullptr) {
  2252. if (!RL) {
  2253. if (FD->getParent()->isInvalidDecl()) return false;
  2254. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2255. }
  2256. unsigned I = FD->getFieldIndex();
  2257. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2258. LVal.addDecl(Info, E, FD);
  2259. return true;
  2260. }
  2261. /// Update LVal to refer to the given indirect field.
  2262. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2263. LValue &LVal,
  2264. const IndirectFieldDecl *IFD) {
  2265. for (const auto *C : IFD->chain())
  2266. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2267. return false;
  2268. return true;
  2269. }
  2270. /// Get the size of the given type in char units.
  2271. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2272. QualType Type, CharUnits &Size) {
  2273. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2274. // extension.
  2275. if (Type->isVoidType() || Type->isFunctionType()) {
  2276. Size = CharUnits::One();
  2277. return true;
  2278. }
  2279. if (Type->isDependentType()) {
  2280. Info.FFDiag(Loc);
  2281. return false;
  2282. }
  2283. if (!Type->isConstantSizeType()) {
  2284. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2285. // FIXME: Better diagnostic.
  2286. Info.FFDiag(Loc);
  2287. return false;
  2288. }
  2289. Size = Info.Ctx.getTypeSizeInChars(Type);
  2290. return true;
  2291. }
  2292. /// Update a pointer value to model pointer arithmetic.
  2293. /// \param Info - Information about the ongoing evaluation.
  2294. /// \param E - The expression being evaluated, for diagnostic purposes.
  2295. /// \param LVal - The pointer value to be updated.
  2296. /// \param EltTy - The pointee type represented by LVal.
  2297. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2298. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2299. LValue &LVal, QualType EltTy,
  2300. APSInt Adjustment) {
  2301. CharUnits SizeOfPointee;
  2302. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2303. return false;
  2304. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2305. return true;
  2306. }
  2307. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2308. LValue &LVal, QualType EltTy,
  2309. int64_t Adjustment) {
  2310. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2311. APSInt::get(Adjustment));
  2312. }
  2313. /// Update an lvalue to refer to a component of a complex number.
  2314. /// \param Info - Information about the ongoing evaluation.
  2315. /// \param LVal - The lvalue to be updated.
  2316. /// \param EltTy - The complex number's component type.
  2317. /// \param Imag - False for the real component, true for the imaginary.
  2318. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2319. LValue &LVal, QualType EltTy,
  2320. bool Imag) {
  2321. if (Imag) {
  2322. CharUnits SizeOfComponent;
  2323. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2324. return false;
  2325. LVal.Offset += SizeOfComponent;
  2326. }
  2327. LVal.addComplex(Info, E, EltTy, Imag);
  2328. return true;
  2329. }
  2330. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2331. QualType Type, const LValue &LVal,
  2332. APValue &RVal);
  2333. /// Try to evaluate the initializer for a variable declaration.
  2334. ///
  2335. /// \param Info Information about the ongoing evaluation.
  2336. /// \param E An expression to be used when printing diagnostics.
  2337. /// \param VD The variable whose initializer should be obtained.
  2338. /// \param Frame The frame in which the variable was created. Must be null
  2339. /// if this variable is not local to the evaluation.
  2340. /// \param Result Filled in with a pointer to the value of the variable.
  2341. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2342. const VarDecl *VD, CallStackFrame *Frame,
  2343. APValue *&Result, const LValue *LVal) {
  2344. // If this is a parameter to an active constexpr function call, perform
  2345. // argument substitution.
  2346. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2347. // Assume arguments of a potential constant expression are unknown
  2348. // constant expressions.
  2349. if (Info.checkingPotentialConstantExpression())
  2350. return false;
  2351. if (!Frame || !Frame->Arguments) {
  2352. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2353. return false;
  2354. }
  2355. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2356. return true;
  2357. }
  2358. // If this is a local variable, dig out its value.
  2359. if (Frame) {
  2360. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2361. : Frame->getCurrentTemporary(VD);
  2362. if (!Result) {
  2363. // Assume variables referenced within a lambda's call operator that were
  2364. // not declared within the call operator are captures and during checking
  2365. // of a potential constant expression, assume they are unknown constant
  2366. // expressions.
  2367. assert(isLambdaCallOperator(Frame->Callee) &&
  2368. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2369. "missing value for local variable");
  2370. if (Info.checkingPotentialConstantExpression())
  2371. return false;
  2372. // FIXME: implement capture evaluation during constant expr evaluation.
  2373. Info.FFDiag(E->getBeginLoc(),
  2374. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2375. << "captures not currently allowed";
  2376. return false;
  2377. }
  2378. return true;
  2379. }
  2380. // Dig out the initializer, and use the declaration which it's attached to.
  2381. const Expr *Init = VD->getAnyInitializer(VD);
  2382. if (!Init || Init->isValueDependent()) {
  2383. // If we're checking a potential constant expression, the variable could be
  2384. // initialized later.
  2385. if (!Info.checkingPotentialConstantExpression())
  2386. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2387. return false;
  2388. }
  2389. // If we're currently evaluating the initializer of this declaration, use that
  2390. // in-flight value.
  2391. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2392. Result = Info.EvaluatingDeclValue;
  2393. return true;
  2394. }
  2395. // Never evaluate the initializer of a weak variable. We can't be sure that
  2396. // this is the definition which will be used.
  2397. if (VD->isWeak()) {
  2398. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2399. return false;
  2400. }
  2401. // Check that we can fold the initializer. In C++, we will have already done
  2402. // this in the cases where it matters for conformance.
  2403. SmallVector<PartialDiagnosticAt, 8> Notes;
  2404. if (!VD->evaluateValue(Notes)) {
  2405. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2406. Notes.size() + 1) << VD;
  2407. Info.Note(VD->getLocation(), diag::note_declared_at);
  2408. Info.addNotes(Notes);
  2409. return false;
  2410. } else if (!VD->checkInitIsICE()) {
  2411. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2412. Notes.size() + 1) << VD;
  2413. Info.Note(VD->getLocation(), diag::note_declared_at);
  2414. Info.addNotes(Notes);
  2415. }
  2416. Result = VD->getEvaluatedValue();
  2417. return true;
  2418. }
  2419. static bool IsConstNonVolatile(QualType T) {
  2420. Qualifiers Quals = T.getQualifiers();
  2421. return Quals.hasConst() && !Quals.hasVolatile();
  2422. }
  2423. /// Get the base index of the given base class within an APValue representing
  2424. /// the given derived class.
  2425. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2426. const CXXRecordDecl *Base) {
  2427. Base = Base->getCanonicalDecl();
  2428. unsigned Index = 0;
  2429. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2430. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2431. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2432. return Index;
  2433. }
  2434. llvm_unreachable("base class missing from derived class's bases list");
  2435. }
  2436. /// Extract the value of a character from a string literal.
  2437. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2438. uint64_t Index) {
  2439. // FIXME: Support MakeStringConstant
  2440. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2441. std::string Str;
  2442. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2443. assert(Index <= Str.size() && "Index too large");
  2444. return APSInt::getUnsigned(Str.c_str()[Index]);
  2445. }
  2446. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2447. Lit = PE->getFunctionName();
  2448. const StringLiteral *S = cast<StringLiteral>(Lit);
  2449. const ConstantArrayType *CAT =
  2450. Info.Ctx.getAsConstantArrayType(S->getType());
  2451. assert(CAT && "string literal isn't an array");
  2452. QualType CharType = CAT->getElementType();
  2453. assert(CharType->isIntegerType() && "unexpected character type");
  2454. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2455. CharType->isUnsignedIntegerType());
  2456. if (Index < S->getLength())
  2457. Value = S->getCodeUnit(Index);
  2458. return Value;
  2459. }
  2460. // Expand a string literal into an array of characters.
  2461. //
  2462. // FIXME: This is inefficient; we should probably introduce something similar
  2463. // to the LLVM ConstantDataArray to make this cheaper.
  2464. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2465. APValue &Result) {
  2466. const ConstantArrayType *CAT =
  2467. Info.Ctx.getAsConstantArrayType(S->getType());
  2468. assert(CAT && "string literal isn't an array");
  2469. QualType CharType = CAT->getElementType();
  2470. assert(CharType->isIntegerType() && "unexpected character type");
  2471. unsigned Elts = CAT->getSize().getZExtValue();
  2472. Result = APValue(APValue::UninitArray(),
  2473. std::min(S->getLength(), Elts), Elts);
  2474. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2475. CharType->isUnsignedIntegerType());
  2476. if (Result.hasArrayFiller())
  2477. Result.getArrayFiller() = APValue(Value);
  2478. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2479. Value = S->getCodeUnit(I);
  2480. Result.getArrayInitializedElt(I) = APValue(Value);
  2481. }
  2482. }
  2483. // Expand an array so that it has more than Index filled elements.
  2484. static void expandArray(APValue &Array, unsigned Index) {
  2485. unsigned Size = Array.getArraySize();
  2486. assert(Index < Size);
  2487. // Always at least double the number of elements for which we store a value.
  2488. unsigned OldElts = Array.getArrayInitializedElts();
  2489. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2490. NewElts = std::min(Size, std::max(NewElts, 8u));
  2491. // Copy the data across.
  2492. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2493. for (unsigned I = 0; I != OldElts; ++I)
  2494. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2495. for (unsigned I = OldElts; I != NewElts; ++I)
  2496. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2497. if (NewValue.hasArrayFiller())
  2498. NewValue.getArrayFiller() = Array.getArrayFiller();
  2499. Array.swap(NewValue);
  2500. }
  2501. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2502. /// conversion. If it's of class type, we may assume that the copy operation
  2503. /// is trivial. Note that this is never true for a union type with fields
  2504. /// (because the copy always "reads" the active member) and always true for
  2505. /// a non-class type.
  2506. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2507. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2508. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2509. return true;
  2510. if (RD->isEmpty())
  2511. return false;
  2512. for (auto *Field : RD->fields())
  2513. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2514. return true;
  2515. for (auto &BaseSpec : RD->bases())
  2516. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2517. return true;
  2518. return false;
  2519. }
  2520. /// Diagnose an attempt to read from any unreadable field within the specified
  2521. /// type, which might be a class type.
  2522. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2523. QualType T) {
  2524. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2525. if (!RD)
  2526. return false;
  2527. if (!RD->hasMutableFields())
  2528. return false;
  2529. for (auto *Field : RD->fields()) {
  2530. // If we're actually going to read this field in some way, then it can't
  2531. // be mutable. If we're in a union, then assigning to a mutable field
  2532. // (even an empty one) can change the active member, so that's not OK.
  2533. // FIXME: Add core issue number for the union case.
  2534. if (Field->isMutable() &&
  2535. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2536. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2537. Info.Note(Field->getLocation(), diag::note_declared_at);
  2538. return true;
  2539. }
  2540. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2541. return true;
  2542. }
  2543. for (auto &BaseSpec : RD->bases())
  2544. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2545. return true;
  2546. // All mutable fields were empty, and thus not actually read.
  2547. return false;
  2548. }
  2549. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2550. APValue::LValueBase Base) {
  2551. // A temporary we created.
  2552. if (Base.getCallIndex())
  2553. return true;
  2554. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2555. if (!Evaluating)
  2556. return false;
  2557. // The variable whose initializer we're evaluating.
  2558. if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
  2559. if (declaresSameEntity(Evaluating, BaseD))
  2560. return true;
  2561. // A temporary lifetime-extended by the variable whose initializer we're
  2562. // evaluating.
  2563. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2564. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2565. if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
  2566. return true;
  2567. return false;
  2568. }
  2569. namespace {
  2570. /// A handle to a complete object (an object that is not a subobject of
  2571. /// another object).
  2572. struct CompleteObject {
  2573. /// The identity of the object.
  2574. APValue::LValueBase Base;
  2575. /// The value of the complete object.
  2576. APValue *Value;
  2577. /// The type of the complete object.
  2578. QualType Type;
  2579. CompleteObject() : Value(nullptr) {}
  2580. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2581. : Base(Base), Value(Value), Type(Type) {}
  2582. bool mayReadMutableMembers(EvalInfo &Info) const {
  2583. // In C++14 onwards, it is permitted to read a mutable member whose
  2584. // lifetime began within the evaluation.
  2585. // FIXME: Should we also allow this in C++11?
  2586. if (!Info.getLangOpts().CPlusPlus14)
  2587. return false;
  2588. return lifetimeStartedInEvaluation(Info, Base);
  2589. }
  2590. explicit operator bool() const { return !Type.isNull(); }
  2591. };
  2592. } // end anonymous namespace
  2593. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2594. bool IsMutable = false) {
  2595. // C++ [basic.type.qualifier]p1:
  2596. // - A const object is an object of type const T or a non-mutable subobject
  2597. // of a const object.
  2598. if (ObjType.isConstQualified() && !IsMutable)
  2599. SubobjType.addConst();
  2600. // - A volatile object is an object of type const T or a subobject of a
  2601. // volatile object.
  2602. if (ObjType.isVolatileQualified())
  2603. SubobjType.addVolatile();
  2604. return SubobjType;
  2605. }
  2606. /// Find the designated sub-object of an rvalue.
  2607. template<typename SubobjectHandler>
  2608. typename SubobjectHandler::result_type
  2609. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2610. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2611. if (Sub.Invalid)
  2612. // A diagnostic will have already been produced.
  2613. return handler.failed();
  2614. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2615. if (Info.getLangOpts().CPlusPlus11)
  2616. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2617. ? diag::note_constexpr_access_past_end
  2618. : diag::note_constexpr_access_unsized_array)
  2619. << handler.AccessKind;
  2620. else
  2621. Info.FFDiag(E);
  2622. return handler.failed();
  2623. }
  2624. APValue *O = Obj.Value;
  2625. QualType ObjType = Obj.Type;
  2626. const FieldDecl *LastField = nullptr;
  2627. const FieldDecl *VolatileField = nullptr;
  2628. // Walk the designator's path to find the subobject.
  2629. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2630. if (O->isUninit()) {
  2631. if (!Info.checkingPotentialConstantExpression())
  2632. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2633. << handler.AccessKind;
  2634. return handler.failed();
  2635. }
  2636. // C++ [class.ctor]p5:
  2637. // const and volatile semantics are not applied on an object under
  2638. // construction.
  2639. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2640. ObjType->isRecordType() &&
  2641. Info.isEvaluatingConstructor(
  2642. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2643. Sub.Entries.begin() + I)) !=
  2644. ConstructionPhase::None) {
  2645. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2646. ObjType.removeLocalConst();
  2647. ObjType.removeLocalVolatile();
  2648. }
  2649. // If this is our last pass, check that the final object type is OK.
  2650. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2651. // Accesses to volatile objects are prohibited.
  2652. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2653. if (Info.getLangOpts().CPlusPlus) {
  2654. int DiagKind;
  2655. SourceLocation Loc;
  2656. const NamedDecl *Decl = nullptr;
  2657. if (VolatileField) {
  2658. DiagKind = 2;
  2659. Loc = VolatileField->getLocation();
  2660. Decl = VolatileField;
  2661. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2662. DiagKind = 1;
  2663. Loc = VD->getLocation();
  2664. Decl = VD;
  2665. } else {
  2666. DiagKind = 0;
  2667. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2668. Loc = E->getExprLoc();
  2669. }
  2670. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2671. << handler.AccessKind << DiagKind << Decl;
  2672. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2673. } else {
  2674. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2675. }
  2676. return handler.failed();
  2677. }
  2678. // If we are reading an object of class type, there may still be more
  2679. // things we need to check: if there are any mutable subobjects, we
  2680. // cannot perform this read. (This only happens when performing a trivial
  2681. // copy or assignment.)
  2682. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2683. !Obj.mayReadMutableMembers(Info) &&
  2684. diagnoseUnreadableFields(Info, E, ObjType))
  2685. return handler.failed();
  2686. }
  2687. if (I == N) {
  2688. if (!handler.found(*O, ObjType))
  2689. return false;
  2690. // If we modified a bit-field, truncate it to the right width.
  2691. if (isModification(handler.AccessKind) &&
  2692. LastField && LastField->isBitField() &&
  2693. !truncateBitfieldValue(Info, E, *O, LastField))
  2694. return false;
  2695. return true;
  2696. }
  2697. LastField = nullptr;
  2698. if (ObjType->isArrayType()) {
  2699. // Next subobject is an array element.
  2700. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2701. assert(CAT && "vla in literal type?");
  2702. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2703. if (CAT->getSize().ule(Index)) {
  2704. // Note, it should not be possible to form a pointer with a valid
  2705. // designator which points more than one past the end of the array.
  2706. if (Info.getLangOpts().CPlusPlus11)
  2707. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2708. << handler.AccessKind;
  2709. else
  2710. Info.FFDiag(E);
  2711. return handler.failed();
  2712. }
  2713. ObjType = CAT->getElementType();
  2714. if (O->getArrayInitializedElts() > Index)
  2715. O = &O->getArrayInitializedElt(Index);
  2716. else if (handler.AccessKind != AK_Read) {
  2717. expandArray(*O, Index);
  2718. O = &O->getArrayInitializedElt(Index);
  2719. } else
  2720. O = &O->getArrayFiller();
  2721. } else if (ObjType->isAnyComplexType()) {
  2722. // Next subobject is a complex number.
  2723. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2724. if (Index > 1) {
  2725. if (Info.getLangOpts().CPlusPlus11)
  2726. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2727. << handler.AccessKind;
  2728. else
  2729. Info.FFDiag(E);
  2730. return handler.failed();
  2731. }
  2732. ObjType = getSubobjectType(
  2733. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2734. assert(I == N - 1 && "extracting subobject of scalar?");
  2735. if (O->isComplexInt()) {
  2736. return handler.found(Index ? O->getComplexIntImag()
  2737. : O->getComplexIntReal(), ObjType);
  2738. } else {
  2739. assert(O->isComplexFloat());
  2740. return handler.found(Index ? O->getComplexFloatImag()
  2741. : O->getComplexFloatReal(), ObjType);
  2742. }
  2743. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2744. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2745. !Obj.mayReadMutableMembers(Info)) {
  2746. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2747. << Field;
  2748. Info.Note(Field->getLocation(), diag::note_declared_at);
  2749. return handler.failed();
  2750. }
  2751. // Next subobject is a class, struct or union field.
  2752. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2753. if (RD->isUnion()) {
  2754. const FieldDecl *UnionField = O->getUnionField();
  2755. if (!UnionField ||
  2756. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2757. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2758. << handler.AccessKind << Field << !UnionField << UnionField;
  2759. return handler.failed();
  2760. }
  2761. O = &O->getUnionValue();
  2762. } else
  2763. O = &O->getStructField(Field->getFieldIndex());
  2764. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2765. LastField = Field;
  2766. if (Field->getType().isVolatileQualified())
  2767. VolatileField = Field;
  2768. } else {
  2769. // Next subobject is a base class.
  2770. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2771. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2772. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2773. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2774. }
  2775. }
  2776. }
  2777. namespace {
  2778. struct ExtractSubobjectHandler {
  2779. EvalInfo &Info;
  2780. APValue &Result;
  2781. static const AccessKinds AccessKind = AK_Read;
  2782. typedef bool result_type;
  2783. bool failed() { return false; }
  2784. bool found(APValue &Subobj, QualType SubobjType) {
  2785. Result = Subobj;
  2786. return true;
  2787. }
  2788. bool found(APSInt &Value, QualType SubobjType) {
  2789. Result = APValue(Value);
  2790. return true;
  2791. }
  2792. bool found(APFloat &Value, QualType SubobjType) {
  2793. Result = APValue(Value);
  2794. return true;
  2795. }
  2796. };
  2797. } // end anonymous namespace
  2798. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2799. /// Extract the designated sub-object of an rvalue.
  2800. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2801. const CompleteObject &Obj,
  2802. const SubobjectDesignator &Sub,
  2803. APValue &Result) {
  2804. ExtractSubobjectHandler Handler = { Info, Result };
  2805. return findSubobject(Info, E, Obj, Sub, Handler);
  2806. }
  2807. namespace {
  2808. struct ModifySubobjectHandler {
  2809. EvalInfo &Info;
  2810. APValue &NewVal;
  2811. const Expr *E;
  2812. typedef bool result_type;
  2813. static const AccessKinds AccessKind = AK_Assign;
  2814. bool checkConst(QualType QT) {
  2815. // Assigning to a const object has undefined behavior.
  2816. if (QT.isConstQualified()) {
  2817. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2818. return false;
  2819. }
  2820. return true;
  2821. }
  2822. bool failed() { return false; }
  2823. bool found(APValue &Subobj, QualType SubobjType) {
  2824. if (!checkConst(SubobjType))
  2825. return false;
  2826. // We've been given ownership of NewVal, so just swap it in.
  2827. Subobj.swap(NewVal);
  2828. return true;
  2829. }
  2830. bool found(APSInt &Value, QualType SubobjType) {
  2831. if (!checkConst(SubobjType))
  2832. return false;
  2833. if (!NewVal.isInt()) {
  2834. // Maybe trying to write a cast pointer value into a complex?
  2835. Info.FFDiag(E);
  2836. return false;
  2837. }
  2838. Value = NewVal.getInt();
  2839. return true;
  2840. }
  2841. bool found(APFloat &Value, QualType SubobjType) {
  2842. if (!checkConst(SubobjType))
  2843. return false;
  2844. Value = NewVal.getFloat();
  2845. return true;
  2846. }
  2847. };
  2848. } // end anonymous namespace
  2849. const AccessKinds ModifySubobjectHandler::AccessKind;
  2850. /// Update the designated sub-object of an rvalue to the given value.
  2851. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2852. const CompleteObject &Obj,
  2853. const SubobjectDesignator &Sub,
  2854. APValue &NewVal) {
  2855. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2856. return findSubobject(Info, E, Obj, Sub, Handler);
  2857. }
  2858. /// Find the position where two subobject designators diverge, or equivalently
  2859. /// the length of the common initial subsequence.
  2860. static unsigned FindDesignatorMismatch(QualType ObjType,
  2861. const SubobjectDesignator &A,
  2862. const SubobjectDesignator &B,
  2863. bool &WasArrayIndex) {
  2864. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2865. for (/**/; I != N; ++I) {
  2866. if (!ObjType.isNull() &&
  2867. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2868. // Next subobject is an array element.
  2869. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  2870. WasArrayIndex = true;
  2871. return I;
  2872. }
  2873. if (ObjType->isAnyComplexType())
  2874. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2875. else
  2876. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2877. } else {
  2878. if (A.Entries[I].getAsBaseOrMember() !=
  2879. B.Entries[I].getAsBaseOrMember()) {
  2880. WasArrayIndex = false;
  2881. return I;
  2882. }
  2883. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2884. // Next subobject is a field.
  2885. ObjType = FD->getType();
  2886. else
  2887. // Next subobject is a base class.
  2888. ObjType = QualType();
  2889. }
  2890. }
  2891. WasArrayIndex = false;
  2892. return I;
  2893. }
  2894. /// Determine whether the given subobject designators refer to elements of the
  2895. /// same array object.
  2896. static bool AreElementsOfSameArray(QualType ObjType,
  2897. const SubobjectDesignator &A,
  2898. const SubobjectDesignator &B) {
  2899. if (A.Entries.size() != B.Entries.size())
  2900. return false;
  2901. bool IsArray = A.MostDerivedIsArrayElement;
  2902. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2903. // A is a subobject of the array element.
  2904. return false;
  2905. // If A (and B) designates an array element, the last entry will be the array
  2906. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2907. // of length 1' case, and the entire path must match.
  2908. bool WasArrayIndex;
  2909. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2910. return CommonLength >= A.Entries.size() - IsArray;
  2911. }
  2912. /// Find the complete object to which an LValue refers.
  2913. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2914. AccessKinds AK, const LValue &LVal,
  2915. QualType LValType) {
  2916. if (!LVal.Base) {
  2917. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2918. return CompleteObject();
  2919. }
  2920. CallStackFrame *Frame = nullptr;
  2921. unsigned Depth = 0;
  2922. if (LVal.getLValueCallIndex()) {
  2923. std::tie(Frame, Depth) =
  2924. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  2925. if (!Frame) {
  2926. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2927. << AK << LVal.Base.is<const ValueDecl*>();
  2928. NoteLValueLocation(Info, LVal.Base);
  2929. return CompleteObject();
  2930. }
  2931. }
  2932. bool IsAccess = isFormalAccess(AK);
  2933. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2934. // is not a constant expression (even if the object is non-volatile). We also
  2935. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2936. // semantics.
  2937. if (IsAccess && LValType.isVolatileQualified()) {
  2938. if (Info.getLangOpts().CPlusPlus)
  2939. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2940. << AK << LValType;
  2941. else
  2942. Info.FFDiag(E);
  2943. return CompleteObject();
  2944. }
  2945. // Compute value storage location and type of base object.
  2946. APValue *BaseVal = nullptr;
  2947. QualType BaseType = getType(LVal.Base);
  2948. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2949. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2950. // In C++11, constexpr, non-volatile variables initialized with constant
  2951. // expressions are constant expressions too. Inside constexpr functions,
  2952. // parameters are constant expressions even if they're non-const.
  2953. // In C++1y, objects local to a constant expression (those with a Frame) are
  2954. // both readable and writable inside constant expressions.
  2955. // In C, such things can also be folded, although they are not ICEs.
  2956. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2957. if (VD) {
  2958. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  2959. VD = VDef;
  2960. }
  2961. if (!VD || VD->isInvalidDecl()) {
  2962. Info.FFDiag(E);
  2963. return CompleteObject();
  2964. }
  2965. // Unless we're looking at a local variable or argument in a constexpr call,
  2966. // the variable we're reading must be const.
  2967. if (!Frame) {
  2968. if (Info.getLangOpts().CPlusPlus14 &&
  2969. declaresSameEntity(
  2970. VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
  2971. // OK, we can read and modify an object if we're in the process of
  2972. // evaluating its initializer, because its lifetime began in this
  2973. // evaluation.
  2974. } else if (isModification(AK)) {
  2975. // All the remaining cases do not permit modification of the object.
  2976. Info.FFDiag(E, diag::note_constexpr_modify_global);
  2977. return CompleteObject();
  2978. } else if (VD->isConstexpr()) {
  2979. // OK, we can read this variable.
  2980. } else if (BaseType->isIntegralOrEnumerationType()) {
  2981. // In OpenCL if a variable is in constant address space it is a const
  2982. // value.
  2983. if (!(BaseType.isConstQualified() ||
  2984. (Info.getLangOpts().OpenCL &&
  2985. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  2986. if (!IsAccess)
  2987. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  2988. if (Info.getLangOpts().CPlusPlus) {
  2989. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  2990. Info.Note(VD->getLocation(), diag::note_declared_at);
  2991. } else {
  2992. Info.FFDiag(E);
  2993. }
  2994. return CompleteObject();
  2995. }
  2996. } else if (!IsAccess) {
  2997. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  2998. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  2999. // We support folding of const floating-point types, in order to make
  3000. // static const data members of such types (supported as an extension)
  3001. // more useful.
  3002. if (Info.getLangOpts().CPlusPlus11) {
  3003. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3004. Info.Note(VD->getLocation(), diag::note_declared_at);
  3005. } else {
  3006. Info.CCEDiag(E);
  3007. }
  3008. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3009. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3010. // Keep evaluating to see what we can do.
  3011. } else {
  3012. // FIXME: Allow folding of values of any literal type in all languages.
  3013. if (Info.checkingPotentialConstantExpression() &&
  3014. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3015. // The definition of this variable could be constexpr. We can't
  3016. // access it right now, but may be able to in future.
  3017. } else if (Info.getLangOpts().CPlusPlus11) {
  3018. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3019. Info.Note(VD->getLocation(), diag::note_declared_at);
  3020. } else {
  3021. Info.FFDiag(E);
  3022. }
  3023. return CompleteObject();
  3024. }
  3025. }
  3026. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3027. return CompleteObject();
  3028. } else {
  3029. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3030. if (!Frame) {
  3031. if (const MaterializeTemporaryExpr *MTE =
  3032. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  3033. assert(MTE->getStorageDuration() == SD_Static &&
  3034. "should have a frame for a non-global materialized temporary");
  3035. // Per C++1y [expr.const]p2:
  3036. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3037. // - a [...] glvalue of integral or enumeration type that refers to
  3038. // a non-volatile const object [...]
  3039. // [...]
  3040. // - a [...] glvalue of literal type that refers to a non-volatile
  3041. // object whose lifetime began within the evaluation of e.
  3042. //
  3043. // C++11 misses the 'began within the evaluation of e' check and
  3044. // instead allows all temporaries, including things like:
  3045. // int &&r = 1;
  3046. // int x = ++r;
  3047. // constexpr int k = r;
  3048. // Therefore we use the C++14 rules in C++11 too.
  3049. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  3050. const ValueDecl *ED = MTE->getExtendingDecl();
  3051. if (!(BaseType.isConstQualified() &&
  3052. BaseType->isIntegralOrEnumerationType()) &&
  3053. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  3054. if (!IsAccess)
  3055. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3056. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3057. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3058. return CompleteObject();
  3059. }
  3060. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3061. assert(BaseVal && "got reference to unevaluated temporary");
  3062. } else {
  3063. if (!IsAccess)
  3064. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3065. Info.FFDiag(E);
  3066. return CompleteObject();
  3067. }
  3068. } else {
  3069. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3070. assert(BaseVal && "missing value for temporary");
  3071. }
  3072. }
  3073. // In C++14, we can't safely access any mutable state when we might be
  3074. // evaluating after an unmodeled side effect.
  3075. //
  3076. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3077. // to be read here (but take care with 'mutable' fields).
  3078. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3079. Info.EvalStatus.HasSideEffects) ||
  3080. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3081. return CompleteObject();
  3082. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3083. }
  3084. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3085. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3086. /// glvalue referred to by an entity of reference type.
  3087. ///
  3088. /// \param Info - Information about the ongoing evaluation.
  3089. /// \param Conv - The expression for which we are performing the conversion.
  3090. /// Used for diagnostics.
  3091. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3092. /// case of a non-class type).
  3093. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3094. /// \param RVal - The produced value will be placed here.
  3095. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  3096. QualType Type,
  3097. const LValue &LVal, APValue &RVal) {
  3098. if (LVal.Designator.Invalid)
  3099. return false;
  3100. // Check for special cases where there is no existing APValue to look at.
  3101. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3102. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3103. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3104. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3105. // initializer until now for such expressions. Such an expression can't be
  3106. // an ICE in C, so this only matters for fold.
  3107. if (Type.isVolatileQualified()) {
  3108. Info.FFDiag(Conv);
  3109. return false;
  3110. }
  3111. APValue Lit;
  3112. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3113. return false;
  3114. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3115. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  3116. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3117. // Special-case character extraction so we don't have to construct an
  3118. // APValue for the whole string.
  3119. assert(LVal.Designator.Entries.size() <= 1 &&
  3120. "Can only read characters from string literals");
  3121. if (LVal.Designator.Entries.empty()) {
  3122. // Fail for now for LValue to RValue conversion of an array.
  3123. // (This shouldn't show up in C/C++, but it could be triggered by a
  3124. // weird EvaluateAsRValue call from a tool.)
  3125. Info.FFDiag(Conv);
  3126. return false;
  3127. }
  3128. if (LVal.Designator.isOnePastTheEnd()) {
  3129. if (Info.getLangOpts().CPlusPlus11)
  3130. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
  3131. else
  3132. Info.FFDiag(Conv);
  3133. return false;
  3134. }
  3135. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3136. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3137. return true;
  3138. }
  3139. }
  3140. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3141. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3142. }
  3143. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3144. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3145. QualType LValType, APValue &Val) {
  3146. if (LVal.Designator.Invalid)
  3147. return false;
  3148. if (!Info.getLangOpts().CPlusPlus14) {
  3149. Info.FFDiag(E);
  3150. return false;
  3151. }
  3152. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3153. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3154. }
  3155. namespace {
  3156. struct CompoundAssignSubobjectHandler {
  3157. EvalInfo &Info;
  3158. const Expr *E;
  3159. QualType PromotedLHSType;
  3160. BinaryOperatorKind Opcode;
  3161. const APValue &RHS;
  3162. static const AccessKinds AccessKind = AK_Assign;
  3163. typedef bool result_type;
  3164. bool checkConst(QualType QT) {
  3165. // Assigning to a const object has undefined behavior.
  3166. if (QT.isConstQualified()) {
  3167. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3168. return false;
  3169. }
  3170. return true;
  3171. }
  3172. bool failed() { return false; }
  3173. bool found(APValue &Subobj, QualType SubobjType) {
  3174. switch (Subobj.getKind()) {
  3175. case APValue::Int:
  3176. return found(Subobj.getInt(), SubobjType);
  3177. case APValue::Float:
  3178. return found(Subobj.getFloat(), SubobjType);
  3179. case APValue::ComplexInt:
  3180. case APValue::ComplexFloat:
  3181. // FIXME: Implement complex compound assignment.
  3182. Info.FFDiag(E);
  3183. return false;
  3184. case APValue::LValue:
  3185. return foundPointer(Subobj, SubobjType);
  3186. default:
  3187. // FIXME: can this happen?
  3188. Info.FFDiag(E);
  3189. return false;
  3190. }
  3191. }
  3192. bool found(APSInt &Value, QualType SubobjType) {
  3193. if (!checkConst(SubobjType))
  3194. return false;
  3195. if (!SubobjType->isIntegerType()) {
  3196. // We don't support compound assignment on integer-cast-to-pointer
  3197. // values.
  3198. Info.FFDiag(E);
  3199. return false;
  3200. }
  3201. if (RHS.isInt()) {
  3202. APSInt LHS =
  3203. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3204. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3205. return false;
  3206. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3207. return true;
  3208. } else if (RHS.isFloat()) {
  3209. APFloat FValue(0.0);
  3210. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3211. FValue) &&
  3212. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3213. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3214. Value);
  3215. }
  3216. Info.FFDiag(E);
  3217. return false;
  3218. }
  3219. bool found(APFloat &Value, QualType SubobjType) {
  3220. return checkConst(SubobjType) &&
  3221. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3222. Value) &&
  3223. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3224. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3225. }
  3226. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3227. if (!checkConst(SubobjType))
  3228. return false;
  3229. QualType PointeeType;
  3230. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3231. PointeeType = PT->getPointeeType();
  3232. if (PointeeType.isNull() || !RHS.isInt() ||
  3233. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3234. Info.FFDiag(E);
  3235. return false;
  3236. }
  3237. APSInt Offset = RHS.getInt();
  3238. if (Opcode == BO_Sub)
  3239. negateAsSigned(Offset);
  3240. LValue LVal;
  3241. LVal.setFrom(Info.Ctx, Subobj);
  3242. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3243. return false;
  3244. LVal.moveInto(Subobj);
  3245. return true;
  3246. }
  3247. };
  3248. } // end anonymous namespace
  3249. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3250. /// Perform a compound assignment of LVal <op>= RVal.
  3251. static bool handleCompoundAssignment(
  3252. EvalInfo &Info, const Expr *E,
  3253. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3254. BinaryOperatorKind Opcode, const APValue &RVal) {
  3255. if (LVal.Designator.Invalid)
  3256. return false;
  3257. if (!Info.getLangOpts().CPlusPlus14) {
  3258. Info.FFDiag(E);
  3259. return false;
  3260. }
  3261. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3262. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3263. RVal };
  3264. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3265. }
  3266. namespace {
  3267. struct IncDecSubobjectHandler {
  3268. EvalInfo &Info;
  3269. const UnaryOperator *E;
  3270. AccessKinds AccessKind;
  3271. APValue *Old;
  3272. typedef bool result_type;
  3273. bool checkConst(QualType QT) {
  3274. // Assigning to a const object has undefined behavior.
  3275. if (QT.isConstQualified()) {
  3276. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3277. return false;
  3278. }
  3279. return true;
  3280. }
  3281. bool failed() { return false; }
  3282. bool found(APValue &Subobj, QualType SubobjType) {
  3283. // Stash the old value. Also clear Old, so we don't clobber it later
  3284. // if we're post-incrementing a complex.
  3285. if (Old) {
  3286. *Old = Subobj;
  3287. Old = nullptr;
  3288. }
  3289. switch (Subobj.getKind()) {
  3290. case APValue::Int:
  3291. return found(Subobj.getInt(), SubobjType);
  3292. case APValue::Float:
  3293. return found(Subobj.getFloat(), SubobjType);
  3294. case APValue::ComplexInt:
  3295. return found(Subobj.getComplexIntReal(),
  3296. SubobjType->castAs<ComplexType>()->getElementType()
  3297. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3298. case APValue::ComplexFloat:
  3299. return found(Subobj.getComplexFloatReal(),
  3300. SubobjType->castAs<ComplexType>()->getElementType()
  3301. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3302. case APValue::LValue:
  3303. return foundPointer(Subobj, SubobjType);
  3304. default:
  3305. // FIXME: can this happen?
  3306. Info.FFDiag(E);
  3307. return false;
  3308. }
  3309. }
  3310. bool found(APSInt &Value, QualType SubobjType) {
  3311. if (!checkConst(SubobjType))
  3312. return false;
  3313. if (!SubobjType->isIntegerType()) {
  3314. // We don't support increment / decrement on integer-cast-to-pointer
  3315. // values.
  3316. Info.FFDiag(E);
  3317. return false;
  3318. }
  3319. if (Old) *Old = APValue(Value);
  3320. // bool arithmetic promotes to int, and the conversion back to bool
  3321. // doesn't reduce mod 2^n, so special-case it.
  3322. if (SubobjType->isBooleanType()) {
  3323. if (AccessKind == AK_Increment)
  3324. Value = 1;
  3325. else
  3326. Value = !Value;
  3327. return true;
  3328. }
  3329. bool WasNegative = Value.isNegative();
  3330. if (AccessKind == AK_Increment) {
  3331. ++Value;
  3332. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3333. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3334. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3335. }
  3336. } else {
  3337. --Value;
  3338. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3339. unsigned BitWidth = Value.getBitWidth();
  3340. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3341. ActualValue.setBit(BitWidth);
  3342. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3343. }
  3344. }
  3345. return true;
  3346. }
  3347. bool found(APFloat &Value, QualType SubobjType) {
  3348. if (!checkConst(SubobjType))
  3349. return false;
  3350. if (Old) *Old = APValue(Value);
  3351. APFloat One(Value.getSemantics(), 1);
  3352. if (AccessKind == AK_Increment)
  3353. Value.add(One, APFloat::rmNearestTiesToEven);
  3354. else
  3355. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3356. return true;
  3357. }
  3358. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3359. if (!checkConst(SubobjType))
  3360. return false;
  3361. QualType PointeeType;
  3362. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3363. PointeeType = PT->getPointeeType();
  3364. else {
  3365. Info.FFDiag(E);
  3366. return false;
  3367. }
  3368. LValue LVal;
  3369. LVal.setFrom(Info.Ctx, Subobj);
  3370. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3371. AccessKind == AK_Increment ? 1 : -1))
  3372. return false;
  3373. LVal.moveInto(Subobj);
  3374. return true;
  3375. }
  3376. };
  3377. } // end anonymous namespace
  3378. /// Perform an increment or decrement on LVal.
  3379. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3380. QualType LValType, bool IsIncrement, APValue *Old) {
  3381. if (LVal.Designator.Invalid)
  3382. return false;
  3383. if (!Info.getLangOpts().CPlusPlus14) {
  3384. Info.FFDiag(E);
  3385. return false;
  3386. }
  3387. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3388. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3389. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3390. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3391. }
  3392. /// Build an lvalue for the object argument of a member function call.
  3393. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3394. LValue &This) {
  3395. if (Object->getType()->isPointerType())
  3396. return EvaluatePointer(Object, This, Info);
  3397. if (Object->isGLValue())
  3398. return EvaluateLValue(Object, This, Info);
  3399. if (Object->getType()->isLiteralType(Info.Ctx))
  3400. return EvaluateTemporary(Object, This, Info);
  3401. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3402. return false;
  3403. }
  3404. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3405. /// lvalue referring to the result.
  3406. ///
  3407. /// \param Info - Information about the ongoing evaluation.
  3408. /// \param LV - An lvalue referring to the base of the member pointer.
  3409. /// \param RHS - The member pointer expression.
  3410. /// \param IncludeMember - Specifies whether the member itself is included in
  3411. /// the resulting LValue subobject designator. This is not possible when
  3412. /// creating a bound member function.
  3413. /// \return The field or method declaration to which the member pointer refers,
  3414. /// or 0 if evaluation fails.
  3415. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3416. QualType LVType,
  3417. LValue &LV,
  3418. const Expr *RHS,
  3419. bool IncludeMember = true) {
  3420. MemberPtr MemPtr;
  3421. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3422. return nullptr;
  3423. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3424. // member value, the behavior is undefined.
  3425. if (!MemPtr.getDecl()) {
  3426. // FIXME: Specific diagnostic.
  3427. Info.FFDiag(RHS);
  3428. return nullptr;
  3429. }
  3430. if (MemPtr.isDerivedMember()) {
  3431. // This is a member of some derived class. Truncate LV appropriately.
  3432. // The end of the derived-to-base path for the base object must match the
  3433. // derived-to-base path for the member pointer.
  3434. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3435. LV.Designator.Entries.size()) {
  3436. Info.FFDiag(RHS);
  3437. return nullptr;
  3438. }
  3439. unsigned PathLengthToMember =
  3440. LV.Designator.Entries.size() - MemPtr.Path.size();
  3441. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3442. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3443. LV.Designator.Entries[PathLengthToMember + I]);
  3444. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3445. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3446. Info.FFDiag(RHS);
  3447. return nullptr;
  3448. }
  3449. }
  3450. // Truncate the lvalue to the appropriate derived class.
  3451. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3452. PathLengthToMember))
  3453. return nullptr;
  3454. } else if (!MemPtr.Path.empty()) {
  3455. // Extend the LValue path with the member pointer's path.
  3456. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3457. MemPtr.Path.size() + IncludeMember);
  3458. // Walk down to the appropriate base class.
  3459. if (const PointerType *PT = LVType->getAs<PointerType>())
  3460. LVType = PT->getPointeeType();
  3461. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3462. assert(RD && "member pointer access on non-class-type expression");
  3463. // The first class in the path is that of the lvalue.
  3464. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3465. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3466. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3467. return nullptr;
  3468. RD = Base;
  3469. }
  3470. // Finally cast to the class containing the member.
  3471. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3472. MemPtr.getContainingRecord()))
  3473. return nullptr;
  3474. }
  3475. // Add the member. Note that we cannot build bound member functions here.
  3476. if (IncludeMember) {
  3477. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3478. if (!HandleLValueMember(Info, RHS, LV, FD))
  3479. return nullptr;
  3480. } else if (const IndirectFieldDecl *IFD =
  3481. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3482. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3483. return nullptr;
  3484. } else {
  3485. llvm_unreachable("can't construct reference to bound member function");
  3486. }
  3487. }
  3488. return MemPtr.getDecl();
  3489. }
  3490. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3491. const BinaryOperator *BO,
  3492. LValue &LV,
  3493. bool IncludeMember = true) {
  3494. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3495. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3496. if (Info.noteFailure()) {
  3497. MemberPtr MemPtr;
  3498. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3499. }
  3500. return nullptr;
  3501. }
  3502. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3503. BO->getRHS(), IncludeMember);
  3504. }
  3505. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3506. /// the provided lvalue, which currently refers to the base object.
  3507. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3508. LValue &Result) {
  3509. SubobjectDesignator &D = Result.Designator;
  3510. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3511. return false;
  3512. QualType TargetQT = E->getType();
  3513. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3514. TargetQT = PT->getPointeeType();
  3515. // Check this cast lands within the final derived-to-base subobject path.
  3516. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3517. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3518. << D.MostDerivedType << TargetQT;
  3519. return false;
  3520. }
  3521. // Check the type of the final cast. We don't need to check the path,
  3522. // since a cast can only be formed if the path is unique.
  3523. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3524. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3525. const CXXRecordDecl *FinalType;
  3526. if (NewEntriesSize == D.MostDerivedPathLength)
  3527. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3528. else
  3529. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3530. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3531. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3532. << D.MostDerivedType << TargetQT;
  3533. return false;
  3534. }
  3535. // Truncate the lvalue to the appropriate derived class.
  3536. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3537. }
  3538. namespace {
  3539. enum EvalStmtResult {
  3540. /// Evaluation failed.
  3541. ESR_Failed,
  3542. /// Hit a 'return' statement.
  3543. ESR_Returned,
  3544. /// Evaluation succeeded.
  3545. ESR_Succeeded,
  3546. /// Hit a 'continue' statement.
  3547. ESR_Continue,
  3548. /// Hit a 'break' statement.
  3549. ESR_Break,
  3550. /// Still scanning for 'case' or 'default' statement.
  3551. ESR_CaseNotFound
  3552. };
  3553. }
  3554. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3555. // We don't need to evaluate the initializer for a static local.
  3556. if (!VD->hasLocalStorage())
  3557. return true;
  3558. LValue Result;
  3559. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3560. const Expr *InitE = VD->getInit();
  3561. if (!InitE) {
  3562. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3563. << false << VD->getType();
  3564. Val = APValue();
  3565. return false;
  3566. }
  3567. if (InitE->isValueDependent())
  3568. return false;
  3569. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3570. // Wipe out any partially-computed value, to allow tracking that this
  3571. // evaluation failed.
  3572. Val = APValue();
  3573. return false;
  3574. }
  3575. return true;
  3576. }
  3577. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3578. bool OK = true;
  3579. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3580. OK &= EvaluateVarDecl(Info, VD);
  3581. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3582. for (auto *BD : DD->bindings())
  3583. if (auto *VD = BD->getHoldingVar())
  3584. OK &= EvaluateDecl(Info, VD);
  3585. return OK;
  3586. }
  3587. /// Evaluate a condition (either a variable declaration or an expression).
  3588. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3589. const Expr *Cond, bool &Result) {
  3590. FullExpressionRAII Scope(Info);
  3591. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3592. return false;
  3593. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3594. }
  3595. namespace {
  3596. /// A location where the result (returned value) of evaluating a
  3597. /// statement should be stored.
  3598. struct StmtResult {
  3599. /// The APValue that should be filled in with the returned value.
  3600. APValue &Value;
  3601. /// The location containing the result, if any (used to support RVO).
  3602. const LValue *Slot;
  3603. };
  3604. struct TempVersionRAII {
  3605. CallStackFrame &Frame;
  3606. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3607. Frame.pushTempVersion();
  3608. }
  3609. ~TempVersionRAII() {
  3610. Frame.popTempVersion();
  3611. }
  3612. };
  3613. }
  3614. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3615. const Stmt *S,
  3616. const SwitchCase *SC = nullptr);
  3617. /// Evaluate the body of a loop, and translate the result as appropriate.
  3618. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3619. const Stmt *Body,
  3620. const SwitchCase *Case = nullptr) {
  3621. BlockScopeRAII Scope(Info);
  3622. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3623. case ESR_Break:
  3624. return ESR_Succeeded;
  3625. case ESR_Succeeded:
  3626. case ESR_Continue:
  3627. return ESR_Continue;
  3628. case ESR_Failed:
  3629. case ESR_Returned:
  3630. case ESR_CaseNotFound:
  3631. return ESR;
  3632. }
  3633. llvm_unreachable("Invalid EvalStmtResult!");
  3634. }
  3635. /// Evaluate a switch statement.
  3636. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3637. const SwitchStmt *SS) {
  3638. BlockScopeRAII Scope(Info);
  3639. // Evaluate the switch condition.
  3640. APSInt Value;
  3641. {
  3642. FullExpressionRAII Scope(Info);
  3643. if (const Stmt *Init = SS->getInit()) {
  3644. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3645. if (ESR != ESR_Succeeded)
  3646. return ESR;
  3647. }
  3648. if (SS->getConditionVariable() &&
  3649. !EvaluateDecl(Info, SS->getConditionVariable()))
  3650. return ESR_Failed;
  3651. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3652. return ESR_Failed;
  3653. }
  3654. // Find the switch case corresponding to the value of the condition.
  3655. // FIXME: Cache this lookup.
  3656. const SwitchCase *Found = nullptr;
  3657. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3658. SC = SC->getNextSwitchCase()) {
  3659. if (isa<DefaultStmt>(SC)) {
  3660. Found = SC;
  3661. continue;
  3662. }
  3663. const CaseStmt *CS = cast<CaseStmt>(SC);
  3664. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3665. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3666. : LHS;
  3667. if (LHS <= Value && Value <= RHS) {
  3668. Found = SC;
  3669. break;
  3670. }
  3671. }
  3672. if (!Found)
  3673. return ESR_Succeeded;
  3674. // Search the switch body for the switch case and evaluate it from there.
  3675. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3676. case ESR_Break:
  3677. return ESR_Succeeded;
  3678. case ESR_Succeeded:
  3679. case ESR_Continue:
  3680. case ESR_Failed:
  3681. case ESR_Returned:
  3682. return ESR;
  3683. case ESR_CaseNotFound:
  3684. // This can only happen if the switch case is nested within a statement
  3685. // expression. We have no intention of supporting that.
  3686. Info.FFDiag(Found->getBeginLoc(),
  3687. diag::note_constexpr_stmt_expr_unsupported);
  3688. return ESR_Failed;
  3689. }
  3690. llvm_unreachable("Invalid EvalStmtResult!");
  3691. }
  3692. // Evaluate a statement.
  3693. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3694. const Stmt *S, const SwitchCase *Case) {
  3695. if (!Info.nextStep(S))
  3696. return ESR_Failed;
  3697. // If we're hunting down a 'case' or 'default' label, recurse through
  3698. // substatements until we hit the label.
  3699. if (Case) {
  3700. // FIXME: We don't start the lifetime of objects whose initialization we
  3701. // jump over. However, such objects must be of class type with a trivial
  3702. // default constructor that initialize all subobjects, so must be empty,
  3703. // so this almost never matters.
  3704. switch (S->getStmtClass()) {
  3705. case Stmt::CompoundStmtClass:
  3706. // FIXME: Precompute which substatement of a compound statement we
  3707. // would jump to, and go straight there rather than performing a
  3708. // linear scan each time.
  3709. case Stmt::LabelStmtClass:
  3710. case Stmt::AttributedStmtClass:
  3711. case Stmt::DoStmtClass:
  3712. break;
  3713. case Stmt::CaseStmtClass:
  3714. case Stmt::DefaultStmtClass:
  3715. if (Case == S)
  3716. Case = nullptr;
  3717. break;
  3718. case Stmt::IfStmtClass: {
  3719. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3720. // straight there rather than scanning both sides.
  3721. const IfStmt *IS = cast<IfStmt>(S);
  3722. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3723. // preceded by our switch label.
  3724. BlockScopeRAII Scope(Info);
  3725. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3726. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3727. return ESR;
  3728. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3729. }
  3730. case Stmt::WhileStmtClass: {
  3731. EvalStmtResult ESR =
  3732. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3733. if (ESR != ESR_Continue)
  3734. return ESR;
  3735. break;
  3736. }
  3737. case Stmt::ForStmtClass: {
  3738. const ForStmt *FS = cast<ForStmt>(S);
  3739. EvalStmtResult ESR =
  3740. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3741. if (ESR != ESR_Continue)
  3742. return ESR;
  3743. if (FS->getInc()) {
  3744. FullExpressionRAII IncScope(Info);
  3745. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3746. return ESR_Failed;
  3747. }
  3748. break;
  3749. }
  3750. case Stmt::DeclStmtClass:
  3751. // FIXME: If the variable has initialization that can't be jumped over,
  3752. // bail out of any immediately-surrounding compound-statement too.
  3753. default:
  3754. return ESR_CaseNotFound;
  3755. }
  3756. }
  3757. switch (S->getStmtClass()) {
  3758. default:
  3759. if (const Expr *E = dyn_cast<Expr>(S)) {
  3760. // Don't bother evaluating beyond an expression-statement which couldn't
  3761. // be evaluated.
  3762. FullExpressionRAII Scope(Info);
  3763. if (!EvaluateIgnoredValue(Info, E))
  3764. return ESR_Failed;
  3765. return ESR_Succeeded;
  3766. }
  3767. Info.FFDiag(S->getBeginLoc());
  3768. return ESR_Failed;
  3769. case Stmt::NullStmtClass:
  3770. return ESR_Succeeded;
  3771. case Stmt::DeclStmtClass: {
  3772. const DeclStmt *DS = cast<DeclStmt>(S);
  3773. for (const auto *DclIt : DS->decls()) {
  3774. // Each declaration initialization is its own full-expression.
  3775. // FIXME: This isn't quite right; if we're performing aggregate
  3776. // initialization, each braced subexpression is its own full-expression.
  3777. FullExpressionRAII Scope(Info);
  3778. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3779. return ESR_Failed;
  3780. }
  3781. return ESR_Succeeded;
  3782. }
  3783. case Stmt::ReturnStmtClass: {
  3784. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3785. FullExpressionRAII Scope(Info);
  3786. if (RetExpr &&
  3787. !(Result.Slot
  3788. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3789. : Evaluate(Result.Value, Info, RetExpr)))
  3790. return ESR_Failed;
  3791. return ESR_Returned;
  3792. }
  3793. case Stmt::CompoundStmtClass: {
  3794. BlockScopeRAII Scope(Info);
  3795. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3796. for (const auto *BI : CS->body()) {
  3797. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3798. if (ESR == ESR_Succeeded)
  3799. Case = nullptr;
  3800. else if (ESR != ESR_CaseNotFound)
  3801. return ESR;
  3802. }
  3803. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3804. }
  3805. case Stmt::IfStmtClass: {
  3806. const IfStmt *IS = cast<IfStmt>(S);
  3807. // Evaluate the condition, as either a var decl or as an expression.
  3808. BlockScopeRAII Scope(Info);
  3809. if (const Stmt *Init = IS->getInit()) {
  3810. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3811. if (ESR != ESR_Succeeded)
  3812. return ESR;
  3813. }
  3814. bool Cond;
  3815. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3816. return ESR_Failed;
  3817. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3818. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3819. if (ESR != ESR_Succeeded)
  3820. return ESR;
  3821. }
  3822. return ESR_Succeeded;
  3823. }
  3824. case Stmt::WhileStmtClass: {
  3825. const WhileStmt *WS = cast<WhileStmt>(S);
  3826. while (true) {
  3827. BlockScopeRAII Scope(Info);
  3828. bool Continue;
  3829. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3830. Continue))
  3831. return ESR_Failed;
  3832. if (!Continue)
  3833. break;
  3834. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3835. if (ESR != ESR_Continue)
  3836. return ESR;
  3837. }
  3838. return ESR_Succeeded;
  3839. }
  3840. case Stmt::DoStmtClass: {
  3841. const DoStmt *DS = cast<DoStmt>(S);
  3842. bool Continue;
  3843. do {
  3844. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3845. if (ESR != ESR_Continue)
  3846. return ESR;
  3847. Case = nullptr;
  3848. FullExpressionRAII CondScope(Info);
  3849. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3850. return ESR_Failed;
  3851. } while (Continue);
  3852. return ESR_Succeeded;
  3853. }
  3854. case Stmt::ForStmtClass: {
  3855. const ForStmt *FS = cast<ForStmt>(S);
  3856. BlockScopeRAII Scope(Info);
  3857. if (FS->getInit()) {
  3858. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3859. if (ESR != ESR_Succeeded)
  3860. return ESR;
  3861. }
  3862. while (true) {
  3863. BlockScopeRAII Scope(Info);
  3864. bool Continue = true;
  3865. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3866. FS->getCond(), Continue))
  3867. return ESR_Failed;
  3868. if (!Continue)
  3869. break;
  3870. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3871. if (ESR != ESR_Continue)
  3872. return ESR;
  3873. if (FS->getInc()) {
  3874. FullExpressionRAII IncScope(Info);
  3875. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3876. return ESR_Failed;
  3877. }
  3878. }
  3879. return ESR_Succeeded;
  3880. }
  3881. case Stmt::CXXForRangeStmtClass: {
  3882. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3883. BlockScopeRAII Scope(Info);
  3884. // Evaluate the init-statement if present.
  3885. if (FS->getInit()) {
  3886. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3887. if (ESR != ESR_Succeeded)
  3888. return ESR;
  3889. }
  3890. // Initialize the __range variable.
  3891. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3892. if (ESR != ESR_Succeeded)
  3893. return ESR;
  3894. // Create the __begin and __end iterators.
  3895. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3896. if (ESR != ESR_Succeeded)
  3897. return ESR;
  3898. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3899. if (ESR != ESR_Succeeded)
  3900. return ESR;
  3901. while (true) {
  3902. // Condition: __begin != __end.
  3903. {
  3904. bool Continue = true;
  3905. FullExpressionRAII CondExpr(Info);
  3906. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3907. return ESR_Failed;
  3908. if (!Continue)
  3909. break;
  3910. }
  3911. // User's variable declaration, initialized by *__begin.
  3912. BlockScopeRAII InnerScope(Info);
  3913. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3914. if (ESR != ESR_Succeeded)
  3915. return ESR;
  3916. // Loop body.
  3917. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3918. if (ESR != ESR_Continue)
  3919. return ESR;
  3920. // Increment: ++__begin
  3921. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3922. return ESR_Failed;
  3923. }
  3924. return ESR_Succeeded;
  3925. }
  3926. case Stmt::SwitchStmtClass:
  3927. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3928. case Stmt::ContinueStmtClass:
  3929. return ESR_Continue;
  3930. case Stmt::BreakStmtClass:
  3931. return ESR_Break;
  3932. case Stmt::LabelStmtClass:
  3933. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3934. case Stmt::AttributedStmtClass:
  3935. // As a general principle, C++11 attributes can be ignored without
  3936. // any semantic impact.
  3937. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3938. Case);
  3939. case Stmt::CaseStmtClass:
  3940. case Stmt::DefaultStmtClass:
  3941. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3942. case Stmt::CXXTryStmtClass:
  3943. // Evaluate try blocks by evaluating all sub statements.
  3944. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  3945. }
  3946. }
  3947. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3948. /// default constructor. If so, we'll fold it whether or not it's marked as
  3949. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3950. /// so we need special handling.
  3951. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  3952. const CXXConstructorDecl *CD,
  3953. bool IsValueInitialization) {
  3954. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  3955. return false;
  3956. // Value-initialization does not call a trivial default constructor, so such a
  3957. // call is a core constant expression whether or not the constructor is
  3958. // constexpr.
  3959. if (!CD->isConstexpr() && !IsValueInitialization) {
  3960. if (Info.getLangOpts().CPlusPlus11) {
  3961. // FIXME: If DiagDecl is an implicitly-declared special member function,
  3962. // we should be much more explicit about why it's not constexpr.
  3963. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  3964. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  3965. Info.Note(CD->getLocation(), diag::note_declared_at);
  3966. } else {
  3967. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  3968. }
  3969. }
  3970. return true;
  3971. }
  3972. /// CheckConstexprFunction - Check that a function can be called in a constant
  3973. /// expression.
  3974. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  3975. const FunctionDecl *Declaration,
  3976. const FunctionDecl *Definition,
  3977. const Stmt *Body) {
  3978. // Potential constant expressions can contain calls to declared, but not yet
  3979. // defined, constexpr functions.
  3980. if (Info.checkingPotentialConstantExpression() && !Definition &&
  3981. Declaration->isConstexpr())
  3982. return false;
  3983. // Bail out if the function declaration itself is invalid. We will
  3984. // have produced a relevant diagnostic while parsing it, so just
  3985. // note the problematic sub-expression.
  3986. if (Declaration->isInvalidDecl()) {
  3987. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3988. return false;
  3989. }
  3990. // DR1872: An instantiated virtual constexpr function can't be called in a
  3991. // constant expression (prior to C++20). We can still constant-fold such a
  3992. // call.
  3993. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  3994. cast<CXXMethodDecl>(Declaration)->isVirtual())
  3995. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  3996. if (Definition && Definition->isInvalidDecl()) {
  3997. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  3998. return false;
  3999. }
  4000. // Can we evaluate this function call?
  4001. if (Definition && Definition->isConstexpr() && Body)
  4002. return true;
  4003. if (Info.getLangOpts().CPlusPlus11) {
  4004. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4005. // If this function is not constexpr because it is an inherited
  4006. // non-constexpr constructor, diagnose that directly.
  4007. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4008. if (CD && CD->isInheritingConstructor()) {
  4009. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4010. if (!Inherited->isConstexpr())
  4011. DiagDecl = CD = Inherited;
  4012. }
  4013. // FIXME: If DiagDecl is an implicitly-declared special member function
  4014. // or an inheriting constructor, we should be much more explicit about why
  4015. // it's not constexpr.
  4016. if (CD && CD->isInheritingConstructor())
  4017. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4018. << CD->getInheritedConstructor().getConstructor()->getParent();
  4019. else
  4020. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4021. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4022. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4023. } else {
  4024. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4025. }
  4026. return false;
  4027. }
  4028. namespace {
  4029. struct CheckDynamicTypeHandler {
  4030. AccessKinds AccessKind;
  4031. typedef bool result_type;
  4032. bool failed() { return false; }
  4033. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4034. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4035. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4036. };
  4037. } // end anonymous namespace
  4038. /// Check that we can access the notional vptr of an object / determine its
  4039. /// dynamic type.
  4040. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4041. AccessKinds AK, bool Polymorphic) {
  4042. if (This.Designator.Invalid)
  4043. return false;
  4044. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4045. if (!Obj)
  4046. return false;
  4047. if (!Obj.Value) {
  4048. // The object is not usable in constant expressions, so we can't inspect
  4049. // its value to see if it's in-lifetime or what the active union members
  4050. // are. We can still check for a one-past-the-end lvalue.
  4051. if (This.Designator.isOnePastTheEnd() ||
  4052. This.Designator.isMostDerivedAnUnsizedArray()) {
  4053. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4054. ? diag::note_constexpr_access_past_end
  4055. : diag::note_constexpr_access_unsized_array)
  4056. << AK;
  4057. return false;
  4058. } else if (Polymorphic) {
  4059. // Conservatively refuse to perform a polymorphic operation if we would
  4060. // not be able to read a notional 'vptr' value.
  4061. APValue Val;
  4062. This.moveInto(Val);
  4063. QualType StarThisType =
  4064. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4065. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4066. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4067. return false;
  4068. }
  4069. return true;
  4070. }
  4071. CheckDynamicTypeHandler Handler{AK};
  4072. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4073. }
  4074. /// Check that the pointee of the 'this' pointer in a member function call is
  4075. /// either within its lifetime or in its period of construction or destruction.
  4076. static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4077. const LValue &This) {
  4078. return checkDynamicType(Info, E, This, AK_MemberCall, false);
  4079. }
  4080. struct DynamicType {
  4081. /// The dynamic class type of the object.
  4082. const CXXRecordDecl *Type;
  4083. /// The corresponding path length in the lvalue.
  4084. unsigned PathLength;
  4085. };
  4086. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4087. unsigned PathLength) {
  4088. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4089. Designator.Entries.size() && "invalid path length");
  4090. return (PathLength == Designator.MostDerivedPathLength)
  4091. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4092. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4093. }
  4094. /// Determine the dynamic type of an object.
  4095. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4096. LValue &This, AccessKinds AK) {
  4097. // If we don't have an lvalue denoting an object of class type, there is no
  4098. // meaningful dynamic type. (We consider objects of non-class type to have no
  4099. // dynamic type.)
  4100. if (!checkDynamicType(Info, E, This, AK, true))
  4101. return None;
  4102. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4103. // shouldn't happen other than in constant-folding situations, since literal
  4104. // types can't have virtual bases.
  4105. //
  4106. // Note that consumers of DynamicType assume that the type has no virtual
  4107. // bases, and will need modifications if this restriction is relaxed.
  4108. const CXXRecordDecl *Class =
  4109. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4110. if (!Class || Class->getNumVBases()) {
  4111. Info.FFDiag(E);
  4112. return None;
  4113. }
  4114. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4115. // binary search here instead. But the overwhelmingly common case is that
  4116. // we're not in the middle of a constructor, so it probably doesn't matter
  4117. // in practice.
  4118. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4119. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4120. PathLength <= Path.size(); ++PathLength) {
  4121. switch (Info.isEvaluatingConstructor(This.getLValueBase(),
  4122. Path.slice(0, PathLength))) {
  4123. case ConstructionPhase::Bases:
  4124. // We're constructing a base class. This is not the dynamic type.
  4125. break;
  4126. case ConstructionPhase::None:
  4127. case ConstructionPhase::AfterBases:
  4128. // We've finished constructing the base classes, so this is the dynamic
  4129. // type.
  4130. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4131. PathLength};
  4132. }
  4133. }
  4134. // CWG issue 1517: we're constructing a base class of the object described by
  4135. // 'This', so that object has not yet begun its period of construction and
  4136. // any polymorphic operation on it results in undefined behavior.
  4137. Info.FFDiag(E);
  4138. return None;
  4139. }
  4140. /// Perform virtual dispatch.
  4141. static const CXXMethodDecl *HandleVirtualDispatch(
  4142. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4143. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4144. Optional<DynamicType> DynType =
  4145. ComputeDynamicType(Info, E, This, AK_MemberCall);
  4146. if (!DynType)
  4147. return nullptr;
  4148. // Find the final overrider. It must be declared in one of the classes on the
  4149. // path from the dynamic type to the static type.
  4150. // FIXME: If we ever allow literal types to have virtual base classes, that
  4151. // won't be true.
  4152. const CXXMethodDecl *Callee = Found;
  4153. unsigned PathLength = DynType->PathLength;
  4154. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4155. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4156. const CXXMethodDecl *Overrider =
  4157. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4158. if (Overrider) {
  4159. Callee = Overrider;
  4160. break;
  4161. }
  4162. }
  4163. // C++2a [class.abstract]p6:
  4164. // the effect of making a virtual call to a pure virtual function [...] is
  4165. // undefined
  4166. if (Callee->isPure()) {
  4167. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4168. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4169. return nullptr;
  4170. }
  4171. // If necessary, walk the rest of the path to determine the sequence of
  4172. // covariant adjustment steps to apply.
  4173. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4174. Found->getReturnType())) {
  4175. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4176. for (unsigned CovariantPathLength = PathLength + 1;
  4177. CovariantPathLength != This.Designator.Entries.size();
  4178. ++CovariantPathLength) {
  4179. const CXXRecordDecl *NextClass =
  4180. getBaseClassType(This.Designator, CovariantPathLength);
  4181. const CXXMethodDecl *Next =
  4182. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4183. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4184. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4185. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4186. }
  4187. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4188. CovariantAdjustmentPath.back()))
  4189. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4190. }
  4191. // Perform 'this' adjustment.
  4192. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4193. return nullptr;
  4194. return Callee;
  4195. }
  4196. /// Perform the adjustment from a value returned by a virtual function to
  4197. /// a value of the statically expected type, which may be a pointer or
  4198. /// reference to a base class of the returned type.
  4199. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4200. APValue &Result,
  4201. ArrayRef<QualType> Path) {
  4202. assert(Result.isLValue() &&
  4203. "unexpected kind of APValue for covariant return");
  4204. if (Result.isNullPointer())
  4205. return true;
  4206. LValue LVal;
  4207. LVal.setFrom(Info.Ctx, Result);
  4208. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4209. for (unsigned I = 1; I != Path.size(); ++I) {
  4210. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4211. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4212. if (OldClass != NewClass &&
  4213. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4214. return false;
  4215. OldClass = NewClass;
  4216. }
  4217. LVal.moveInto(Result);
  4218. return true;
  4219. }
  4220. /// Determine whether \p Base, which is known to be a direct base class of
  4221. /// \p Derived, is a public base class.
  4222. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4223. const CXXRecordDecl *Base) {
  4224. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4225. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4226. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4227. return BaseSpec.getAccessSpecifier() == AS_public;
  4228. }
  4229. llvm_unreachable("Base is not a direct base of Derived");
  4230. }
  4231. /// Apply the given dynamic cast operation on the provided lvalue.
  4232. ///
  4233. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4234. /// to find a suitable target subobject.
  4235. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4236. LValue &Ptr) {
  4237. // We can't do anything with a non-symbolic pointer value.
  4238. SubobjectDesignator &D = Ptr.Designator;
  4239. if (D.Invalid)
  4240. return false;
  4241. // C++ [expr.dynamic.cast]p6:
  4242. // If v is a null pointer value, the result is a null pointer value.
  4243. if (Ptr.isNullPointer() && !E->isGLValue())
  4244. return true;
  4245. // For all the other cases, we need the pointer to point to an object within
  4246. // its lifetime / period of construction / destruction, and we need to know
  4247. // its dynamic type.
  4248. Optional<DynamicType> DynType =
  4249. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4250. if (!DynType)
  4251. return false;
  4252. // C++ [expr.dynamic.cast]p7:
  4253. // If T is "pointer to cv void", then the result is a pointer to the most
  4254. // derived object
  4255. if (E->getType()->isVoidPointerType())
  4256. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4257. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4258. assert(C && "dynamic_cast target is not void pointer nor class");
  4259. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4260. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4261. // C++ [expr.dynamic.cast]p9:
  4262. if (!E->isGLValue()) {
  4263. // The value of a failed cast to pointer type is the null pointer value
  4264. // of the required result type.
  4265. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4266. Ptr.setNull(E->getType(), TargetVal);
  4267. return true;
  4268. }
  4269. // A failed cast to reference type throws [...] std::bad_cast.
  4270. unsigned DiagKind;
  4271. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4272. DynType->Type->isDerivedFrom(C)))
  4273. DiagKind = 0;
  4274. else if (!Paths || Paths->begin() == Paths->end())
  4275. DiagKind = 1;
  4276. else if (Paths->isAmbiguous(CQT))
  4277. DiagKind = 2;
  4278. else {
  4279. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4280. DiagKind = 3;
  4281. }
  4282. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4283. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4284. << Info.Ctx.getRecordType(DynType->Type)
  4285. << E->getType().getUnqualifiedType();
  4286. return false;
  4287. };
  4288. // Runtime check, phase 1:
  4289. // Walk from the base subobject towards the derived object looking for the
  4290. // target type.
  4291. for (int PathLength = Ptr.Designator.Entries.size();
  4292. PathLength >= (int)DynType->PathLength; --PathLength) {
  4293. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4294. if (declaresSameEntity(Class, C))
  4295. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4296. // We can only walk across public inheritance edges.
  4297. if (PathLength > (int)DynType->PathLength &&
  4298. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4299. Class))
  4300. return RuntimeCheckFailed(nullptr);
  4301. }
  4302. // Runtime check, phase 2:
  4303. // Search the dynamic type for an unambiguous public base of type C.
  4304. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4305. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4306. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4307. Paths.front().Access == AS_public) {
  4308. // Downcast to the dynamic type...
  4309. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4310. return false;
  4311. // ... then upcast to the chosen base class subobject.
  4312. for (CXXBasePathElement &Elem : Paths.front())
  4313. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4314. return false;
  4315. return true;
  4316. }
  4317. // Otherwise, the runtime check fails.
  4318. return RuntimeCheckFailed(&Paths);
  4319. }
  4320. /// Determine if a class has any fields that might need to be copied by a
  4321. /// trivial copy or move operation.
  4322. static bool hasFields(const CXXRecordDecl *RD) {
  4323. if (!RD || RD->isEmpty())
  4324. return false;
  4325. for (auto *FD : RD->fields()) {
  4326. if (FD->isUnnamedBitfield())
  4327. continue;
  4328. return true;
  4329. }
  4330. for (auto &Base : RD->bases())
  4331. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4332. return true;
  4333. return false;
  4334. }
  4335. namespace {
  4336. typedef SmallVector<APValue, 8> ArgVector;
  4337. }
  4338. /// EvaluateArgs - Evaluate the arguments to a function call.
  4339. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  4340. EvalInfo &Info) {
  4341. bool Success = true;
  4342. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4343. I != E; ++I) {
  4344. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4345. // If we're checking for a potential constant expression, evaluate all
  4346. // initializers even if some of them fail.
  4347. if (!Info.noteFailure())
  4348. return false;
  4349. Success = false;
  4350. }
  4351. }
  4352. return Success;
  4353. }
  4354. /// Evaluate a function call.
  4355. static bool HandleFunctionCall(SourceLocation CallLoc,
  4356. const FunctionDecl *Callee, const LValue *This,
  4357. ArrayRef<const Expr*> Args, const Stmt *Body,
  4358. EvalInfo &Info, APValue &Result,
  4359. const LValue *ResultSlot) {
  4360. ArgVector ArgValues(Args.size());
  4361. if (!EvaluateArgs(Args, ArgValues, Info))
  4362. return false;
  4363. if (!Info.CheckCallLimit(CallLoc))
  4364. return false;
  4365. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4366. // For a trivial copy or move assignment, perform an APValue copy. This is
  4367. // essential for unions, where the operations performed by the assignment
  4368. // operator cannot be represented as statements.
  4369. //
  4370. // Skip this for non-union classes with no fields; in that case, the defaulted
  4371. // copy/move does not actually read the object.
  4372. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4373. if (MD && MD->isDefaulted() &&
  4374. (MD->getParent()->isUnion() ||
  4375. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4376. assert(This &&
  4377. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4378. LValue RHS;
  4379. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4380. APValue RHSValue;
  4381. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  4382. RHS, RHSValue))
  4383. return false;
  4384. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4385. RHSValue))
  4386. return false;
  4387. This->moveInto(Result);
  4388. return true;
  4389. } else if (MD && isLambdaCallOperator(MD)) {
  4390. // We're in a lambda; determine the lambda capture field maps unless we're
  4391. // just constexpr checking a lambda's call operator. constexpr checking is
  4392. // done before the captures have been added to the closure object (unless
  4393. // we're inferring constexpr-ness), so we don't have access to them in this
  4394. // case. But since we don't need the captures to constexpr check, we can
  4395. // just ignore them.
  4396. if (!Info.checkingPotentialConstantExpression())
  4397. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4398. Frame.LambdaThisCaptureField);
  4399. }
  4400. StmtResult Ret = {Result, ResultSlot};
  4401. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4402. if (ESR == ESR_Succeeded) {
  4403. if (Callee->getReturnType()->isVoidType())
  4404. return true;
  4405. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4406. }
  4407. return ESR == ESR_Returned;
  4408. }
  4409. /// Evaluate a constructor call.
  4410. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4411. APValue *ArgValues,
  4412. const CXXConstructorDecl *Definition,
  4413. EvalInfo &Info, APValue &Result) {
  4414. SourceLocation CallLoc = E->getExprLoc();
  4415. if (!Info.CheckCallLimit(CallLoc))
  4416. return false;
  4417. const CXXRecordDecl *RD = Definition->getParent();
  4418. if (RD->getNumVBases()) {
  4419. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4420. return false;
  4421. }
  4422. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4423. Info,
  4424. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4425. RD->getNumBases());
  4426. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4427. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4428. // wasteful.
  4429. APValue RetVal;
  4430. StmtResult Ret = {RetVal, nullptr};
  4431. // If it's a delegating constructor, delegate.
  4432. if (Definition->isDelegatingConstructor()) {
  4433. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4434. {
  4435. FullExpressionRAII InitScope(Info);
  4436. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  4437. return false;
  4438. }
  4439. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4440. }
  4441. // For a trivial copy or move constructor, perform an APValue copy. This is
  4442. // essential for unions (or classes with anonymous union members), where the
  4443. // operations performed by the constructor cannot be represented by
  4444. // ctor-initializers.
  4445. //
  4446. // Skip this for empty non-union classes; we should not perform an
  4447. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4448. // actually read them.
  4449. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4450. (Definition->getParent()->isUnion() ||
  4451. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4452. LValue RHS;
  4453. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4454. return handleLValueToRValueConversion(
  4455. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4456. RHS, Result);
  4457. }
  4458. // Reserve space for the struct members.
  4459. if (!RD->isUnion() && Result.isUninit())
  4460. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4461. std::distance(RD->field_begin(), RD->field_end()));
  4462. if (RD->isInvalidDecl()) return false;
  4463. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4464. // A scope for temporaries lifetime-extended by reference members.
  4465. BlockScopeRAII LifetimeExtendedScope(Info);
  4466. bool Success = true;
  4467. unsigned BasesSeen = 0;
  4468. #ifndef NDEBUG
  4469. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4470. #endif
  4471. for (const auto *I : Definition->inits()) {
  4472. LValue Subobject = This;
  4473. LValue SubobjectParent = This;
  4474. APValue *Value = &Result;
  4475. // Determine the subobject to initialize.
  4476. FieldDecl *FD = nullptr;
  4477. if (I->isBaseInitializer()) {
  4478. QualType BaseType(I->getBaseClass(), 0);
  4479. #ifndef NDEBUG
  4480. // Non-virtual base classes are initialized in the order in the class
  4481. // definition. We have already checked for virtual base classes.
  4482. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4483. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4484. "base class initializers not in expected order");
  4485. ++BaseIt;
  4486. #endif
  4487. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4488. BaseType->getAsCXXRecordDecl(), &Layout))
  4489. return false;
  4490. Value = &Result.getStructBase(BasesSeen++);
  4491. } else if ((FD = I->getMember())) {
  4492. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4493. return false;
  4494. if (RD->isUnion()) {
  4495. Result = APValue(FD);
  4496. Value = &Result.getUnionValue();
  4497. } else {
  4498. Value = &Result.getStructField(FD->getFieldIndex());
  4499. }
  4500. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4501. // Walk the indirect field decl's chain to find the object to initialize,
  4502. // and make sure we've initialized every step along it.
  4503. auto IndirectFieldChain = IFD->chain();
  4504. for (auto *C : IndirectFieldChain) {
  4505. FD = cast<FieldDecl>(C);
  4506. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4507. // Switch the union field if it differs. This happens if we had
  4508. // preceding zero-initialization, and we're now initializing a union
  4509. // subobject other than the first.
  4510. // FIXME: In this case, the values of the other subobjects are
  4511. // specified, since zero-initialization sets all padding bits to zero.
  4512. if (Value->isUninit() ||
  4513. (Value->isUnion() && Value->getUnionField() != FD)) {
  4514. if (CD->isUnion())
  4515. *Value = APValue(FD);
  4516. else
  4517. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4518. std::distance(CD->field_begin(), CD->field_end()));
  4519. }
  4520. // Store Subobject as its parent before updating it for the last element
  4521. // in the chain.
  4522. if (C == IndirectFieldChain.back())
  4523. SubobjectParent = Subobject;
  4524. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4525. return false;
  4526. if (CD->isUnion())
  4527. Value = &Value->getUnionValue();
  4528. else
  4529. Value = &Value->getStructField(FD->getFieldIndex());
  4530. }
  4531. } else {
  4532. llvm_unreachable("unknown base initializer kind");
  4533. }
  4534. // Need to override This for implicit field initializers as in this case
  4535. // This refers to innermost anonymous struct/union containing initializer,
  4536. // not to currently constructed class.
  4537. const Expr *Init = I->getInit();
  4538. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4539. isa<CXXDefaultInitExpr>(Init));
  4540. FullExpressionRAII InitScope(Info);
  4541. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4542. (FD && FD->isBitField() &&
  4543. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4544. // If we're checking for a potential constant expression, evaluate all
  4545. // initializers even if some of them fail.
  4546. if (!Info.noteFailure())
  4547. return false;
  4548. Success = false;
  4549. }
  4550. // This is the point at which the dynamic type of the object becomes this
  4551. // class type.
  4552. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  4553. EvalObj.finishedConstructingBases();
  4554. }
  4555. return Success &&
  4556. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4557. }
  4558. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4559. ArrayRef<const Expr*> Args,
  4560. const CXXConstructorDecl *Definition,
  4561. EvalInfo &Info, APValue &Result) {
  4562. ArgVector ArgValues(Args.size());
  4563. if (!EvaluateArgs(Args, ArgValues, Info))
  4564. return false;
  4565. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4566. Info, Result);
  4567. }
  4568. //===----------------------------------------------------------------------===//
  4569. // Generic Evaluation
  4570. //===----------------------------------------------------------------------===//
  4571. namespace {
  4572. template <class Derived>
  4573. class ExprEvaluatorBase
  4574. : public ConstStmtVisitor<Derived, bool> {
  4575. private:
  4576. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4577. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4578. return getDerived().Success(V, E);
  4579. }
  4580. bool DerivedZeroInitialization(const Expr *E) {
  4581. return getDerived().ZeroInitialization(E);
  4582. }
  4583. // Check whether a conditional operator with a non-constant condition is a
  4584. // potential constant expression. If neither arm is a potential constant
  4585. // expression, then the conditional operator is not either.
  4586. template<typename ConditionalOperator>
  4587. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4588. assert(Info.checkingPotentialConstantExpression());
  4589. // Speculatively evaluate both arms.
  4590. SmallVector<PartialDiagnosticAt, 8> Diag;
  4591. {
  4592. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4593. StmtVisitorTy::Visit(E->getFalseExpr());
  4594. if (Diag.empty())
  4595. return;
  4596. }
  4597. {
  4598. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4599. Diag.clear();
  4600. StmtVisitorTy::Visit(E->getTrueExpr());
  4601. if (Diag.empty())
  4602. return;
  4603. }
  4604. Error(E, diag::note_constexpr_conditional_never_const);
  4605. }
  4606. template<typename ConditionalOperator>
  4607. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4608. bool BoolResult;
  4609. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4610. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4611. CheckPotentialConstantConditional(E);
  4612. return false;
  4613. }
  4614. if (Info.noteFailure()) {
  4615. StmtVisitorTy::Visit(E->getTrueExpr());
  4616. StmtVisitorTy::Visit(E->getFalseExpr());
  4617. }
  4618. return false;
  4619. }
  4620. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4621. return StmtVisitorTy::Visit(EvalExpr);
  4622. }
  4623. protected:
  4624. EvalInfo &Info;
  4625. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4626. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4627. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4628. return Info.CCEDiag(E, D);
  4629. }
  4630. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4631. public:
  4632. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4633. EvalInfo &getEvalInfo() { return Info; }
  4634. /// Report an evaluation error. This should only be called when an error is
  4635. /// first discovered. When propagating an error, just return false.
  4636. bool Error(const Expr *E, diag::kind D) {
  4637. Info.FFDiag(E, D);
  4638. return false;
  4639. }
  4640. bool Error(const Expr *E) {
  4641. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4642. }
  4643. bool VisitStmt(const Stmt *) {
  4644. llvm_unreachable("Expression evaluator should not be called on stmts");
  4645. }
  4646. bool VisitExpr(const Expr *E) {
  4647. return Error(E);
  4648. }
  4649. bool VisitConstantExpr(const ConstantExpr *E)
  4650. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4651. bool VisitParenExpr(const ParenExpr *E)
  4652. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4653. bool VisitUnaryExtension(const UnaryOperator *E)
  4654. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4655. bool VisitUnaryPlus(const UnaryOperator *E)
  4656. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4657. bool VisitChooseExpr(const ChooseExpr *E)
  4658. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4659. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4660. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4661. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4662. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4663. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4664. TempVersionRAII RAII(*Info.CurrentCall);
  4665. return StmtVisitorTy::Visit(E->getExpr());
  4666. }
  4667. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4668. TempVersionRAII RAII(*Info.CurrentCall);
  4669. // The initializer may not have been parsed yet, or might be erroneous.
  4670. if (!E->getExpr())
  4671. return Error(E);
  4672. return StmtVisitorTy::Visit(E->getExpr());
  4673. }
  4674. // We cannot create any objects for which cleanups are required, so there is
  4675. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4676. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4677. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4678. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4679. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4680. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4681. }
  4682. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4683. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  4684. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4685. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4686. }
  4687. bool VisitBinaryOperator(const BinaryOperator *E) {
  4688. switch (E->getOpcode()) {
  4689. default:
  4690. return Error(E);
  4691. case BO_Comma:
  4692. VisitIgnoredValue(E->getLHS());
  4693. return StmtVisitorTy::Visit(E->getRHS());
  4694. case BO_PtrMemD:
  4695. case BO_PtrMemI: {
  4696. LValue Obj;
  4697. if (!HandleMemberPointerAccess(Info, E, Obj))
  4698. return false;
  4699. APValue Result;
  4700. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4701. return false;
  4702. return DerivedSuccess(Result, E);
  4703. }
  4704. }
  4705. }
  4706. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4707. // Evaluate and cache the common expression. We treat it as a temporary,
  4708. // even though it's not quite the same thing.
  4709. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4710. Info, E->getCommon()))
  4711. return false;
  4712. return HandleConditionalOperator(E);
  4713. }
  4714. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4715. bool IsBcpCall = false;
  4716. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4717. // the result is a constant expression if it can be folded without
  4718. // side-effects. This is an important GNU extension. See GCC PR38377
  4719. // for discussion.
  4720. if (const CallExpr *CallCE =
  4721. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4722. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4723. IsBcpCall = true;
  4724. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4725. // constant expression; we can't check whether it's potentially foldable.
  4726. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4727. return false;
  4728. FoldConstant Fold(Info, IsBcpCall);
  4729. if (!HandleConditionalOperator(E)) {
  4730. Fold.keepDiagnostics();
  4731. return false;
  4732. }
  4733. return true;
  4734. }
  4735. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4736. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4737. return DerivedSuccess(*Value, E);
  4738. const Expr *Source = E->getSourceExpr();
  4739. if (!Source)
  4740. return Error(E);
  4741. if (Source == E) { // sanity checking.
  4742. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4743. return Error(E);
  4744. }
  4745. return StmtVisitorTy::Visit(Source);
  4746. }
  4747. bool VisitCallExpr(const CallExpr *E) {
  4748. APValue Result;
  4749. if (!handleCallExpr(E, Result, nullptr))
  4750. return false;
  4751. return DerivedSuccess(Result, E);
  4752. }
  4753. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4754. const LValue *ResultSlot) {
  4755. const Expr *Callee = E->getCallee()->IgnoreParens();
  4756. QualType CalleeType = Callee->getType();
  4757. const FunctionDecl *FD = nullptr;
  4758. LValue *This = nullptr, ThisVal;
  4759. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4760. bool HasQualifier = false;
  4761. // Extract function decl and 'this' pointer from the callee.
  4762. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4763. const CXXMethodDecl *Member = nullptr;
  4764. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4765. // Explicit bound member calls, such as x.f() or p->g();
  4766. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4767. return false;
  4768. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  4769. if (!Member)
  4770. return Error(Callee);
  4771. This = &ThisVal;
  4772. HasQualifier = ME->hasQualifier();
  4773. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4774. // Indirect bound member calls ('.*' or '->*').
  4775. Member = dyn_cast_or_null<CXXMethodDecl>(
  4776. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  4777. if (!Member)
  4778. return Error(Callee);
  4779. This = &ThisVal;
  4780. } else
  4781. return Error(Callee);
  4782. FD = Member;
  4783. } else if (CalleeType->isFunctionPointerType()) {
  4784. LValue Call;
  4785. if (!EvaluatePointer(Callee, Call, Info))
  4786. return false;
  4787. if (!Call.getLValueOffset().isZero())
  4788. return Error(Callee);
  4789. FD = dyn_cast_or_null<FunctionDecl>(
  4790. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4791. if (!FD)
  4792. return Error(Callee);
  4793. // Don't call function pointers which have been cast to some other type.
  4794. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4795. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4796. CalleeType->getPointeeType(), FD->getType())) {
  4797. return Error(E);
  4798. }
  4799. // Overloaded operator calls to member functions are represented as normal
  4800. // calls with '*this' as the first argument.
  4801. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4802. if (MD && !MD->isStatic()) {
  4803. // FIXME: When selecting an implicit conversion for an overloaded
  4804. // operator delete, we sometimes try to evaluate calls to conversion
  4805. // operators without a 'this' parameter!
  4806. if (Args.empty())
  4807. return Error(E);
  4808. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4809. return false;
  4810. This = &ThisVal;
  4811. Args = Args.slice(1);
  4812. } else if (MD && MD->isLambdaStaticInvoker()) {
  4813. // Map the static invoker for the lambda back to the call operator.
  4814. // Conveniently, we don't have to slice out the 'this' argument (as is
  4815. // being done for the non-static case), since a static member function
  4816. // doesn't have an implicit argument passed in.
  4817. const CXXRecordDecl *ClosureClass = MD->getParent();
  4818. assert(
  4819. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  4820. "Number of captures must be zero for conversion to function-ptr");
  4821. const CXXMethodDecl *LambdaCallOp =
  4822. ClosureClass->getLambdaCallOperator();
  4823. // Set 'FD', the function that will be called below, to the call
  4824. // operator. If the closure object represents a generic lambda, find
  4825. // the corresponding specialization of the call operator.
  4826. if (ClosureClass->isGenericLambda()) {
  4827. assert(MD->isFunctionTemplateSpecialization() &&
  4828. "A generic lambda's static-invoker function must be a "
  4829. "template specialization");
  4830. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  4831. FunctionTemplateDecl *CallOpTemplate =
  4832. LambdaCallOp->getDescribedFunctionTemplate();
  4833. void *InsertPos = nullptr;
  4834. FunctionDecl *CorrespondingCallOpSpecialization =
  4835. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  4836. assert(CorrespondingCallOpSpecialization &&
  4837. "We must always have a function call operator specialization "
  4838. "that corresponds to our static invoker specialization");
  4839. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  4840. } else
  4841. FD = LambdaCallOp;
  4842. }
  4843. } else
  4844. return Error(E);
  4845. SmallVector<QualType, 4> CovariantAdjustmentPath;
  4846. if (This) {
  4847. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  4848. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  4849. // Perform virtual dispatch, if necessary.
  4850. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  4851. CovariantAdjustmentPath);
  4852. if (!FD)
  4853. return false;
  4854. } else {
  4855. // Check that the 'this' pointer points to an object of the right type.
  4856. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
  4857. return false;
  4858. }
  4859. }
  4860. const FunctionDecl *Definition = nullptr;
  4861. Stmt *Body = FD->getBody(Definition);
  4862. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  4863. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  4864. Result, ResultSlot))
  4865. return false;
  4866. if (!CovariantAdjustmentPath.empty() &&
  4867. !HandleCovariantReturnAdjustment(Info, E, Result,
  4868. CovariantAdjustmentPath))
  4869. return false;
  4870. return true;
  4871. }
  4872. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  4873. return StmtVisitorTy::Visit(E->getInitializer());
  4874. }
  4875. bool VisitInitListExpr(const InitListExpr *E) {
  4876. if (E->getNumInits() == 0)
  4877. return DerivedZeroInitialization(E);
  4878. if (E->getNumInits() == 1)
  4879. return StmtVisitorTy::Visit(E->getInit(0));
  4880. return Error(E);
  4881. }
  4882. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  4883. return DerivedZeroInitialization(E);
  4884. }
  4885. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  4886. return DerivedZeroInitialization(E);
  4887. }
  4888. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  4889. return DerivedZeroInitialization(E);
  4890. }
  4891. /// A member expression where the object is a prvalue is itself a prvalue.
  4892. bool VisitMemberExpr(const MemberExpr *E) {
  4893. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  4894. "missing temporary materialization conversion");
  4895. assert(!E->isArrow() && "missing call to bound member function?");
  4896. APValue Val;
  4897. if (!Evaluate(Val, Info, E->getBase()))
  4898. return false;
  4899. QualType BaseTy = E->getBase()->getType();
  4900. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  4901. if (!FD) return Error(E);
  4902. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  4903. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  4904. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  4905. // Note: there is no lvalue base here. But this case should only ever
  4906. // happen in C or in C++98, where we cannot be evaluating a constexpr
  4907. // constructor, which is the only case the base matters.
  4908. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  4909. SubobjectDesignator Designator(BaseTy);
  4910. Designator.addDeclUnchecked(FD);
  4911. APValue Result;
  4912. return extractSubobject(Info, E, Obj, Designator, Result) &&
  4913. DerivedSuccess(Result, E);
  4914. }
  4915. bool VisitCastExpr(const CastExpr *E) {
  4916. switch (E->getCastKind()) {
  4917. default:
  4918. break;
  4919. case CK_AtomicToNonAtomic: {
  4920. APValue AtomicVal;
  4921. // This does not need to be done in place even for class/array types:
  4922. // atomic-to-non-atomic conversion implies copying the object
  4923. // representation.
  4924. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  4925. return false;
  4926. return DerivedSuccess(AtomicVal, E);
  4927. }
  4928. case CK_NoOp:
  4929. case CK_UserDefinedConversion:
  4930. return StmtVisitorTy::Visit(E->getSubExpr());
  4931. case CK_LValueToRValue: {
  4932. LValue LVal;
  4933. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  4934. return false;
  4935. APValue RVal;
  4936. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  4937. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  4938. LVal, RVal))
  4939. return false;
  4940. return DerivedSuccess(RVal, E);
  4941. }
  4942. }
  4943. return Error(E);
  4944. }
  4945. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  4946. return VisitUnaryPostIncDec(UO);
  4947. }
  4948. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  4949. return VisitUnaryPostIncDec(UO);
  4950. }
  4951. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  4952. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  4953. return Error(UO);
  4954. LValue LVal;
  4955. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  4956. return false;
  4957. APValue RVal;
  4958. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  4959. UO->isIncrementOp(), &RVal))
  4960. return false;
  4961. return DerivedSuccess(RVal, UO);
  4962. }
  4963. bool VisitStmtExpr(const StmtExpr *E) {
  4964. // We will have checked the full-expressions inside the statement expression
  4965. // when they were completed, and don't need to check them again now.
  4966. if (Info.checkingForOverflow())
  4967. return Error(E);
  4968. BlockScopeRAII Scope(Info);
  4969. const CompoundStmt *CS = E->getSubStmt();
  4970. if (CS->body_empty())
  4971. return true;
  4972. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  4973. BE = CS->body_end();
  4974. /**/; ++BI) {
  4975. if (BI + 1 == BE) {
  4976. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  4977. if (!FinalExpr) {
  4978. Info.FFDiag((*BI)->getBeginLoc(),
  4979. diag::note_constexpr_stmt_expr_unsupported);
  4980. return false;
  4981. }
  4982. return this->Visit(FinalExpr);
  4983. }
  4984. APValue ReturnValue;
  4985. StmtResult Result = { ReturnValue, nullptr };
  4986. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  4987. if (ESR != ESR_Succeeded) {
  4988. // FIXME: If the statement-expression terminated due to 'return',
  4989. // 'break', or 'continue', it would be nice to propagate that to
  4990. // the outer statement evaluation rather than bailing out.
  4991. if (ESR != ESR_Failed)
  4992. Info.FFDiag((*BI)->getBeginLoc(),
  4993. diag::note_constexpr_stmt_expr_unsupported);
  4994. return false;
  4995. }
  4996. }
  4997. llvm_unreachable("Return from function from the loop above.");
  4998. }
  4999. /// Visit a value which is evaluated, but whose value is ignored.
  5000. void VisitIgnoredValue(const Expr *E) {
  5001. EvaluateIgnoredValue(Info, E);
  5002. }
  5003. /// Potentially visit a MemberExpr's base expression.
  5004. void VisitIgnoredBaseExpression(const Expr *E) {
  5005. // While MSVC doesn't evaluate the base expression, it does diagnose the
  5006. // presence of side-effecting behavior.
  5007. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  5008. return;
  5009. VisitIgnoredValue(E);
  5010. }
  5011. };
  5012. } // namespace
  5013. //===----------------------------------------------------------------------===//
  5014. // Common base class for lvalue and temporary evaluation.
  5015. //===----------------------------------------------------------------------===//
  5016. namespace {
  5017. template<class Derived>
  5018. class LValueExprEvaluatorBase
  5019. : public ExprEvaluatorBase<Derived> {
  5020. protected:
  5021. LValue &Result;
  5022. bool InvalidBaseOK;
  5023. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  5024. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  5025. bool Success(APValue::LValueBase B) {
  5026. Result.set(B);
  5027. return true;
  5028. }
  5029. bool evaluatePointer(const Expr *E, LValue &Result) {
  5030. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  5031. }
  5032. public:
  5033. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  5034. : ExprEvaluatorBaseTy(Info), Result(Result),
  5035. InvalidBaseOK(InvalidBaseOK) {}
  5036. bool Success(const APValue &V, const Expr *E) {
  5037. Result.setFrom(this->Info.Ctx, V);
  5038. return true;
  5039. }
  5040. bool VisitMemberExpr(const MemberExpr *E) {
  5041. // Handle non-static data members.
  5042. QualType BaseTy;
  5043. bool EvalOK;
  5044. if (E->isArrow()) {
  5045. EvalOK = evaluatePointer(E->getBase(), Result);
  5046. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  5047. } else if (E->getBase()->isRValue()) {
  5048. assert(E->getBase()->getType()->isRecordType());
  5049. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  5050. BaseTy = E->getBase()->getType();
  5051. } else {
  5052. EvalOK = this->Visit(E->getBase());
  5053. BaseTy = E->getBase()->getType();
  5054. }
  5055. if (!EvalOK) {
  5056. if (!InvalidBaseOK)
  5057. return false;
  5058. Result.setInvalid(E);
  5059. return true;
  5060. }
  5061. const ValueDecl *MD = E->getMemberDecl();
  5062. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  5063. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5064. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5065. (void)BaseTy;
  5066. if (!HandleLValueMember(this->Info, E, Result, FD))
  5067. return false;
  5068. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  5069. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  5070. return false;
  5071. } else
  5072. return this->Error(E);
  5073. if (MD->getType()->isReferenceType()) {
  5074. APValue RefValue;
  5075. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  5076. RefValue))
  5077. return false;
  5078. return Success(RefValue, E);
  5079. }
  5080. return true;
  5081. }
  5082. bool VisitBinaryOperator(const BinaryOperator *E) {
  5083. switch (E->getOpcode()) {
  5084. default:
  5085. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5086. case BO_PtrMemD:
  5087. case BO_PtrMemI:
  5088. return HandleMemberPointerAccess(this->Info, E, Result);
  5089. }
  5090. }
  5091. bool VisitCastExpr(const CastExpr *E) {
  5092. switch (E->getCastKind()) {
  5093. default:
  5094. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5095. case CK_DerivedToBase:
  5096. case CK_UncheckedDerivedToBase:
  5097. if (!this->Visit(E->getSubExpr()))
  5098. return false;
  5099. // Now figure out the necessary offset to add to the base LV to get from
  5100. // the derived class to the base class.
  5101. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  5102. Result);
  5103. }
  5104. }
  5105. };
  5106. }
  5107. //===----------------------------------------------------------------------===//
  5108. // LValue Evaluation
  5109. //
  5110. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  5111. // function designators (in C), decl references to void objects (in C), and
  5112. // temporaries (if building with -Wno-address-of-temporary).
  5113. //
  5114. // LValue evaluation produces values comprising a base expression of one of the
  5115. // following types:
  5116. // - Declarations
  5117. // * VarDecl
  5118. // * FunctionDecl
  5119. // - Literals
  5120. // * CompoundLiteralExpr in C (and in global scope in C++)
  5121. // * StringLiteral
  5122. // * CXXTypeidExpr
  5123. // * PredefinedExpr
  5124. // * ObjCStringLiteralExpr
  5125. // * ObjCEncodeExpr
  5126. // * AddrLabelExpr
  5127. // * BlockExpr
  5128. // * CallExpr for a MakeStringConstant builtin
  5129. // - Locals and temporaries
  5130. // * MaterializeTemporaryExpr
  5131. // * Any Expr, with a CallIndex indicating the function in which the temporary
  5132. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  5133. // from the AST (FIXME).
  5134. // * A MaterializeTemporaryExpr that has static storage duration, with no
  5135. // CallIndex, for a lifetime-extended temporary.
  5136. // plus an offset in bytes.
  5137. //===----------------------------------------------------------------------===//
  5138. namespace {
  5139. class LValueExprEvaluator
  5140. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  5141. public:
  5142. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  5143. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  5144. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  5145. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  5146. bool VisitDeclRefExpr(const DeclRefExpr *E);
  5147. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  5148. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  5149. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  5150. bool VisitMemberExpr(const MemberExpr *E);
  5151. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  5152. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  5153. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  5154. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  5155. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  5156. bool VisitUnaryDeref(const UnaryOperator *E);
  5157. bool VisitUnaryReal(const UnaryOperator *E);
  5158. bool VisitUnaryImag(const UnaryOperator *E);
  5159. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  5160. return VisitUnaryPreIncDec(UO);
  5161. }
  5162. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  5163. return VisitUnaryPreIncDec(UO);
  5164. }
  5165. bool VisitBinAssign(const BinaryOperator *BO);
  5166. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  5167. bool VisitCastExpr(const CastExpr *E) {
  5168. switch (E->getCastKind()) {
  5169. default:
  5170. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  5171. case CK_LValueBitCast:
  5172. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5173. if (!Visit(E->getSubExpr()))
  5174. return false;
  5175. Result.Designator.setInvalid();
  5176. return true;
  5177. case CK_BaseToDerived:
  5178. if (!Visit(E->getSubExpr()))
  5179. return false;
  5180. return HandleBaseToDerivedCast(Info, E, Result);
  5181. case CK_Dynamic:
  5182. if (!Visit(E->getSubExpr()))
  5183. return false;
  5184. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  5185. }
  5186. }
  5187. };
  5188. } // end anonymous namespace
  5189. /// Evaluate an expression as an lvalue. This can be legitimately called on
  5190. /// expressions which are not glvalues, in three cases:
  5191. /// * function designators in C, and
  5192. /// * "extern void" objects
  5193. /// * @selector() expressions in Objective-C
  5194. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  5195. bool InvalidBaseOK) {
  5196. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  5197. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  5198. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5199. }
  5200. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  5201. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  5202. return Success(FD);
  5203. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  5204. return VisitVarDecl(E, VD);
  5205. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  5206. return Visit(BD->getBinding());
  5207. return Error(E);
  5208. }
  5209. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  5210. // If we are within a lambda's call operator, check whether the 'VD' referred
  5211. // to within 'E' actually represents a lambda-capture that maps to a
  5212. // data-member/field within the closure object, and if so, evaluate to the
  5213. // field or what the field refers to.
  5214. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  5215. isa<DeclRefExpr>(E) &&
  5216. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  5217. // We don't always have a complete capture-map when checking or inferring if
  5218. // the function call operator meets the requirements of a constexpr function
  5219. // - but we don't need to evaluate the captures to determine constexprness
  5220. // (dcl.constexpr C++17).
  5221. if (Info.checkingPotentialConstantExpression())
  5222. return false;
  5223. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  5224. // Start with 'Result' referring to the complete closure object...
  5225. Result = *Info.CurrentCall->This;
  5226. // ... then update it to refer to the field of the closure object
  5227. // that represents the capture.
  5228. if (!HandleLValueMember(Info, E, Result, FD))
  5229. return false;
  5230. // And if the field is of reference type, update 'Result' to refer to what
  5231. // the field refers to.
  5232. if (FD->getType()->isReferenceType()) {
  5233. APValue RVal;
  5234. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  5235. RVal))
  5236. return false;
  5237. Result.setFrom(Info.Ctx, RVal);
  5238. }
  5239. return true;
  5240. }
  5241. }
  5242. CallStackFrame *Frame = nullptr;
  5243. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  5244. // Only if a local variable was declared in the function currently being
  5245. // evaluated, do we expect to be able to find its value in the current
  5246. // frame. (Otherwise it was likely declared in an enclosing context and
  5247. // could either have a valid evaluatable value (for e.g. a constexpr
  5248. // variable) or be ill-formed (and trigger an appropriate evaluation
  5249. // diagnostic)).
  5250. if (Info.CurrentCall->Callee &&
  5251. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  5252. Frame = Info.CurrentCall;
  5253. }
  5254. }
  5255. if (!VD->getType()->isReferenceType()) {
  5256. if (Frame) {
  5257. Result.set({VD, Frame->Index,
  5258. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  5259. return true;
  5260. }
  5261. return Success(VD);
  5262. }
  5263. APValue *V;
  5264. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  5265. return false;
  5266. if (V->isUninit()) {
  5267. if (!Info.checkingPotentialConstantExpression())
  5268. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  5269. return false;
  5270. }
  5271. return Success(*V, E);
  5272. }
  5273. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  5274. const MaterializeTemporaryExpr *E) {
  5275. // Walk through the expression to find the materialized temporary itself.
  5276. SmallVector<const Expr *, 2> CommaLHSs;
  5277. SmallVector<SubobjectAdjustment, 2> Adjustments;
  5278. const Expr *Inner = E->GetTemporaryExpr()->
  5279. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  5280. // If we passed any comma operators, evaluate their LHSs.
  5281. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  5282. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  5283. return false;
  5284. // A materialized temporary with static storage duration can appear within the
  5285. // result of a constant expression evaluation, so we need to preserve its
  5286. // value for use outside this evaluation.
  5287. APValue *Value;
  5288. if (E->getStorageDuration() == SD_Static) {
  5289. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  5290. *Value = APValue();
  5291. Result.set(E);
  5292. } else {
  5293. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  5294. *Info.CurrentCall);
  5295. }
  5296. QualType Type = Inner->getType();
  5297. // Materialize the temporary itself.
  5298. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  5299. (E->getStorageDuration() == SD_Static &&
  5300. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  5301. *Value = APValue();
  5302. return false;
  5303. }
  5304. // Adjust our lvalue to refer to the desired subobject.
  5305. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  5306. --I;
  5307. switch (Adjustments[I].Kind) {
  5308. case SubobjectAdjustment::DerivedToBaseAdjustment:
  5309. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  5310. Type, Result))
  5311. return false;
  5312. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  5313. break;
  5314. case SubobjectAdjustment::FieldAdjustment:
  5315. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  5316. return false;
  5317. Type = Adjustments[I].Field->getType();
  5318. break;
  5319. case SubobjectAdjustment::MemberPointerAdjustment:
  5320. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  5321. Adjustments[I].Ptr.RHS))
  5322. return false;
  5323. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  5324. break;
  5325. }
  5326. }
  5327. return true;
  5328. }
  5329. bool
  5330. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5331. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  5332. "lvalue compound literal in c++?");
  5333. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  5334. // only see this when folding in C, so there's no standard to follow here.
  5335. return Success(E);
  5336. }
  5337. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  5338. if (!E->isPotentiallyEvaluated())
  5339. return Success(E);
  5340. Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
  5341. << E->getExprOperand()->getType()
  5342. << E->getExprOperand()->getSourceRange();
  5343. return false;
  5344. }
  5345. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  5346. return Success(E);
  5347. }
  5348. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  5349. // Handle static data members.
  5350. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  5351. VisitIgnoredBaseExpression(E->getBase());
  5352. return VisitVarDecl(E, VD);
  5353. }
  5354. // Handle static member functions.
  5355. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  5356. if (MD->isStatic()) {
  5357. VisitIgnoredBaseExpression(E->getBase());
  5358. return Success(MD);
  5359. }
  5360. }
  5361. // Handle non-static data members.
  5362. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  5363. }
  5364. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  5365. // FIXME: Deal with vectors as array subscript bases.
  5366. if (E->getBase()->getType()->isVectorType())
  5367. return Error(E);
  5368. bool Success = true;
  5369. if (!evaluatePointer(E->getBase(), Result)) {
  5370. if (!Info.noteFailure())
  5371. return false;
  5372. Success = false;
  5373. }
  5374. APSInt Index;
  5375. if (!EvaluateInteger(E->getIdx(), Index, Info))
  5376. return false;
  5377. return Success &&
  5378. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  5379. }
  5380. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  5381. return evaluatePointer(E->getSubExpr(), Result);
  5382. }
  5383. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  5384. if (!Visit(E->getSubExpr()))
  5385. return false;
  5386. // __real is a no-op on scalar lvalues.
  5387. if (E->getSubExpr()->getType()->isAnyComplexType())
  5388. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  5389. return true;
  5390. }
  5391. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  5392. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  5393. "lvalue __imag__ on scalar?");
  5394. if (!Visit(E->getSubExpr()))
  5395. return false;
  5396. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  5397. return true;
  5398. }
  5399. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  5400. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5401. return Error(UO);
  5402. if (!this->Visit(UO->getSubExpr()))
  5403. return false;
  5404. return handleIncDec(
  5405. this->Info, UO, Result, UO->getSubExpr()->getType(),
  5406. UO->isIncrementOp(), nullptr);
  5407. }
  5408. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  5409. const CompoundAssignOperator *CAO) {
  5410. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5411. return Error(CAO);
  5412. APValue RHS;
  5413. // The overall lvalue result is the result of evaluating the LHS.
  5414. if (!this->Visit(CAO->getLHS())) {
  5415. if (Info.noteFailure())
  5416. Evaluate(RHS, this->Info, CAO->getRHS());
  5417. return false;
  5418. }
  5419. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  5420. return false;
  5421. return handleCompoundAssignment(
  5422. this->Info, CAO,
  5423. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  5424. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  5425. }
  5426. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  5427. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5428. return Error(E);
  5429. APValue NewVal;
  5430. if (!this->Visit(E->getLHS())) {
  5431. if (Info.noteFailure())
  5432. Evaluate(NewVal, this->Info, E->getRHS());
  5433. return false;
  5434. }
  5435. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  5436. return false;
  5437. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  5438. NewVal);
  5439. }
  5440. //===----------------------------------------------------------------------===//
  5441. // Pointer Evaluation
  5442. //===----------------------------------------------------------------------===//
  5443. /// Attempts to compute the number of bytes available at the pointer
  5444. /// returned by a function with the alloc_size attribute. Returns true if we
  5445. /// were successful. Places an unsigned number into `Result`.
  5446. ///
  5447. /// This expects the given CallExpr to be a call to a function with an
  5448. /// alloc_size attribute.
  5449. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5450. const CallExpr *Call,
  5451. llvm::APInt &Result) {
  5452. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  5453. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  5454. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  5455. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  5456. if (Call->getNumArgs() <= SizeArgNo)
  5457. return false;
  5458. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  5459. Expr::EvalResult ExprResult;
  5460. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  5461. return false;
  5462. Into = ExprResult.Val.getInt();
  5463. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  5464. return false;
  5465. Into = Into.zextOrSelf(BitsInSizeT);
  5466. return true;
  5467. };
  5468. APSInt SizeOfElem;
  5469. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  5470. return false;
  5471. if (!AllocSize->getNumElemsParam().isValid()) {
  5472. Result = std::move(SizeOfElem);
  5473. return true;
  5474. }
  5475. APSInt NumberOfElems;
  5476. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  5477. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  5478. return false;
  5479. bool Overflow;
  5480. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  5481. if (Overflow)
  5482. return false;
  5483. Result = std::move(BytesAvailable);
  5484. return true;
  5485. }
  5486. /// Convenience function. LVal's base must be a call to an alloc_size
  5487. /// function.
  5488. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5489. const LValue &LVal,
  5490. llvm::APInt &Result) {
  5491. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  5492. "Can't get the size of a non alloc_size function");
  5493. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  5494. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  5495. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  5496. }
  5497. /// Attempts to evaluate the given LValueBase as the result of a call to
  5498. /// a function with the alloc_size attribute. If it was possible to do so, this
  5499. /// function will return true, make Result's Base point to said function call,
  5500. /// and mark Result's Base as invalid.
  5501. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  5502. LValue &Result) {
  5503. if (Base.isNull())
  5504. return false;
  5505. // Because we do no form of static analysis, we only support const variables.
  5506. //
  5507. // Additionally, we can't support parameters, nor can we support static
  5508. // variables (in the latter case, use-before-assign isn't UB; in the former,
  5509. // we have no clue what they'll be assigned to).
  5510. const auto *VD =
  5511. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  5512. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  5513. return false;
  5514. const Expr *Init = VD->getAnyInitializer();
  5515. if (!Init)
  5516. return false;
  5517. const Expr *E = Init->IgnoreParens();
  5518. if (!tryUnwrapAllocSizeCall(E))
  5519. return false;
  5520. // Store E instead of E unwrapped so that the type of the LValue's base is
  5521. // what the user wanted.
  5522. Result.setInvalid(E);
  5523. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5524. Result.addUnsizedArray(Info, E, Pointee);
  5525. return true;
  5526. }
  5527. namespace {
  5528. class PointerExprEvaluator
  5529. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5530. LValue &Result;
  5531. bool InvalidBaseOK;
  5532. bool Success(const Expr *E) {
  5533. Result.set(E);
  5534. return true;
  5535. }
  5536. bool evaluateLValue(const Expr *E, LValue &Result) {
  5537. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5538. }
  5539. bool evaluatePointer(const Expr *E, LValue &Result) {
  5540. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5541. }
  5542. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5543. public:
  5544. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5545. : ExprEvaluatorBaseTy(info), Result(Result),
  5546. InvalidBaseOK(InvalidBaseOK) {}
  5547. bool Success(const APValue &V, const Expr *E) {
  5548. Result.setFrom(Info.Ctx, V);
  5549. return true;
  5550. }
  5551. bool ZeroInitialization(const Expr *E) {
  5552. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5553. Result.setNull(E->getType(), TargetVal);
  5554. return true;
  5555. }
  5556. bool VisitBinaryOperator(const BinaryOperator *E);
  5557. bool VisitCastExpr(const CastExpr* E);
  5558. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5559. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5560. { return Success(E); }
  5561. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5562. if (E->isExpressibleAsConstantInitializer())
  5563. return Success(E);
  5564. if (Info.noteFailure())
  5565. EvaluateIgnoredValue(Info, E->getSubExpr());
  5566. return Error(E);
  5567. }
  5568. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5569. { return Success(E); }
  5570. bool VisitCallExpr(const CallExpr *E);
  5571. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5572. bool VisitBlockExpr(const BlockExpr *E) {
  5573. if (!E->getBlockDecl()->hasCaptures())
  5574. return Success(E);
  5575. return Error(E);
  5576. }
  5577. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5578. // Can't look at 'this' when checking a potential constant expression.
  5579. if (Info.checkingPotentialConstantExpression())
  5580. return false;
  5581. if (!Info.CurrentCall->This) {
  5582. if (Info.getLangOpts().CPlusPlus11)
  5583. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5584. else
  5585. Info.FFDiag(E);
  5586. return false;
  5587. }
  5588. Result = *Info.CurrentCall->This;
  5589. // If we are inside a lambda's call operator, the 'this' expression refers
  5590. // to the enclosing '*this' object (either by value or reference) which is
  5591. // either copied into the closure object's field that represents the '*this'
  5592. // or refers to '*this'.
  5593. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5594. // Update 'Result' to refer to the data member/field of the closure object
  5595. // that represents the '*this' capture.
  5596. if (!HandleLValueMember(Info, E, Result,
  5597. Info.CurrentCall->LambdaThisCaptureField))
  5598. return false;
  5599. // If we captured '*this' by reference, replace the field with its referent.
  5600. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5601. ->isPointerType()) {
  5602. APValue RVal;
  5603. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5604. RVal))
  5605. return false;
  5606. Result.setFrom(Info.Ctx, RVal);
  5607. }
  5608. }
  5609. return true;
  5610. }
  5611. // FIXME: Missing: @protocol, @selector
  5612. };
  5613. } // end anonymous namespace
  5614. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5615. bool InvalidBaseOK) {
  5616. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5617. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5618. }
  5619. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5620. if (E->getOpcode() != BO_Add &&
  5621. E->getOpcode() != BO_Sub)
  5622. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5623. const Expr *PExp = E->getLHS();
  5624. const Expr *IExp = E->getRHS();
  5625. if (IExp->getType()->isPointerType())
  5626. std::swap(PExp, IExp);
  5627. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5628. if (!EvalPtrOK && !Info.noteFailure())
  5629. return false;
  5630. llvm::APSInt Offset;
  5631. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5632. return false;
  5633. if (E->getOpcode() == BO_Sub)
  5634. negateAsSigned(Offset);
  5635. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5636. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5637. }
  5638. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5639. return evaluateLValue(E->getSubExpr(), Result);
  5640. }
  5641. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5642. const Expr *SubExpr = E->getSubExpr();
  5643. switch (E->getCastKind()) {
  5644. default:
  5645. break;
  5646. case CK_BitCast:
  5647. case CK_CPointerToObjCPointerCast:
  5648. case CK_BlockPointerToObjCPointerCast:
  5649. case CK_AnyPointerToBlockPointerCast:
  5650. case CK_AddressSpaceConversion:
  5651. if (!Visit(SubExpr))
  5652. return false;
  5653. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5654. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5655. // also static_casts, but we disallow them as a resolution to DR1312.
  5656. if (!E->getType()->isVoidPointerType()) {
  5657. Result.Designator.setInvalid();
  5658. if (SubExpr->getType()->isVoidPointerType())
  5659. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5660. << 3 << SubExpr->getType();
  5661. else
  5662. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5663. }
  5664. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5665. ZeroInitialization(E);
  5666. return true;
  5667. case CK_DerivedToBase:
  5668. case CK_UncheckedDerivedToBase:
  5669. if (!evaluatePointer(E->getSubExpr(), Result))
  5670. return false;
  5671. if (!Result.Base && Result.Offset.isZero())
  5672. return true;
  5673. // Now figure out the necessary offset to add to the base LV to get from
  5674. // the derived class to the base class.
  5675. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5676. castAs<PointerType>()->getPointeeType(),
  5677. Result);
  5678. case CK_BaseToDerived:
  5679. if (!Visit(E->getSubExpr()))
  5680. return false;
  5681. if (!Result.Base && Result.Offset.isZero())
  5682. return true;
  5683. return HandleBaseToDerivedCast(Info, E, Result);
  5684. case CK_Dynamic:
  5685. if (!Visit(E->getSubExpr()))
  5686. return false;
  5687. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  5688. case CK_NullToPointer:
  5689. VisitIgnoredValue(E->getSubExpr());
  5690. return ZeroInitialization(E);
  5691. case CK_IntegralToPointer: {
  5692. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5693. APValue Value;
  5694. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5695. break;
  5696. if (Value.isInt()) {
  5697. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5698. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5699. Result.Base = (Expr*)nullptr;
  5700. Result.InvalidBase = false;
  5701. Result.Offset = CharUnits::fromQuantity(N);
  5702. Result.Designator.setInvalid();
  5703. Result.IsNullPtr = false;
  5704. return true;
  5705. } else {
  5706. // Cast is of an lvalue, no need to change value.
  5707. Result.setFrom(Info.Ctx, Value);
  5708. return true;
  5709. }
  5710. }
  5711. case CK_ArrayToPointerDecay: {
  5712. if (SubExpr->isGLValue()) {
  5713. if (!evaluateLValue(SubExpr, Result))
  5714. return false;
  5715. } else {
  5716. APValue &Value = createTemporary(SubExpr, false, Result,
  5717. *Info.CurrentCall);
  5718. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5719. return false;
  5720. }
  5721. // The result is a pointer to the first element of the array.
  5722. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5723. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5724. Result.addArray(Info, E, CAT);
  5725. else
  5726. Result.addUnsizedArray(Info, E, AT->getElementType());
  5727. return true;
  5728. }
  5729. case CK_FunctionToPointerDecay:
  5730. return evaluateLValue(SubExpr, Result);
  5731. case CK_LValueToRValue: {
  5732. LValue LVal;
  5733. if (!evaluateLValue(E->getSubExpr(), LVal))
  5734. return false;
  5735. APValue RVal;
  5736. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5737. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5738. LVal, RVal))
  5739. return InvalidBaseOK &&
  5740. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5741. return Success(RVal, E);
  5742. }
  5743. }
  5744. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5745. }
  5746. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  5747. UnaryExprOrTypeTrait ExprKind) {
  5748. // C++ [expr.alignof]p3:
  5749. // When alignof is applied to a reference type, the result is the
  5750. // alignment of the referenced type.
  5751. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5752. T = Ref->getPointeeType();
  5753. if (T.getQualifiers().hasUnaligned())
  5754. return CharUnits::One();
  5755. const bool AlignOfReturnsPreferred =
  5756. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  5757. // __alignof is defined to return the preferred alignment.
  5758. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  5759. // as well.
  5760. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  5761. return Info.Ctx.toCharUnitsFromBits(
  5762. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5763. // alignof and _Alignof are defined to return the ABI alignment.
  5764. else if (ExprKind == UETT_AlignOf)
  5765. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  5766. else
  5767. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  5768. }
  5769. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  5770. UnaryExprOrTypeTrait ExprKind) {
  5771. E = E->IgnoreParens();
  5772. // The kinds of expressions that we have special-case logic here for
  5773. // should be kept up to date with the special checks for those
  5774. // expressions in Sema.
  5775. // alignof decl is always accepted, even if it doesn't make sense: we default
  5776. // to 1 in those cases.
  5777. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5778. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5779. /*RefAsPointee*/true);
  5780. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5781. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5782. /*RefAsPointee*/true);
  5783. return GetAlignOfType(Info, E->getType(), ExprKind);
  5784. }
  5785. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5786. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  5787. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  5788. return true;
  5789. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  5790. return false;
  5791. Result.setInvalid(E);
  5792. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  5793. Result.addUnsizedArray(Info, E, PointeeTy);
  5794. return true;
  5795. }
  5796. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  5797. if (IsStringLiteralCall(E))
  5798. return Success(E);
  5799. if (unsigned BuiltinOp = E->getBuiltinCallee())
  5800. return VisitBuiltinCallExpr(E, BuiltinOp);
  5801. return visitNonBuiltinCallExpr(E);
  5802. }
  5803. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  5804. unsigned BuiltinOp) {
  5805. switch (BuiltinOp) {
  5806. case Builtin::BI__builtin_addressof:
  5807. return evaluateLValue(E->getArg(0), Result);
  5808. case Builtin::BI__builtin_assume_aligned: {
  5809. // We need to be very careful here because: if the pointer does not have the
  5810. // asserted alignment, then the behavior is undefined, and undefined
  5811. // behavior is non-constant.
  5812. if (!evaluatePointer(E->getArg(0), Result))
  5813. return false;
  5814. LValue OffsetResult(Result);
  5815. APSInt Alignment;
  5816. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  5817. return false;
  5818. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  5819. if (E->getNumArgs() > 2) {
  5820. APSInt Offset;
  5821. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  5822. return false;
  5823. int64_t AdditionalOffset = -Offset.getZExtValue();
  5824. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  5825. }
  5826. // If there is a base object, then it must have the correct alignment.
  5827. if (OffsetResult.Base) {
  5828. CharUnits BaseAlignment;
  5829. if (const ValueDecl *VD =
  5830. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  5831. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  5832. } else {
  5833. BaseAlignment = GetAlignOfExpr(
  5834. Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
  5835. }
  5836. if (BaseAlignment < Align) {
  5837. Result.Designator.setInvalid();
  5838. // FIXME: Add support to Diagnostic for long / long long.
  5839. CCEDiag(E->getArg(0),
  5840. diag::note_constexpr_baa_insufficient_alignment) << 0
  5841. << (unsigned)BaseAlignment.getQuantity()
  5842. << (unsigned)Align.getQuantity();
  5843. return false;
  5844. }
  5845. }
  5846. // The offset must also have the correct alignment.
  5847. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  5848. Result.Designator.setInvalid();
  5849. (OffsetResult.Base
  5850. ? CCEDiag(E->getArg(0),
  5851. diag::note_constexpr_baa_insufficient_alignment) << 1
  5852. : CCEDiag(E->getArg(0),
  5853. diag::note_constexpr_baa_value_insufficient_alignment))
  5854. << (int)OffsetResult.Offset.getQuantity()
  5855. << (unsigned)Align.getQuantity();
  5856. return false;
  5857. }
  5858. return true;
  5859. }
  5860. case Builtin::BI__builtin_launder:
  5861. return evaluatePointer(E->getArg(0), Result);
  5862. case Builtin::BIstrchr:
  5863. case Builtin::BIwcschr:
  5864. case Builtin::BImemchr:
  5865. case Builtin::BIwmemchr:
  5866. if (Info.getLangOpts().CPlusPlus11)
  5867. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5868. << /*isConstexpr*/0 << /*isConstructor*/0
  5869. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5870. else
  5871. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5872. LLVM_FALLTHROUGH;
  5873. case Builtin::BI__builtin_strchr:
  5874. case Builtin::BI__builtin_wcschr:
  5875. case Builtin::BI__builtin_memchr:
  5876. case Builtin::BI__builtin_char_memchr:
  5877. case Builtin::BI__builtin_wmemchr: {
  5878. if (!Visit(E->getArg(0)))
  5879. return false;
  5880. APSInt Desired;
  5881. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  5882. return false;
  5883. uint64_t MaxLength = uint64_t(-1);
  5884. if (BuiltinOp != Builtin::BIstrchr &&
  5885. BuiltinOp != Builtin::BIwcschr &&
  5886. BuiltinOp != Builtin::BI__builtin_strchr &&
  5887. BuiltinOp != Builtin::BI__builtin_wcschr) {
  5888. APSInt N;
  5889. if (!EvaluateInteger(E->getArg(2), N, Info))
  5890. return false;
  5891. MaxLength = N.getExtValue();
  5892. }
  5893. // We cannot find the value if there are no candidates to match against.
  5894. if (MaxLength == 0u)
  5895. return ZeroInitialization(E);
  5896. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  5897. Result.Designator.Invalid)
  5898. return false;
  5899. QualType CharTy = Result.Designator.getType(Info.Ctx);
  5900. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  5901. BuiltinOp == Builtin::BI__builtin_memchr;
  5902. assert(IsRawByte ||
  5903. Info.Ctx.hasSameUnqualifiedType(
  5904. CharTy, E->getArg(0)->getType()->getPointeeType()));
  5905. // Pointers to const void may point to objects of incomplete type.
  5906. if (IsRawByte && CharTy->isIncompleteType()) {
  5907. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  5908. return false;
  5909. }
  5910. // Give up on byte-oriented matching against multibyte elements.
  5911. // FIXME: We can compare the bytes in the correct order.
  5912. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  5913. return false;
  5914. // Figure out what value we're actually looking for (after converting to
  5915. // the corresponding unsigned type if necessary).
  5916. uint64_t DesiredVal;
  5917. bool StopAtNull = false;
  5918. switch (BuiltinOp) {
  5919. case Builtin::BIstrchr:
  5920. case Builtin::BI__builtin_strchr:
  5921. // strchr compares directly to the passed integer, and therefore
  5922. // always fails if given an int that is not a char.
  5923. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  5924. E->getArg(1)->getType(),
  5925. Desired),
  5926. Desired))
  5927. return ZeroInitialization(E);
  5928. StopAtNull = true;
  5929. LLVM_FALLTHROUGH;
  5930. case Builtin::BImemchr:
  5931. case Builtin::BI__builtin_memchr:
  5932. case Builtin::BI__builtin_char_memchr:
  5933. // memchr compares by converting both sides to unsigned char. That's also
  5934. // correct for strchr if we get this far (to cope with plain char being
  5935. // unsigned in the strchr case).
  5936. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  5937. break;
  5938. case Builtin::BIwcschr:
  5939. case Builtin::BI__builtin_wcschr:
  5940. StopAtNull = true;
  5941. LLVM_FALLTHROUGH;
  5942. case Builtin::BIwmemchr:
  5943. case Builtin::BI__builtin_wmemchr:
  5944. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  5945. DesiredVal = Desired.getZExtValue();
  5946. break;
  5947. }
  5948. for (; MaxLength; --MaxLength) {
  5949. APValue Char;
  5950. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  5951. !Char.isInt())
  5952. return false;
  5953. if (Char.getInt().getZExtValue() == DesiredVal)
  5954. return true;
  5955. if (StopAtNull && !Char.getInt())
  5956. break;
  5957. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  5958. return false;
  5959. }
  5960. // Not found: return nullptr.
  5961. return ZeroInitialization(E);
  5962. }
  5963. case Builtin::BImemcpy:
  5964. case Builtin::BImemmove:
  5965. case Builtin::BIwmemcpy:
  5966. case Builtin::BIwmemmove:
  5967. if (Info.getLangOpts().CPlusPlus11)
  5968. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  5969. << /*isConstexpr*/0 << /*isConstructor*/0
  5970. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  5971. else
  5972. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  5973. LLVM_FALLTHROUGH;
  5974. case Builtin::BI__builtin_memcpy:
  5975. case Builtin::BI__builtin_memmove:
  5976. case Builtin::BI__builtin_wmemcpy:
  5977. case Builtin::BI__builtin_wmemmove: {
  5978. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  5979. BuiltinOp == Builtin::BIwmemmove ||
  5980. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  5981. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5982. bool Move = BuiltinOp == Builtin::BImemmove ||
  5983. BuiltinOp == Builtin::BIwmemmove ||
  5984. BuiltinOp == Builtin::BI__builtin_memmove ||
  5985. BuiltinOp == Builtin::BI__builtin_wmemmove;
  5986. // The result of mem* is the first argument.
  5987. if (!Visit(E->getArg(0)))
  5988. return false;
  5989. LValue Dest = Result;
  5990. LValue Src;
  5991. if (!EvaluatePointer(E->getArg(1), Src, Info))
  5992. return false;
  5993. APSInt N;
  5994. if (!EvaluateInteger(E->getArg(2), N, Info))
  5995. return false;
  5996. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  5997. // If the size is zero, we treat this as always being a valid no-op.
  5998. // (Even if one of the src and dest pointers is null.)
  5999. if (!N)
  6000. return true;
  6001. // Otherwise, if either of the operands is null, we can't proceed. Don't
  6002. // try to determine the type of the copied objects, because there aren't
  6003. // any.
  6004. if (!Src.Base || !Dest.Base) {
  6005. APValue Val;
  6006. (!Src.Base ? Src : Dest).moveInto(Val);
  6007. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  6008. << Move << WChar << !!Src.Base
  6009. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  6010. return false;
  6011. }
  6012. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  6013. return false;
  6014. // We require that Src and Dest are both pointers to arrays of
  6015. // trivially-copyable type. (For the wide version, the designator will be
  6016. // invalid if the designated object is not a wchar_t.)
  6017. QualType T = Dest.Designator.getType(Info.Ctx);
  6018. QualType SrcT = Src.Designator.getType(Info.Ctx);
  6019. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  6020. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  6021. return false;
  6022. }
  6023. if (T->isIncompleteType()) {
  6024. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  6025. return false;
  6026. }
  6027. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  6028. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  6029. return false;
  6030. }
  6031. // Figure out how many T's we're copying.
  6032. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  6033. if (!WChar) {
  6034. uint64_t Remainder;
  6035. llvm::APInt OrigN = N;
  6036. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  6037. if (Remainder) {
  6038. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6039. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  6040. << (unsigned)TSize;
  6041. return false;
  6042. }
  6043. }
  6044. // Check that the copying will remain within the arrays, just so that we
  6045. // can give a more meaningful diagnostic. This implicitly also checks that
  6046. // N fits into 64 bits.
  6047. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  6048. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  6049. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  6050. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6051. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  6052. << N.toString(10, /*Signed*/false);
  6053. return false;
  6054. }
  6055. uint64_t NElems = N.getZExtValue();
  6056. uint64_t NBytes = NElems * TSize;
  6057. // Check for overlap.
  6058. int Direction = 1;
  6059. if (HasSameBase(Src, Dest)) {
  6060. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  6061. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  6062. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  6063. // Dest is inside the source region.
  6064. if (!Move) {
  6065. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6066. return false;
  6067. }
  6068. // For memmove and friends, copy backwards.
  6069. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  6070. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  6071. return false;
  6072. Direction = -1;
  6073. } else if (!Move && SrcOffset >= DestOffset &&
  6074. SrcOffset - DestOffset < NBytes) {
  6075. // Src is inside the destination region for memcpy: invalid.
  6076. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6077. return false;
  6078. }
  6079. }
  6080. while (true) {
  6081. APValue Val;
  6082. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  6083. !handleAssignment(Info, E, Dest, T, Val))
  6084. return false;
  6085. // Do not iterate past the last element; if we're copying backwards, that
  6086. // might take us off the start of the array.
  6087. if (--NElems == 0)
  6088. return true;
  6089. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  6090. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  6091. return false;
  6092. }
  6093. }
  6094. default:
  6095. return visitNonBuiltinCallExpr(E);
  6096. }
  6097. }
  6098. //===----------------------------------------------------------------------===//
  6099. // Member Pointer Evaluation
  6100. //===----------------------------------------------------------------------===//
  6101. namespace {
  6102. class MemberPointerExprEvaluator
  6103. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  6104. MemberPtr &Result;
  6105. bool Success(const ValueDecl *D) {
  6106. Result = MemberPtr(D);
  6107. return true;
  6108. }
  6109. public:
  6110. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  6111. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  6112. bool Success(const APValue &V, const Expr *E) {
  6113. Result.setFrom(V);
  6114. return true;
  6115. }
  6116. bool ZeroInitialization(const Expr *E) {
  6117. return Success((const ValueDecl*)nullptr);
  6118. }
  6119. bool VisitCastExpr(const CastExpr *E);
  6120. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6121. };
  6122. } // end anonymous namespace
  6123. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  6124. EvalInfo &Info) {
  6125. assert(E->isRValue() && E->getType()->isMemberPointerType());
  6126. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  6127. }
  6128. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6129. switch (E->getCastKind()) {
  6130. default:
  6131. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6132. case CK_NullToMemberPointer:
  6133. VisitIgnoredValue(E->getSubExpr());
  6134. return ZeroInitialization(E);
  6135. case CK_BaseToDerivedMemberPointer: {
  6136. if (!Visit(E->getSubExpr()))
  6137. return false;
  6138. if (E->path_empty())
  6139. return true;
  6140. // Base-to-derived member pointer casts store the path in derived-to-base
  6141. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  6142. // the wrong end of the derived->base arc, so stagger the path by one class.
  6143. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  6144. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  6145. PathI != PathE; ++PathI) {
  6146. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6147. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  6148. if (!Result.castToDerived(Derived))
  6149. return Error(E);
  6150. }
  6151. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  6152. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  6153. return Error(E);
  6154. return true;
  6155. }
  6156. case CK_DerivedToBaseMemberPointer:
  6157. if (!Visit(E->getSubExpr()))
  6158. return false;
  6159. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6160. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6161. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6162. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6163. if (!Result.castToBase(Base))
  6164. return Error(E);
  6165. }
  6166. return true;
  6167. }
  6168. }
  6169. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6170. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  6171. // member can be formed.
  6172. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  6173. }
  6174. //===----------------------------------------------------------------------===//
  6175. // Record Evaluation
  6176. //===----------------------------------------------------------------------===//
  6177. namespace {
  6178. class RecordExprEvaluator
  6179. : public ExprEvaluatorBase<RecordExprEvaluator> {
  6180. const LValue &This;
  6181. APValue &Result;
  6182. public:
  6183. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  6184. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  6185. bool Success(const APValue &V, const Expr *E) {
  6186. Result = V;
  6187. return true;
  6188. }
  6189. bool ZeroInitialization(const Expr *E) {
  6190. return ZeroInitialization(E, E->getType());
  6191. }
  6192. bool ZeroInitialization(const Expr *E, QualType T);
  6193. bool VisitCallExpr(const CallExpr *E) {
  6194. return handleCallExpr(E, Result, &This);
  6195. }
  6196. bool VisitCastExpr(const CastExpr *E);
  6197. bool VisitInitListExpr(const InitListExpr *E);
  6198. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6199. return VisitCXXConstructExpr(E, E->getType());
  6200. }
  6201. bool VisitLambdaExpr(const LambdaExpr *E);
  6202. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  6203. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  6204. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  6205. bool VisitBinCmp(const BinaryOperator *E);
  6206. };
  6207. }
  6208. /// Perform zero-initialization on an object of non-union class type.
  6209. /// C++11 [dcl.init]p5:
  6210. /// To zero-initialize an object or reference of type T means:
  6211. /// [...]
  6212. /// -- if T is a (possibly cv-qualified) non-union class type,
  6213. /// each non-static data member and each base-class subobject is
  6214. /// zero-initialized
  6215. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  6216. const RecordDecl *RD,
  6217. const LValue &This, APValue &Result) {
  6218. assert(!RD->isUnion() && "Expected non-union class type");
  6219. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  6220. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  6221. std::distance(RD->field_begin(), RD->field_end()));
  6222. if (RD->isInvalidDecl()) return false;
  6223. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6224. if (CD) {
  6225. unsigned Index = 0;
  6226. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  6227. End = CD->bases_end(); I != End; ++I, ++Index) {
  6228. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  6229. LValue Subobject = This;
  6230. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  6231. return false;
  6232. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  6233. Result.getStructBase(Index)))
  6234. return false;
  6235. }
  6236. }
  6237. for (const auto *I : RD->fields()) {
  6238. // -- if T is a reference type, no initialization is performed.
  6239. if (I->getType()->isReferenceType())
  6240. continue;
  6241. LValue Subobject = This;
  6242. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  6243. return false;
  6244. ImplicitValueInitExpr VIE(I->getType());
  6245. if (!EvaluateInPlace(
  6246. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  6247. return false;
  6248. }
  6249. return true;
  6250. }
  6251. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  6252. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  6253. if (RD->isInvalidDecl()) return false;
  6254. if (RD->isUnion()) {
  6255. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  6256. // object's first non-static named data member is zero-initialized
  6257. RecordDecl::field_iterator I = RD->field_begin();
  6258. if (I == RD->field_end()) {
  6259. Result = APValue((const FieldDecl*)nullptr);
  6260. return true;
  6261. }
  6262. LValue Subobject = This;
  6263. if (!HandleLValueMember(Info, E, Subobject, *I))
  6264. return false;
  6265. Result = APValue(*I);
  6266. ImplicitValueInitExpr VIE(I->getType());
  6267. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  6268. }
  6269. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  6270. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  6271. return false;
  6272. }
  6273. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  6274. }
  6275. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6276. switch (E->getCastKind()) {
  6277. default:
  6278. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6279. case CK_ConstructorConversion:
  6280. return Visit(E->getSubExpr());
  6281. case CK_DerivedToBase:
  6282. case CK_UncheckedDerivedToBase: {
  6283. APValue DerivedObject;
  6284. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  6285. return false;
  6286. if (!DerivedObject.isStruct())
  6287. return Error(E->getSubExpr());
  6288. // Derived-to-base rvalue conversion: just slice off the derived part.
  6289. APValue *Value = &DerivedObject;
  6290. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  6291. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6292. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6293. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  6294. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6295. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  6296. RD = Base;
  6297. }
  6298. Result = *Value;
  6299. return true;
  6300. }
  6301. }
  6302. }
  6303. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6304. if (E->isTransparent())
  6305. return Visit(E->getInit(0));
  6306. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  6307. if (RD->isInvalidDecl()) return false;
  6308. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6309. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  6310. EvalInfo::EvaluatingConstructorRAII EvalObj(
  6311. Info,
  6312. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  6313. CXXRD && CXXRD->getNumBases());
  6314. if (RD->isUnion()) {
  6315. const FieldDecl *Field = E->getInitializedFieldInUnion();
  6316. Result = APValue(Field);
  6317. if (!Field)
  6318. return true;
  6319. // If the initializer list for a union does not contain any elements, the
  6320. // first element of the union is value-initialized.
  6321. // FIXME: The element should be initialized from an initializer list.
  6322. // Is this difference ever observable for initializer lists which
  6323. // we don't build?
  6324. ImplicitValueInitExpr VIE(Field->getType());
  6325. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  6326. LValue Subobject = This;
  6327. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  6328. return false;
  6329. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6330. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6331. isa<CXXDefaultInitExpr>(InitExpr));
  6332. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  6333. }
  6334. if (Result.isUninit())
  6335. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  6336. std::distance(RD->field_begin(), RD->field_end()));
  6337. unsigned ElementNo = 0;
  6338. bool Success = true;
  6339. // Initialize base classes.
  6340. if (CXXRD && CXXRD->getNumBases()) {
  6341. for (const auto &Base : CXXRD->bases()) {
  6342. assert(ElementNo < E->getNumInits() && "missing init for base class");
  6343. const Expr *Init = E->getInit(ElementNo);
  6344. LValue Subobject = This;
  6345. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  6346. return false;
  6347. APValue &FieldVal = Result.getStructBase(ElementNo);
  6348. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  6349. if (!Info.noteFailure())
  6350. return false;
  6351. Success = false;
  6352. }
  6353. ++ElementNo;
  6354. }
  6355. EvalObj.finishedConstructingBases();
  6356. }
  6357. // Initialize members.
  6358. for (const auto *Field : RD->fields()) {
  6359. // Anonymous bit-fields are not considered members of the class for
  6360. // purposes of aggregate initialization.
  6361. if (Field->isUnnamedBitfield())
  6362. continue;
  6363. LValue Subobject = This;
  6364. bool HaveInit = ElementNo < E->getNumInits();
  6365. // FIXME: Diagnostics here should point to the end of the initializer
  6366. // list, not the start.
  6367. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  6368. Subobject, Field, &Layout))
  6369. return false;
  6370. // Perform an implicit value-initialization for members beyond the end of
  6371. // the initializer list.
  6372. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  6373. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  6374. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6375. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6376. isa<CXXDefaultInitExpr>(Init));
  6377. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  6378. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  6379. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  6380. FieldVal, Field))) {
  6381. if (!Info.noteFailure())
  6382. return false;
  6383. Success = false;
  6384. }
  6385. }
  6386. return Success;
  6387. }
  6388. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6389. QualType T) {
  6390. // Note that E's type is not necessarily the type of our class here; we might
  6391. // be initializing an array element instead.
  6392. const CXXConstructorDecl *FD = E->getConstructor();
  6393. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  6394. bool ZeroInit = E->requiresZeroInitialization();
  6395. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  6396. // If we've already performed zero-initialization, we're already done.
  6397. if (!Result.isUninit())
  6398. return true;
  6399. // We can get here in two different ways:
  6400. // 1) We're performing value-initialization, and should zero-initialize
  6401. // the object, or
  6402. // 2) We're performing default-initialization of an object with a trivial
  6403. // constexpr default constructor, in which case we should start the
  6404. // lifetimes of all the base subobjects (there can be no data member
  6405. // subobjects in this case) per [basic.life]p1.
  6406. // Either way, ZeroInitialization is appropriate.
  6407. return ZeroInitialization(E, T);
  6408. }
  6409. const FunctionDecl *Definition = nullptr;
  6410. auto Body = FD->getBody(Definition);
  6411. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  6412. return false;
  6413. // Avoid materializing a temporary for an elidable copy/move constructor.
  6414. if (E->isElidable() && !ZeroInit)
  6415. if (const MaterializeTemporaryExpr *ME
  6416. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  6417. return Visit(ME->GetTemporaryExpr());
  6418. if (ZeroInit && !ZeroInitialization(E, T))
  6419. return false;
  6420. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  6421. return HandleConstructorCall(E, This, Args,
  6422. cast<CXXConstructorDecl>(Definition), Info,
  6423. Result);
  6424. }
  6425. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  6426. const CXXInheritedCtorInitExpr *E) {
  6427. if (!Info.CurrentCall) {
  6428. assert(Info.checkingPotentialConstantExpression());
  6429. return false;
  6430. }
  6431. const CXXConstructorDecl *FD = E->getConstructor();
  6432. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  6433. return false;
  6434. const FunctionDecl *Definition = nullptr;
  6435. auto Body = FD->getBody(Definition);
  6436. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  6437. return false;
  6438. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  6439. cast<CXXConstructorDecl>(Definition), Info,
  6440. Result);
  6441. }
  6442. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  6443. const CXXStdInitializerListExpr *E) {
  6444. const ConstantArrayType *ArrayType =
  6445. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  6446. LValue Array;
  6447. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  6448. return false;
  6449. // Get a pointer to the first element of the array.
  6450. Array.addArray(Info, E, ArrayType);
  6451. // FIXME: Perform the checks on the field types in SemaInit.
  6452. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  6453. RecordDecl::field_iterator Field = Record->field_begin();
  6454. if (Field == Record->field_end())
  6455. return Error(E);
  6456. // Start pointer.
  6457. if (!Field->getType()->isPointerType() ||
  6458. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  6459. ArrayType->getElementType()))
  6460. return Error(E);
  6461. // FIXME: What if the initializer_list type has base classes, etc?
  6462. Result = APValue(APValue::UninitStruct(), 0, 2);
  6463. Array.moveInto(Result.getStructField(0));
  6464. if (++Field == Record->field_end())
  6465. return Error(E);
  6466. if (Field->getType()->isPointerType() &&
  6467. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  6468. ArrayType->getElementType())) {
  6469. // End pointer.
  6470. if (!HandleLValueArrayAdjustment(Info, E, Array,
  6471. ArrayType->getElementType(),
  6472. ArrayType->getSize().getZExtValue()))
  6473. return false;
  6474. Array.moveInto(Result.getStructField(1));
  6475. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  6476. // Length.
  6477. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  6478. else
  6479. return Error(E);
  6480. if (++Field != Record->field_end())
  6481. return Error(E);
  6482. return true;
  6483. }
  6484. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  6485. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  6486. if (ClosureClass->isInvalidDecl()) return false;
  6487. if (Info.checkingPotentialConstantExpression()) return true;
  6488. const size_t NumFields =
  6489. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  6490. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  6491. E->capture_init_end()) &&
  6492. "The number of lambda capture initializers should equal the number of "
  6493. "fields within the closure type");
  6494. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  6495. // Iterate through all the lambda's closure object's fields and initialize
  6496. // them.
  6497. auto *CaptureInitIt = E->capture_init_begin();
  6498. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  6499. bool Success = true;
  6500. for (const auto *Field : ClosureClass->fields()) {
  6501. assert(CaptureInitIt != E->capture_init_end());
  6502. // Get the initializer for this field
  6503. Expr *const CurFieldInit = *CaptureInitIt++;
  6504. // If there is no initializer, either this is a VLA or an error has
  6505. // occurred.
  6506. if (!CurFieldInit)
  6507. return Error(E);
  6508. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  6509. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  6510. if (!Info.keepEvaluatingAfterFailure())
  6511. return false;
  6512. Success = false;
  6513. }
  6514. ++CaptureIt;
  6515. }
  6516. return Success;
  6517. }
  6518. static bool EvaluateRecord(const Expr *E, const LValue &This,
  6519. APValue &Result, EvalInfo &Info) {
  6520. assert(E->isRValue() && E->getType()->isRecordType() &&
  6521. "can't evaluate expression as a record rvalue");
  6522. return RecordExprEvaluator(Info, This, Result).Visit(E);
  6523. }
  6524. //===----------------------------------------------------------------------===//
  6525. // Temporary Evaluation
  6526. //
  6527. // Temporaries are represented in the AST as rvalues, but generally behave like
  6528. // lvalues. The full-object of which the temporary is a subobject is implicitly
  6529. // materialized so that a reference can bind to it.
  6530. //===----------------------------------------------------------------------===//
  6531. namespace {
  6532. class TemporaryExprEvaluator
  6533. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  6534. public:
  6535. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  6536. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  6537. /// Visit an expression which constructs the value of this temporary.
  6538. bool VisitConstructExpr(const Expr *E) {
  6539. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  6540. return EvaluateInPlace(Value, Info, Result, E);
  6541. }
  6542. bool VisitCastExpr(const CastExpr *E) {
  6543. switch (E->getCastKind()) {
  6544. default:
  6545. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6546. case CK_ConstructorConversion:
  6547. return VisitConstructExpr(E->getSubExpr());
  6548. }
  6549. }
  6550. bool VisitInitListExpr(const InitListExpr *E) {
  6551. return VisitConstructExpr(E);
  6552. }
  6553. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6554. return VisitConstructExpr(E);
  6555. }
  6556. bool VisitCallExpr(const CallExpr *E) {
  6557. return VisitConstructExpr(E);
  6558. }
  6559. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  6560. return VisitConstructExpr(E);
  6561. }
  6562. bool VisitLambdaExpr(const LambdaExpr *E) {
  6563. return VisitConstructExpr(E);
  6564. }
  6565. };
  6566. } // end anonymous namespace
  6567. /// Evaluate an expression of record type as a temporary.
  6568. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  6569. assert(E->isRValue() && E->getType()->isRecordType());
  6570. return TemporaryExprEvaluator(Info, Result).Visit(E);
  6571. }
  6572. //===----------------------------------------------------------------------===//
  6573. // Vector Evaluation
  6574. //===----------------------------------------------------------------------===//
  6575. namespace {
  6576. class VectorExprEvaluator
  6577. : public ExprEvaluatorBase<VectorExprEvaluator> {
  6578. APValue &Result;
  6579. public:
  6580. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  6581. : ExprEvaluatorBaseTy(info), Result(Result) {}
  6582. bool Success(ArrayRef<APValue> V, const Expr *E) {
  6583. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  6584. // FIXME: remove this APValue copy.
  6585. Result = APValue(V.data(), V.size());
  6586. return true;
  6587. }
  6588. bool Success(const APValue &V, const Expr *E) {
  6589. assert(V.isVector());
  6590. Result = V;
  6591. return true;
  6592. }
  6593. bool ZeroInitialization(const Expr *E);
  6594. bool VisitUnaryReal(const UnaryOperator *E)
  6595. { return Visit(E->getSubExpr()); }
  6596. bool VisitCastExpr(const CastExpr* E);
  6597. bool VisitInitListExpr(const InitListExpr *E);
  6598. bool VisitUnaryImag(const UnaryOperator *E);
  6599. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  6600. // binary comparisons, binary and/or/xor,
  6601. // shufflevector, ExtVectorElementExpr
  6602. };
  6603. } // end anonymous namespace
  6604. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  6605. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  6606. return VectorExprEvaluator(Info, Result).Visit(E);
  6607. }
  6608. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6609. const VectorType *VTy = E->getType()->castAs<VectorType>();
  6610. unsigned NElts = VTy->getNumElements();
  6611. const Expr *SE = E->getSubExpr();
  6612. QualType SETy = SE->getType();
  6613. switch (E->getCastKind()) {
  6614. case CK_VectorSplat: {
  6615. APValue Val = APValue();
  6616. if (SETy->isIntegerType()) {
  6617. APSInt IntResult;
  6618. if (!EvaluateInteger(SE, IntResult, Info))
  6619. return false;
  6620. Val = APValue(std::move(IntResult));
  6621. } else if (SETy->isRealFloatingType()) {
  6622. APFloat FloatResult(0.0);
  6623. if (!EvaluateFloat(SE, FloatResult, Info))
  6624. return false;
  6625. Val = APValue(std::move(FloatResult));
  6626. } else {
  6627. return Error(E);
  6628. }
  6629. // Splat and create vector APValue.
  6630. SmallVector<APValue, 4> Elts(NElts, Val);
  6631. return Success(Elts, E);
  6632. }
  6633. case CK_BitCast: {
  6634. // Evaluate the operand into an APInt we can extract from.
  6635. llvm::APInt SValInt;
  6636. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  6637. return false;
  6638. // Extract the elements
  6639. QualType EltTy = VTy->getElementType();
  6640. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  6641. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  6642. SmallVector<APValue, 4> Elts;
  6643. if (EltTy->isRealFloatingType()) {
  6644. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  6645. unsigned FloatEltSize = EltSize;
  6646. if (&Sem == &APFloat::x87DoubleExtended())
  6647. FloatEltSize = 80;
  6648. for (unsigned i = 0; i < NElts; i++) {
  6649. llvm::APInt Elt;
  6650. if (BigEndian)
  6651. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  6652. else
  6653. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  6654. Elts.push_back(APValue(APFloat(Sem, Elt)));
  6655. }
  6656. } else if (EltTy->isIntegerType()) {
  6657. for (unsigned i = 0; i < NElts; i++) {
  6658. llvm::APInt Elt;
  6659. if (BigEndian)
  6660. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  6661. else
  6662. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  6663. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  6664. }
  6665. } else {
  6666. return Error(E);
  6667. }
  6668. return Success(Elts, E);
  6669. }
  6670. default:
  6671. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6672. }
  6673. }
  6674. bool
  6675. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6676. const VectorType *VT = E->getType()->castAs<VectorType>();
  6677. unsigned NumInits = E->getNumInits();
  6678. unsigned NumElements = VT->getNumElements();
  6679. QualType EltTy = VT->getElementType();
  6680. SmallVector<APValue, 4> Elements;
  6681. // The number of initializers can be less than the number of
  6682. // vector elements. For OpenCL, this can be due to nested vector
  6683. // initialization. For GCC compatibility, missing trailing elements
  6684. // should be initialized with zeroes.
  6685. unsigned CountInits = 0, CountElts = 0;
  6686. while (CountElts < NumElements) {
  6687. // Handle nested vector initialization.
  6688. if (CountInits < NumInits
  6689. && E->getInit(CountInits)->getType()->isVectorType()) {
  6690. APValue v;
  6691. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  6692. return Error(E);
  6693. unsigned vlen = v.getVectorLength();
  6694. for (unsigned j = 0; j < vlen; j++)
  6695. Elements.push_back(v.getVectorElt(j));
  6696. CountElts += vlen;
  6697. } else if (EltTy->isIntegerType()) {
  6698. llvm::APSInt sInt(32);
  6699. if (CountInits < NumInits) {
  6700. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6701. return false;
  6702. } else // trailing integer zero.
  6703. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6704. Elements.push_back(APValue(sInt));
  6705. CountElts++;
  6706. } else {
  6707. llvm::APFloat f(0.0);
  6708. if (CountInits < NumInits) {
  6709. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6710. return false;
  6711. } else // trailing float zero.
  6712. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6713. Elements.push_back(APValue(f));
  6714. CountElts++;
  6715. }
  6716. CountInits++;
  6717. }
  6718. return Success(Elements, E);
  6719. }
  6720. bool
  6721. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6722. const VectorType *VT = E->getType()->getAs<VectorType>();
  6723. QualType EltTy = VT->getElementType();
  6724. APValue ZeroElement;
  6725. if (EltTy->isIntegerType())
  6726. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6727. else
  6728. ZeroElement =
  6729. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6730. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6731. return Success(Elements, E);
  6732. }
  6733. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6734. VisitIgnoredValue(E->getSubExpr());
  6735. return ZeroInitialization(E);
  6736. }
  6737. //===----------------------------------------------------------------------===//
  6738. // Array Evaluation
  6739. //===----------------------------------------------------------------------===//
  6740. namespace {
  6741. class ArrayExprEvaluator
  6742. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6743. const LValue &This;
  6744. APValue &Result;
  6745. public:
  6746. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6747. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6748. bool Success(const APValue &V, const Expr *E) {
  6749. assert(V.isArray() && "expected array");
  6750. Result = V;
  6751. return true;
  6752. }
  6753. bool ZeroInitialization(const Expr *E) {
  6754. const ConstantArrayType *CAT =
  6755. Info.Ctx.getAsConstantArrayType(E->getType());
  6756. if (!CAT)
  6757. return Error(E);
  6758. Result = APValue(APValue::UninitArray(), 0,
  6759. CAT->getSize().getZExtValue());
  6760. if (!Result.hasArrayFiller()) return true;
  6761. // Zero-initialize all elements.
  6762. LValue Subobject = This;
  6763. Subobject.addArray(Info, E, CAT);
  6764. ImplicitValueInitExpr VIE(CAT->getElementType());
  6765. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6766. }
  6767. bool VisitCallExpr(const CallExpr *E) {
  6768. return handleCallExpr(E, Result, &This);
  6769. }
  6770. bool VisitInitListExpr(const InitListExpr *E);
  6771. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6772. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6773. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6774. const LValue &Subobject,
  6775. APValue *Value, QualType Type);
  6776. bool VisitStringLiteral(const StringLiteral *E) {
  6777. expandStringLiteral(Info, E, Result);
  6778. return true;
  6779. }
  6780. };
  6781. } // end anonymous namespace
  6782. static bool EvaluateArray(const Expr *E, const LValue &This,
  6783. APValue &Result, EvalInfo &Info) {
  6784. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  6785. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  6786. }
  6787. // Return true iff the given array filler may depend on the element index.
  6788. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  6789. // For now, just whitelist non-class value-initialization and initialization
  6790. // lists comprised of them.
  6791. if (isa<ImplicitValueInitExpr>(FillerExpr))
  6792. return false;
  6793. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  6794. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  6795. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  6796. return true;
  6797. }
  6798. return false;
  6799. }
  6800. return true;
  6801. }
  6802. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6803. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  6804. if (!CAT)
  6805. return Error(E);
  6806. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  6807. // an appropriately-typed string literal enclosed in braces.
  6808. if (E->isStringLiteralInit())
  6809. return Visit(E->getInit(0));
  6810. bool Success = true;
  6811. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  6812. "zero-initialized array shouldn't have any initialized elts");
  6813. APValue Filler;
  6814. if (Result.isArray() && Result.hasArrayFiller())
  6815. Filler = Result.getArrayFiller();
  6816. unsigned NumEltsToInit = E->getNumInits();
  6817. unsigned NumElts = CAT->getSize().getZExtValue();
  6818. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  6819. // If the initializer might depend on the array index, run it for each
  6820. // array element.
  6821. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  6822. NumEltsToInit = NumElts;
  6823. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  6824. << NumEltsToInit << ".\n");
  6825. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  6826. // If the array was previously zero-initialized, preserve the
  6827. // zero-initialized values.
  6828. if (!Filler.isUninit()) {
  6829. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  6830. Result.getArrayInitializedElt(I) = Filler;
  6831. if (Result.hasArrayFiller())
  6832. Result.getArrayFiller() = Filler;
  6833. }
  6834. LValue Subobject = This;
  6835. Subobject.addArray(Info, E, CAT);
  6836. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  6837. const Expr *Init =
  6838. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  6839. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6840. Info, Subobject, Init) ||
  6841. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  6842. CAT->getElementType(), 1)) {
  6843. if (!Info.noteFailure())
  6844. return false;
  6845. Success = false;
  6846. }
  6847. }
  6848. if (!Result.hasArrayFiller())
  6849. return Success;
  6850. // If we get here, we have a trivial filler, which we can just evaluate
  6851. // once and splat over the rest of the array elements.
  6852. assert(FillerExpr && "no array filler for incomplete init list");
  6853. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  6854. FillerExpr) && Success;
  6855. }
  6856. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  6857. if (E->getCommonExpr() &&
  6858. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  6859. Info, E->getCommonExpr()->getSourceExpr()))
  6860. return false;
  6861. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  6862. uint64_t Elements = CAT->getSize().getZExtValue();
  6863. Result = APValue(APValue::UninitArray(), Elements, Elements);
  6864. LValue Subobject = This;
  6865. Subobject.addArray(Info, E, CAT);
  6866. bool Success = true;
  6867. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  6868. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  6869. Info, Subobject, E->getSubExpr()) ||
  6870. !HandleLValueArrayAdjustment(Info, E, Subobject,
  6871. CAT->getElementType(), 1)) {
  6872. if (!Info.noteFailure())
  6873. return false;
  6874. Success = false;
  6875. }
  6876. }
  6877. return Success;
  6878. }
  6879. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6880. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  6881. }
  6882. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6883. const LValue &Subobject,
  6884. APValue *Value,
  6885. QualType Type) {
  6886. bool HadZeroInit = !Value->isUninit();
  6887. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  6888. unsigned N = CAT->getSize().getZExtValue();
  6889. // Preserve the array filler if we had prior zero-initialization.
  6890. APValue Filler =
  6891. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  6892. : APValue();
  6893. *Value = APValue(APValue::UninitArray(), N, N);
  6894. if (HadZeroInit)
  6895. for (unsigned I = 0; I != N; ++I)
  6896. Value->getArrayInitializedElt(I) = Filler;
  6897. // Initialize the elements.
  6898. LValue ArrayElt = Subobject;
  6899. ArrayElt.addArray(Info, E, CAT);
  6900. for (unsigned I = 0; I != N; ++I)
  6901. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  6902. CAT->getElementType()) ||
  6903. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  6904. CAT->getElementType(), 1))
  6905. return false;
  6906. return true;
  6907. }
  6908. if (!Type->isRecordType())
  6909. return Error(E);
  6910. return RecordExprEvaluator(Info, Subobject, *Value)
  6911. .VisitCXXConstructExpr(E, Type);
  6912. }
  6913. //===----------------------------------------------------------------------===//
  6914. // Integer Evaluation
  6915. //
  6916. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  6917. // types and back in constant folding. Integer values are thus represented
  6918. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  6919. //===----------------------------------------------------------------------===//
  6920. namespace {
  6921. class IntExprEvaluator
  6922. : public ExprEvaluatorBase<IntExprEvaluator> {
  6923. APValue &Result;
  6924. public:
  6925. IntExprEvaluator(EvalInfo &info, APValue &result)
  6926. : ExprEvaluatorBaseTy(info), Result(result) {}
  6927. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  6928. assert(E->getType()->isIntegralOrEnumerationType() &&
  6929. "Invalid evaluation result.");
  6930. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  6931. "Invalid evaluation result.");
  6932. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6933. "Invalid evaluation result.");
  6934. Result = APValue(SI);
  6935. return true;
  6936. }
  6937. bool Success(const llvm::APSInt &SI, const Expr *E) {
  6938. return Success(SI, E, Result);
  6939. }
  6940. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  6941. assert(E->getType()->isIntegralOrEnumerationType() &&
  6942. "Invalid evaluation result.");
  6943. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  6944. "Invalid evaluation result.");
  6945. Result = APValue(APSInt(I));
  6946. Result.getInt().setIsUnsigned(
  6947. E->getType()->isUnsignedIntegerOrEnumerationType());
  6948. return true;
  6949. }
  6950. bool Success(const llvm::APInt &I, const Expr *E) {
  6951. return Success(I, E, Result);
  6952. }
  6953. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  6954. assert(E->getType()->isIntegralOrEnumerationType() &&
  6955. "Invalid evaluation result.");
  6956. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  6957. return true;
  6958. }
  6959. bool Success(uint64_t Value, const Expr *E) {
  6960. return Success(Value, E, Result);
  6961. }
  6962. bool Success(CharUnits Size, const Expr *E) {
  6963. return Success(Size.getQuantity(), E);
  6964. }
  6965. bool Success(const APValue &V, const Expr *E) {
  6966. if (V.isLValue() || V.isAddrLabelDiff()) {
  6967. Result = V;
  6968. return true;
  6969. }
  6970. return Success(V.getInt(), E);
  6971. }
  6972. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  6973. //===--------------------------------------------------------------------===//
  6974. // Visitor Methods
  6975. //===--------------------------------------------------------------------===//
  6976. bool VisitConstantExpr(const ConstantExpr *E);
  6977. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  6978. return Success(E->getValue(), E);
  6979. }
  6980. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  6981. return Success(E->getValue(), E);
  6982. }
  6983. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  6984. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  6985. if (CheckReferencedDecl(E, E->getDecl()))
  6986. return true;
  6987. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  6988. }
  6989. bool VisitMemberExpr(const MemberExpr *E) {
  6990. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  6991. VisitIgnoredBaseExpression(E->getBase());
  6992. return true;
  6993. }
  6994. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  6995. }
  6996. bool VisitCallExpr(const CallExpr *E);
  6997. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  6998. bool VisitBinaryOperator(const BinaryOperator *E);
  6999. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  7000. bool VisitUnaryOperator(const UnaryOperator *E);
  7001. bool VisitCastExpr(const CastExpr* E);
  7002. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  7003. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  7004. return Success(E->getValue(), E);
  7005. }
  7006. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  7007. return Success(E->getValue(), E);
  7008. }
  7009. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  7010. if (Info.ArrayInitIndex == uint64_t(-1)) {
  7011. // We were asked to evaluate this subexpression independent of the
  7012. // enclosing ArrayInitLoopExpr. We can't do that.
  7013. Info.FFDiag(E);
  7014. return false;
  7015. }
  7016. return Success(Info.ArrayInitIndex, E);
  7017. }
  7018. // Note, GNU defines __null as an integer, not a pointer.
  7019. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  7020. return ZeroInitialization(E);
  7021. }
  7022. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  7023. return Success(E->getValue(), E);
  7024. }
  7025. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  7026. return Success(E->getValue(), E);
  7027. }
  7028. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  7029. return Success(E->getValue(), E);
  7030. }
  7031. bool VisitUnaryReal(const UnaryOperator *E);
  7032. bool VisitUnaryImag(const UnaryOperator *E);
  7033. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  7034. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  7035. // FIXME: Missing: array subscript of vector, member of vector
  7036. };
  7037. class FixedPointExprEvaluator
  7038. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  7039. APValue &Result;
  7040. public:
  7041. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  7042. : ExprEvaluatorBaseTy(info), Result(result) {}
  7043. bool Success(const llvm::APInt &I, const Expr *E) {
  7044. return Success(
  7045. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7046. }
  7047. bool Success(uint64_t Value, const Expr *E) {
  7048. return Success(
  7049. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7050. }
  7051. bool Success(const APValue &V, const Expr *E) {
  7052. return Success(V.getFixedPoint(), E);
  7053. }
  7054. bool Success(const APFixedPoint &V, const Expr *E) {
  7055. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  7056. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7057. "Invalid evaluation result.");
  7058. Result = APValue(V);
  7059. return true;
  7060. }
  7061. //===--------------------------------------------------------------------===//
  7062. // Visitor Methods
  7063. //===--------------------------------------------------------------------===//
  7064. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  7065. return Success(E->getValue(), E);
  7066. }
  7067. bool VisitCastExpr(const CastExpr *E);
  7068. bool VisitUnaryOperator(const UnaryOperator *E);
  7069. bool VisitBinaryOperator(const BinaryOperator *E);
  7070. };
  7071. } // end anonymous namespace
  7072. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  7073. /// produce either the integer value or a pointer.
  7074. ///
  7075. /// GCC has a heinous extension which folds casts between pointer types and
  7076. /// pointer-sized integral types. We support this by allowing the evaluation of
  7077. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  7078. /// Some simple arithmetic on such values is supported (they are treated much
  7079. /// like char*).
  7080. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  7081. EvalInfo &Info) {
  7082. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  7083. return IntExprEvaluator(Info, Result).Visit(E);
  7084. }
  7085. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  7086. APValue Val;
  7087. if (!EvaluateIntegerOrLValue(E, Val, Info))
  7088. return false;
  7089. if (!Val.isInt()) {
  7090. // FIXME: It would be better to produce the diagnostic for casting
  7091. // a pointer to an integer.
  7092. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7093. return false;
  7094. }
  7095. Result = Val.getInt();
  7096. return true;
  7097. }
  7098. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  7099. EvalInfo &Info) {
  7100. if (E->getType()->isFixedPointType()) {
  7101. APValue Val;
  7102. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  7103. return false;
  7104. if (!Val.isFixedPoint())
  7105. return false;
  7106. Result = Val.getFixedPoint();
  7107. return true;
  7108. }
  7109. return false;
  7110. }
  7111. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  7112. EvalInfo &Info) {
  7113. if (E->getType()->isIntegerType()) {
  7114. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  7115. APSInt Val;
  7116. if (!EvaluateInteger(E, Val, Info))
  7117. return false;
  7118. Result = APFixedPoint(Val, FXSema);
  7119. return true;
  7120. } else if (E->getType()->isFixedPointType()) {
  7121. return EvaluateFixedPoint(E, Result, Info);
  7122. }
  7123. return false;
  7124. }
  7125. /// Check whether the given declaration can be directly converted to an integral
  7126. /// rvalue. If not, no diagnostic is produced; there are other things we can
  7127. /// try.
  7128. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  7129. // Enums are integer constant exprs.
  7130. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  7131. // Check for signedness/width mismatches between E type and ECD value.
  7132. bool SameSign = (ECD->getInitVal().isSigned()
  7133. == E->getType()->isSignedIntegerOrEnumerationType());
  7134. bool SameWidth = (ECD->getInitVal().getBitWidth()
  7135. == Info.Ctx.getIntWidth(E->getType()));
  7136. if (SameSign && SameWidth)
  7137. return Success(ECD->getInitVal(), E);
  7138. else {
  7139. // Get rid of mismatch (otherwise Success assertions will fail)
  7140. // by computing a new value matching the type of E.
  7141. llvm::APSInt Val = ECD->getInitVal();
  7142. if (!SameSign)
  7143. Val.setIsSigned(!ECD->getInitVal().isSigned());
  7144. if (!SameWidth)
  7145. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  7146. return Success(Val, E);
  7147. }
  7148. }
  7149. return false;
  7150. }
  7151. /// Values returned by __builtin_classify_type, chosen to match the values
  7152. /// produced by GCC's builtin.
  7153. enum class GCCTypeClass {
  7154. None = -1,
  7155. Void = 0,
  7156. Integer = 1,
  7157. // GCC reserves 2 for character types, but instead classifies them as
  7158. // integers.
  7159. Enum = 3,
  7160. Bool = 4,
  7161. Pointer = 5,
  7162. // GCC reserves 6 for references, but appears to never use it (because
  7163. // expressions never have reference type, presumably).
  7164. PointerToDataMember = 7,
  7165. RealFloat = 8,
  7166. Complex = 9,
  7167. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  7168. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7169. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  7170. // uses 12 for that purpose, same as for a class or struct. Maybe it
  7171. // internally implements a pointer to member as a struct? Who knows.
  7172. PointerToMemberFunction = 12, // Not a bug, see above.
  7173. ClassOrStruct = 12,
  7174. Union = 13,
  7175. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  7176. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7177. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  7178. // literals.
  7179. };
  7180. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7181. /// as GCC.
  7182. static GCCTypeClass
  7183. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  7184. assert(!T->isDependentType() && "unexpected dependent type");
  7185. QualType CanTy = T.getCanonicalType();
  7186. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  7187. switch (CanTy->getTypeClass()) {
  7188. #define TYPE(ID, BASE)
  7189. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7190. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  7191. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7192. #include "clang/AST/TypeNodes.def"
  7193. case Type::Auto:
  7194. case Type::DeducedTemplateSpecialization:
  7195. llvm_unreachable("unexpected non-canonical or dependent type");
  7196. case Type::Builtin:
  7197. switch (BT->getKind()) {
  7198. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  7199. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  7200. case BuiltinType::ID: return GCCTypeClass::Integer;
  7201. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  7202. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  7203. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  7204. case BuiltinType::ID: break;
  7205. #include "clang/AST/BuiltinTypes.def"
  7206. case BuiltinType::Void:
  7207. return GCCTypeClass::Void;
  7208. case BuiltinType::Bool:
  7209. return GCCTypeClass::Bool;
  7210. case BuiltinType::Char_U:
  7211. case BuiltinType::UChar:
  7212. case BuiltinType::WChar_U:
  7213. case BuiltinType::Char8:
  7214. case BuiltinType::Char16:
  7215. case BuiltinType::Char32:
  7216. case BuiltinType::UShort:
  7217. case BuiltinType::UInt:
  7218. case BuiltinType::ULong:
  7219. case BuiltinType::ULongLong:
  7220. case BuiltinType::UInt128:
  7221. return GCCTypeClass::Integer;
  7222. case BuiltinType::UShortAccum:
  7223. case BuiltinType::UAccum:
  7224. case BuiltinType::ULongAccum:
  7225. case BuiltinType::UShortFract:
  7226. case BuiltinType::UFract:
  7227. case BuiltinType::ULongFract:
  7228. case BuiltinType::SatUShortAccum:
  7229. case BuiltinType::SatUAccum:
  7230. case BuiltinType::SatULongAccum:
  7231. case BuiltinType::SatUShortFract:
  7232. case BuiltinType::SatUFract:
  7233. case BuiltinType::SatULongFract:
  7234. return GCCTypeClass::None;
  7235. case BuiltinType::NullPtr:
  7236. case BuiltinType::ObjCId:
  7237. case BuiltinType::ObjCClass:
  7238. case BuiltinType::ObjCSel:
  7239. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  7240. case BuiltinType::Id:
  7241. #include "clang/Basic/OpenCLImageTypes.def"
  7242. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  7243. case BuiltinType::Id:
  7244. #include "clang/Basic/OpenCLExtensionTypes.def"
  7245. case BuiltinType::OCLSampler:
  7246. case BuiltinType::OCLEvent:
  7247. case BuiltinType::OCLClkEvent:
  7248. case BuiltinType::OCLQueue:
  7249. case BuiltinType::OCLReserveID:
  7250. return GCCTypeClass::None;
  7251. case BuiltinType::Dependent:
  7252. llvm_unreachable("unexpected dependent type");
  7253. };
  7254. llvm_unreachable("unexpected placeholder type");
  7255. case Type::Enum:
  7256. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  7257. case Type::Pointer:
  7258. case Type::ConstantArray:
  7259. case Type::VariableArray:
  7260. case Type::IncompleteArray:
  7261. case Type::FunctionNoProto:
  7262. case Type::FunctionProto:
  7263. return GCCTypeClass::Pointer;
  7264. case Type::MemberPointer:
  7265. return CanTy->isMemberDataPointerType()
  7266. ? GCCTypeClass::PointerToDataMember
  7267. : GCCTypeClass::PointerToMemberFunction;
  7268. case Type::Complex:
  7269. return GCCTypeClass::Complex;
  7270. case Type::Record:
  7271. return CanTy->isUnionType() ? GCCTypeClass::Union
  7272. : GCCTypeClass::ClassOrStruct;
  7273. case Type::Atomic:
  7274. // GCC classifies _Atomic T the same as T.
  7275. return EvaluateBuiltinClassifyType(
  7276. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  7277. case Type::BlockPointer:
  7278. case Type::Vector:
  7279. case Type::ExtVector:
  7280. case Type::ObjCObject:
  7281. case Type::ObjCInterface:
  7282. case Type::ObjCObjectPointer:
  7283. case Type::Pipe:
  7284. // GCC classifies vectors as None. We follow its lead and classify all
  7285. // other types that don't fit into the regular classification the same way.
  7286. return GCCTypeClass::None;
  7287. case Type::LValueReference:
  7288. case Type::RValueReference:
  7289. llvm_unreachable("invalid type for expression");
  7290. }
  7291. llvm_unreachable("unexpected type class");
  7292. }
  7293. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7294. /// as GCC.
  7295. static GCCTypeClass
  7296. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  7297. // If no argument was supplied, default to None. This isn't
  7298. // ideal, however it is what gcc does.
  7299. if (E->getNumArgs() == 0)
  7300. return GCCTypeClass::None;
  7301. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  7302. // being an ICE, but still folds it to a constant using the type of the first
  7303. // argument.
  7304. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  7305. }
  7306. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  7307. /// __builtin_constant_p when applied to the given pointer.
  7308. ///
  7309. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  7310. /// or it points to the first character of a string literal.
  7311. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  7312. APValue::LValueBase Base = LV.getLValueBase();
  7313. if (Base.isNull()) {
  7314. // A null base is acceptable.
  7315. return true;
  7316. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  7317. if (!isa<StringLiteral>(E))
  7318. return false;
  7319. return LV.getLValueOffset().isZero();
  7320. } else {
  7321. // Any other base is not constant enough for GCC.
  7322. return false;
  7323. }
  7324. }
  7325. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  7326. /// GCC as we can manage.
  7327. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  7328. // This evaluation is not permitted to have side-effects, so evaluate it in
  7329. // a speculative evaluation context.
  7330. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7331. // Constant-folding is always enabled for the operand of __builtin_constant_p
  7332. // (even when the enclosing evaluation context otherwise requires a strict
  7333. // language-specific constant expression).
  7334. FoldConstant Fold(Info, true);
  7335. QualType ArgType = Arg->getType();
  7336. // __builtin_constant_p always has one operand. The rules which gcc follows
  7337. // are not precisely documented, but are as follows:
  7338. //
  7339. // - If the operand is of integral, floating, complex or enumeration type,
  7340. // and can be folded to a known value of that type, it returns 1.
  7341. // - If the operand can be folded to a pointer to the first character
  7342. // of a string literal (or such a pointer cast to an integral type)
  7343. // or to a null pointer or an integer cast to a pointer, it returns 1.
  7344. //
  7345. // Otherwise, it returns 0.
  7346. //
  7347. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  7348. // its support for this did not work prior to GCC 9 and is not yet well
  7349. // understood.
  7350. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  7351. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  7352. ArgType->isNullPtrType()) {
  7353. APValue V;
  7354. if (!::EvaluateAsRValue(Info, Arg, V)) {
  7355. Fold.keepDiagnostics();
  7356. return false;
  7357. }
  7358. // For a pointer (possibly cast to integer), there are special rules.
  7359. if (V.getKind() == APValue::LValue)
  7360. return EvaluateBuiltinConstantPForLValue(V);
  7361. // Otherwise, any constant value is good enough.
  7362. return V.getKind() != APValue::Uninitialized;
  7363. }
  7364. // Anything else isn't considered to be sufficiently constant.
  7365. return false;
  7366. }
  7367. /// Retrieves the "underlying object type" of the given expression,
  7368. /// as used by __builtin_object_size.
  7369. static QualType getObjectType(APValue::LValueBase B) {
  7370. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  7371. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  7372. return VD->getType();
  7373. } else if (const Expr *E = B.get<const Expr*>()) {
  7374. if (isa<CompoundLiteralExpr>(E))
  7375. return E->getType();
  7376. }
  7377. return QualType();
  7378. }
  7379. /// A more selective version of E->IgnoreParenCasts for
  7380. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  7381. /// to change the type of E.
  7382. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  7383. ///
  7384. /// Always returns an RValue with a pointer representation.
  7385. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  7386. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  7387. auto *NoParens = E->IgnoreParens();
  7388. auto *Cast = dyn_cast<CastExpr>(NoParens);
  7389. if (Cast == nullptr)
  7390. return NoParens;
  7391. // We only conservatively allow a few kinds of casts, because this code is
  7392. // inherently a simple solution that seeks to support the common case.
  7393. auto CastKind = Cast->getCastKind();
  7394. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  7395. CastKind != CK_AddressSpaceConversion)
  7396. return NoParens;
  7397. auto *SubExpr = Cast->getSubExpr();
  7398. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  7399. return NoParens;
  7400. return ignorePointerCastsAndParens(SubExpr);
  7401. }
  7402. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  7403. /// record layout. e.g.
  7404. /// struct { struct { int a, b; } fst, snd; } obj;
  7405. /// obj.fst // no
  7406. /// obj.snd // yes
  7407. /// obj.fst.a // no
  7408. /// obj.fst.b // no
  7409. /// obj.snd.a // no
  7410. /// obj.snd.b // yes
  7411. ///
  7412. /// Please note: this function is specialized for how __builtin_object_size
  7413. /// views "objects".
  7414. ///
  7415. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  7416. /// correct result, it will always return true.
  7417. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  7418. assert(!LVal.Designator.Invalid);
  7419. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  7420. const RecordDecl *Parent = FD->getParent();
  7421. Invalid = Parent->isInvalidDecl();
  7422. if (Invalid || Parent->isUnion())
  7423. return true;
  7424. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  7425. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  7426. };
  7427. auto &Base = LVal.getLValueBase();
  7428. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  7429. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  7430. bool Invalid;
  7431. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  7432. return Invalid;
  7433. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  7434. for (auto *FD : IFD->chain()) {
  7435. bool Invalid;
  7436. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  7437. return Invalid;
  7438. }
  7439. }
  7440. }
  7441. unsigned I = 0;
  7442. QualType BaseType = getType(Base);
  7443. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  7444. // If we don't know the array bound, conservatively assume we're looking at
  7445. // the final array element.
  7446. ++I;
  7447. if (BaseType->isIncompleteArrayType())
  7448. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  7449. else
  7450. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  7451. }
  7452. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  7453. const auto &Entry = LVal.Designator.Entries[I];
  7454. if (BaseType->isArrayType()) {
  7455. // Because __builtin_object_size treats arrays as objects, we can ignore
  7456. // the index iff this is the last array in the Designator.
  7457. if (I + 1 == E)
  7458. return true;
  7459. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  7460. uint64_t Index = Entry.getAsArrayIndex();
  7461. if (Index + 1 != CAT->getSize())
  7462. return false;
  7463. BaseType = CAT->getElementType();
  7464. } else if (BaseType->isAnyComplexType()) {
  7465. const auto *CT = BaseType->castAs<ComplexType>();
  7466. uint64_t Index = Entry.getAsArrayIndex();
  7467. if (Index != 1)
  7468. return false;
  7469. BaseType = CT->getElementType();
  7470. } else if (auto *FD = getAsField(Entry)) {
  7471. bool Invalid;
  7472. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  7473. return Invalid;
  7474. BaseType = FD->getType();
  7475. } else {
  7476. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  7477. return false;
  7478. }
  7479. }
  7480. return true;
  7481. }
  7482. /// Tests to see if the LValue has a user-specified designator (that isn't
  7483. /// necessarily valid). Note that this always returns 'true' if the LValue has
  7484. /// an unsized array as its first designator entry, because there's currently no
  7485. /// way to tell if the user typed *foo or foo[0].
  7486. static bool refersToCompleteObject(const LValue &LVal) {
  7487. if (LVal.Designator.Invalid)
  7488. return false;
  7489. if (!LVal.Designator.Entries.empty())
  7490. return LVal.Designator.isMostDerivedAnUnsizedArray();
  7491. if (!LVal.InvalidBase)
  7492. return true;
  7493. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  7494. // the LValueBase.
  7495. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  7496. return !E || !isa<MemberExpr>(E);
  7497. }
  7498. /// Attempts to detect a user writing into a piece of memory that's impossible
  7499. /// to figure out the size of by just using types.
  7500. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  7501. const SubobjectDesignator &Designator = LVal.Designator;
  7502. // Notes:
  7503. // - Users can only write off of the end when we have an invalid base. Invalid
  7504. // bases imply we don't know where the memory came from.
  7505. // - We used to be a bit more aggressive here; we'd only be conservative if
  7506. // the array at the end was flexible, or if it had 0 or 1 elements. This
  7507. // broke some common standard library extensions (PR30346), but was
  7508. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  7509. // with some sort of whitelist. OTOH, it seems that GCC is always
  7510. // conservative with the last element in structs (if it's an array), so our
  7511. // current behavior is more compatible than a whitelisting approach would
  7512. // be.
  7513. return LVal.InvalidBase &&
  7514. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  7515. Designator.MostDerivedIsArrayElement &&
  7516. isDesignatorAtObjectEnd(Ctx, LVal);
  7517. }
  7518. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  7519. /// Fails if the conversion would cause loss of precision.
  7520. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  7521. CharUnits &Result) {
  7522. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  7523. if (Int.ugt(CharUnitsMax))
  7524. return false;
  7525. Result = CharUnits::fromQuantity(Int.getZExtValue());
  7526. return true;
  7527. }
  7528. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  7529. /// determine how many bytes exist from the beginning of the object to either
  7530. /// the end of the current subobject, or the end of the object itself, depending
  7531. /// on what the LValue looks like + the value of Type.
  7532. ///
  7533. /// If this returns false, the value of Result is undefined.
  7534. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  7535. unsigned Type, const LValue &LVal,
  7536. CharUnits &EndOffset) {
  7537. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  7538. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  7539. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  7540. return false;
  7541. return HandleSizeof(Info, ExprLoc, Ty, Result);
  7542. };
  7543. // We want to evaluate the size of the entire object. This is a valid fallback
  7544. // for when Type=1 and the designator is invalid, because we're asked for an
  7545. // upper-bound.
  7546. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  7547. // Type=3 wants a lower bound, so we can't fall back to this.
  7548. if (Type == 3 && !DetermineForCompleteObject)
  7549. return false;
  7550. llvm::APInt APEndOffset;
  7551. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7552. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7553. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7554. if (LVal.InvalidBase)
  7555. return false;
  7556. QualType BaseTy = getObjectType(LVal.getLValueBase());
  7557. return CheckedHandleSizeof(BaseTy, EndOffset);
  7558. }
  7559. // We want to evaluate the size of a subobject.
  7560. const SubobjectDesignator &Designator = LVal.Designator;
  7561. // The following is a moderately common idiom in C:
  7562. //
  7563. // struct Foo { int a; char c[1]; };
  7564. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  7565. // strcpy(&F->c[0], Bar);
  7566. //
  7567. // In order to not break too much legacy code, we need to support it.
  7568. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  7569. // If we can resolve this to an alloc_size call, we can hand that back,
  7570. // because we know for certain how many bytes there are to write to.
  7571. llvm::APInt APEndOffset;
  7572. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7573. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7574. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7575. // If we cannot determine the size of the initial allocation, then we can't
  7576. // given an accurate upper-bound. However, we are still able to give
  7577. // conservative lower-bounds for Type=3.
  7578. if (Type == 1)
  7579. return false;
  7580. }
  7581. CharUnits BytesPerElem;
  7582. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  7583. return false;
  7584. // According to the GCC documentation, we want the size of the subobject
  7585. // denoted by the pointer. But that's not quite right -- what we actually
  7586. // want is the size of the immediately-enclosing array, if there is one.
  7587. int64_t ElemsRemaining;
  7588. if (Designator.MostDerivedIsArrayElement &&
  7589. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  7590. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  7591. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  7592. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  7593. } else {
  7594. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  7595. }
  7596. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  7597. return true;
  7598. }
  7599. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  7600. /// returns true and stores the result in @p Size.
  7601. ///
  7602. /// If @p WasError is non-null, this will report whether the failure to evaluate
  7603. /// is to be treated as an Error in IntExprEvaluator.
  7604. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  7605. EvalInfo &Info, uint64_t &Size) {
  7606. // Determine the denoted object.
  7607. LValue LVal;
  7608. {
  7609. // The operand of __builtin_object_size is never evaluated for side-effects.
  7610. // If there are any, but we can determine the pointed-to object anyway, then
  7611. // ignore the side-effects.
  7612. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7613. IgnoreSideEffectsRAII Fold(Info);
  7614. if (E->isGLValue()) {
  7615. // It's possible for us to be given GLValues if we're called via
  7616. // Expr::tryEvaluateObjectSize.
  7617. APValue RVal;
  7618. if (!EvaluateAsRValue(Info, E, RVal))
  7619. return false;
  7620. LVal.setFrom(Info.Ctx, RVal);
  7621. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  7622. /*InvalidBaseOK=*/true))
  7623. return false;
  7624. }
  7625. // If we point to before the start of the object, there are no accessible
  7626. // bytes.
  7627. if (LVal.getLValueOffset().isNegative()) {
  7628. Size = 0;
  7629. return true;
  7630. }
  7631. CharUnits EndOffset;
  7632. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  7633. return false;
  7634. // If we've fallen outside of the end offset, just pretend there's nothing to
  7635. // write to/read from.
  7636. if (EndOffset <= LVal.getLValueOffset())
  7637. Size = 0;
  7638. else
  7639. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  7640. return true;
  7641. }
  7642. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  7643. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  7644. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  7645. }
  7646. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7647. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7648. return VisitBuiltinCallExpr(E, BuiltinOp);
  7649. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7650. }
  7651. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7652. unsigned BuiltinOp) {
  7653. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  7654. default:
  7655. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7656. case Builtin::BI__builtin_dynamic_object_size:
  7657. case Builtin::BI__builtin_object_size: {
  7658. // The type was checked when we built the expression.
  7659. unsigned Type =
  7660. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7661. assert(Type <= 3 && "unexpected type");
  7662. uint64_t Size;
  7663. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  7664. return Success(Size, E);
  7665. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  7666. return Success((Type & 2) ? 0 : -1, E);
  7667. // Expression had no side effects, but we couldn't statically determine the
  7668. // size of the referenced object.
  7669. switch (Info.EvalMode) {
  7670. case EvalInfo::EM_ConstantExpression:
  7671. case EvalInfo::EM_PotentialConstantExpression:
  7672. case EvalInfo::EM_ConstantFold:
  7673. case EvalInfo::EM_EvaluateForOverflow:
  7674. case EvalInfo::EM_IgnoreSideEffects:
  7675. // Leave it to IR generation.
  7676. return Error(E);
  7677. case EvalInfo::EM_ConstantExpressionUnevaluated:
  7678. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  7679. // Reduce it to a constant now.
  7680. return Success((Type & 2) ? 0 : -1, E);
  7681. }
  7682. llvm_unreachable("unexpected EvalMode");
  7683. }
  7684. case Builtin::BI__builtin_os_log_format_buffer_size: {
  7685. analyze_os_log::OSLogBufferLayout Layout;
  7686. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  7687. return Success(Layout.size().getQuantity(), E);
  7688. }
  7689. case Builtin::BI__builtin_bswap16:
  7690. case Builtin::BI__builtin_bswap32:
  7691. case Builtin::BI__builtin_bswap64: {
  7692. APSInt Val;
  7693. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7694. return false;
  7695. return Success(Val.byteSwap(), E);
  7696. }
  7697. case Builtin::BI__builtin_classify_type:
  7698. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  7699. case Builtin::BI__builtin_clrsb:
  7700. case Builtin::BI__builtin_clrsbl:
  7701. case Builtin::BI__builtin_clrsbll: {
  7702. APSInt Val;
  7703. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7704. return false;
  7705. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  7706. }
  7707. case Builtin::BI__builtin_clz:
  7708. case Builtin::BI__builtin_clzl:
  7709. case Builtin::BI__builtin_clzll:
  7710. case Builtin::BI__builtin_clzs: {
  7711. APSInt Val;
  7712. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7713. return false;
  7714. if (!Val)
  7715. return Error(E);
  7716. return Success(Val.countLeadingZeros(), E);
  7717. }
  7718. case Builtin::BI__builtin_constant_p: {
  7719. const Expr *Arg = E->getArg(0);
  7720. if (EvaluateBuiltinConstantP(Info, Arg))
  7721. return Success(true, E);
  7722. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  7723. // Outside a constant context, eagerly evaluate to false in the presence
  7724. // of side-effects in order to avoid -Wunsequenced false-positives in
  7725. // a branch on __builtin_constant_p(expr).
  7726. return Success(false, E);
  7727. }
  7728. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7729. return false;
  7730. }
  7731. case Builtin::BI__builtin_is_constant_evaluated:
  7732. return Success(Info.InConstantContext, E);
  7733. case Builtin::BI__builtin_ctz:
  7734. case Builtin::BI__builtin_ctzl:
  7735. case Builtin::BI__builtin_ctzll:
  7736. case Builtin::BI__builtin_ctzs: {
  7737. APSInt Val;
  7738. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7739. return false;
  7740. if (!Val)
  7741. return Error(E);
  7742. return Success(Val.countTrailingZeros(), E);
  7743. }
  7744. case Builtin::BI__builtin_eh_return_data_regno: {
  7745. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7746. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7747. return Success(Operand, E);
  7748. }
  7749. case Builtin::BI__builtin_expect:
  7750. return Visit(E->getArg(0));
  7751. case Builtin::BI__builtin_ffs:
  7752. case Builtin::BI__builtin_ffsl:
  7753. case Builtin::BI__builtin_ffsll: {
  7754. APSInt Val;
  7755. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7756. return false;
  7757. unsigned N = Val.countTrailingZeros();
  7758. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7759. }
  7760. case Builtin::BI__builtin_fpclassify: {
  7761. APFloat Val(0.0);
  7762. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7763. return false;
  7764. unsigned Arg;
  7765. switch (Val.getCategory()) {
  7766. case APFloat::fcNaN: Arg = 0; break;
  7767. case APFloat::fcInfinity: Arg = 1; break;
  7768. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7769. case APFloat::fcZero: Arg = 4; break;
  7770. }
  7771. return Visit(E->getArg(Arg));
  7772. }
  7773. case Builtin::BI__builtin_isinf_sign: {
  7774. APFloat Val(0.0);
  7775. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7776. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  7777. }
  7778. case Builtin::BI__builtin_isinf: {
  7779. APFloat Val(0.0);
  7780. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7781. Success(Val.isInfinity() ? 1 : 0, E);
  7782. }
  7783. case Builtin::BI__builtin_isfinite: {
  7784. APFloat Val(0.0);
  7785. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7786. Success(Val.isFinite() ? 1 : 0, E);
  7787. }
  7788. case Builtin::BI__builtin_isnan: {
  7789. APFloat Val(0.0);
  7790. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7791. Success(Val.isNaN() ? 1 : 0, E);
  7792. }
  7793. case Builtin::BI__builtin_isnormal: {
  7794. APFloat Val(0.0);
  7795. return EvaluateFloat(E->getArg(0), Val, Info) &&
  7796. Success(Val.isNormal() ? 1 : 0, E);
  7797. }
  7798. case Builtin::BI__builtin_parity:
  7799. case Builtin::BI__builtin_parityl:
  7800. case Builtin::BI__builtin_parityll: {
  7801. APSInt Val;
  7802. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7803. return false;
  7804. return Success(Val.countPopulation() % 2, E);
  7805. }
  7806. case Builtin::BI__builtin_popcount:
  7807. case Builtin::BI__builtin_popcountl:
  7808. case Builtin::BI__builtin_popcountll: {
  7809. APSInt Val;
  7810. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7811. return false;
  7812. return Success(Val.countPopulation(), E);
  7813. }
  7814. case Builtin::BIstrlen:
  7815. case Builtin::BIwcslen:
  7816. // A call to strlen is not a constant expression.
  7817. if (Info.getLangOpts().CPlusPlus11)
  7818. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7819. << /*isConstexpr*/0 << /*isConstructor*/0
  7820. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7821. else
  7822. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7823. LLVM_FALLTHROUGH;
  7824. case Builtin::BI__builtin_strlen:
  7825. case Builtin::BI__builtin_wcslen: {
  7826. // As an extension, we support __builtin_strlen() as a constant expression,
  7827. // and support folding strlen() to a constant.
  7828. LValue String;
  7829. if (!EvaluatePointer(E->getArg(0), String, Info))
  7830. return false;
  7831. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  7832. // Fast path: if it's a string literal, search the string value.
  7833. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  7834. String.getLValueBase().dyn_cast<const Expr *>())) {
  7835. // The string literal may have embedded null characters. Find the first
  7836. // one and truncate there.
  7837. StringRef Str = S->getBytes();
  7838. int64_t Off = String.Offset.getQuantity();
  7839. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  7840. S->getCharByteWidth() == 1 &&
  7841. // FIXME: Add fast-path for wchar_t too.
  7842. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  7843. Str = Str.substr(Off);
  7844. StringRef::size_type Pos = Str.find(0);
  7845. if (Pos != StringRef::npos)
  7846. Str = Str.substr(0, Pos);
  7847. return Success(Str.size(), E);
  7848. }
  7849. // Fall through to slow path to issue appropriate diagnostic.
  7850. }
  7851. // Slow path: scan the bytes of the string looking for the terminating 0.
  7852. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  7853. APValue Char;
  7854. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  7855. !Char.isInt())
  7856. return false;
  7857. if (!Char.getInt())
  7858. return Success(Strlen, E);
  7859. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  7860. return false;
  7861. }
  7862. }
  7863. case Builtin::BIstrcmp:
  7864. case Builtin::BIwcscmp:
  7865. case Builtin::BIstrncmp:
  7866. case Builtin::BIwcsncmp:
  7867. case Builtin::BImemcmp:
  7868. case Builtin::BIbcmp:
  7869. case Builtin::BIwmemcmp:
  7870. // A call to strlen is not a constant expression.
  7871. if (Info.getLangOpts().CPlusPlus11)
  7872. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  7873. << /*isConstexpr*/0 << /*isConstructor*/0
  7874. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  7875. else
  7876. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7877. LLVM_FALLTHROUGH;
  7878. case Builtin::BI__builtin_strcmp:
  7879. case Builtin::BI__builtin_wcscmp:
  7880. case Builtin::BI__builtin_strncmp:
  7881. case Builtin::BI__builtin_wcsncmp:
  7882. case Builtin::BI__builtin_memcmp:
  7883. case Builtin::BI__builtin_bcmp:
  7884. case Builtin::BI__builtin_wmemcmp: {
  7885. LValue String1, String2;
  7886. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  7887. !EvaluatePointer(E->getArg(1), String2, Info))
  7888. return false;
  7889. uint64_t MaxLength = uint64_t(-1);
  7890. if (BuiltinOp != Builtin::BIstrcmp &&
  7891. BuiltinOp != Builtin::BIwcscmp &&
  7892. BuiltinOp != Builtin::BI__builtin_strcmp &&
  7893. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  7894. APSInt N;
  7895. if (!EvaluateInteger(E->getArg(2), N, Info))
  7896. return false;
  7897. MaxLength = N.getExtValue();
  7898. }
  7899. // Empty substrings compare equal by definition.
  7900. if (MaxLength == 0u)
  7901. return Success(0, E);
  7902. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  7903. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  7904. String1.Designator.Invalid || String2.Designator.Invalid)
  7905. return false;
  7906. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  7907. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  7908. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  7909. BuiltinOp == Builtin::BIbcmp ||
  7910. BuiltinOp == Builtin::BI__builtin_memcmp ||
  7911. BuiltinOp == Builtin::BI__builtin_bcmp;
  7912. assert(IsRawByte ||
  7913. (Info.Ctx.hasSameUnqualifiedType(
  7914. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  7915. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  7916. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  7917. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  7918. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  7919. Char1.isInt() && Char2.isInt();
  7920. };
  7921. const auto &AdvanceElems = [&] {
  7922. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  7923. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  7924. };
  7925. if (IsRawByte) {
  7926. uint64_t BytesRemaining = MaxLength;
  7927. // Pointers to const void may point to objects of incomplete type.
  7928. if (CharTy1->isIncompleteType()) {
  7929. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  7930. return false;
  7931. }
  7932. if (CharTy2->isIncompleteType()) {
  7933. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  7934. return false;
  7935. }
  7936. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  7937. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  7938. // Give up on comparing between elements with disparate widths.
  7939. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  7940. return false;
  7941. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  7942. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  7943. "following loop considers at least one element");
  7944. while (true) {
  7945. APValue Char1, Char2;
  7946. if (!ReadCurElems(Char1, Char2))
  7947. return false;
  7948. // We have compatible in-memory widths, but a possible type and
  7949. // (for `bool`) internal representation mismatch.
  7950. // Assuming two's complement representation, including 0 for `false` and
  7951. // 1 for `true`, we can check an appropriate number of elements for
  7952. // equality even if they are not byte-sized.
  7953. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  7954. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  7955. if (Char1InMem.ne(Char2InMem)) {
  7956. // If the elements are byte-sized, then we can produce a three-way
  7957. // comparison result in a straightforward manner.
  7958. if (BytesPerElement == 1u) {
  7959. // memcmp always compares unsigned chars.
  7960. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  7961. }
  7962. // The result is byte-order sensitive, and we have multibyte elements.
  7963. // FIXME: We can compare the remaining bytes in the correct order.
  7964. return false;
  7965. }
  7966. if (!AdvanceElems())
  7967. return false;
  7968. if (BytesRemaining <= BytesPerElement)
  7969. break;
  7970. BytesRemaining -= BytesPerElement;
  7971. }
  7972. // Enough elements are equal to account for the memcmp limit.
  7973. return Success(0, E);
  7974. }
  7975. bool StopAtNull =
  7976. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  7977. BuiltinOp != Builtin::BIwmemcmp &&
  7978. BuiltinOp != Builtin::BI__builtin_memcmp &&
  7979. BuiltinOp != Builtin::BI__builtin_bcmp &&
  7980. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  7981. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  7982. BuiltinOp == Builtin::BIwcsncmp ||
  7983. BuiltinOp == Builtin::BIwmemcmp ||
  7984. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  7985. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  7986. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  7987. for (; MaxLength; --MaxLength) {
  7988. APValue Char1, Char2;
  7989. if (!ReadCurElems(Char1, Char2))
  7990. return false;
  7991. if (Char1.getInt() != Char2.getInt()) {
  7992. if (IsWide) // wmemcmp compares with wchar_t signedness.
  7993. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  7994. // memcmp always compares unsigned chars.
  7995. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  7996. }
  7997. if (StopAtNull && !Char1.getInt())
  7998. return Success(0, E);
  7999. assert(!(StopAtNull && !Char2.getInt()));
  8000. if (!AdvanceElems())
  8001. return false;
  8002. }
  8003. // We hit the strncmp / memcmp limit.
  8004. return Success(0, E);
  8005. }
  8006. case Builtin::BI__atomic_always_lock_free:
  8007. case Builtin::BI__atomic_is_lock_free:
  8008. case Builtin::BI__c11_atomic_is_lock_free: {
  8009. APSInt SizeVal;
  8010. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  8011. return false;
  8012. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  8013. // of two less than the maximum inline atomic width, we know it is
  8014. // lock-free. If the size isn't a power of two, or greater than the
  8015. // maximum alignment where we promote atomics, we know it is not lock-free
  8016. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  8017. // the answer can only be determined at runtime; for example, 16-byte
  8018. // atomics have lock-free implementations on some, but not all,
  8019. // x86-64 processors.
  8020. // Check power-of-two.
  8021. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  8022. if (Size.isPowerOfTwo()) {
  8023. // Check against inlining width.
  8024. unsigned InlineWidthBits =
  8025. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  8026. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  8027. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  8028. Size == CharUnits::One() ||
  8029. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  8030. Expr::NPC_NeverValueDependent))
  8031. // OK, we will inline appropriately-aligned operations of this size,
  8032. // and _Atomic(T) is appropriately-aligned.
  8033. return Success(1, E);
  8034. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  8035. castAs<PointerType>()->getPointeeType();
  8036. if (!PointeeType->isIncompleteType() &&
  8037. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  8038. // OK, we will inline operations on this object.
  8039. return Success(1, E);
  8040. }
  8041. }
  8042. }
  8043. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  8044. Success(0, E) : Error(E);
  8045. }
  8046. case Builtin::BIomp_is_initial_device:
  8047. // We can decide statically which value the runtime would return if called.
  8048. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  8049. case Builtin::BI__builtin_add_overflow:
  8050. case Builtin::BI__builtin_sub_overflow:
  8051. case Builtin::BI__builtin_mul_overflow:
  8052. case Builtin::BI__builtin_sadd_overflow:
  8053. case Builtin::BI__builtin_uadd_overflow:
  8054. case Builtin::BI__builtin_uaddl_overflow:
  8055. case Builtin::BI__builtin_uaddll_overflow:
  8056. case Builtin::BI__builtin_usub_overflow:
  8057. case Builtin::BI__builtin_usubl_overflow:
  8058. case Builtin::BI__builtin_usubll_overflow:
  8059. case Builtin::BI__builtin_umul_overflow:
  8060. case Builtin::BI__builtin_umull_overflow:
  8061. case Builtin::BI__builtin_umulll_overflow:
  8062. case Builtin::BI__builtin_saddl_overflow:
  8063. case Builtin::BI__builtin_saddll_overflow:
  8064. case Builtin::BI__builtin_ssub_overflow:
  8065. case Builtin::BI__builtin_ssubl_overflow:
  8066. case Builtin::BI__builtin_ssubll_overflow:
  8067. case Builtin::BI__builtin_smul_overflow:
  8068. case Builtin::BI__builtin_smull_overflow:
  8069. case Builtin::BI__builtin_smulll_overflow: {
  8070. LValue ResultLValue;
  8071. APSInt LHS, RHS;
  8072. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  8073. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  8074. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  8075. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  8076. return false;
  8077. APSInt Result;
  8078. bool DidOverflow = false;
  8079. // If the types don't have to match, enlarge all 3 to the largest of them.
  8080. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8081. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8082. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8083. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  8084. ResultType->isSignedIntegerOrEnumerationType();
  8085. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  8086. ResultType->isSignedIntegerOrEnumerationType();
  8087. uint64_t LHSSize = LHS.getBitWidth();
  8088. uint64_t RHSSize = RHS.getBitWidth();
  8089. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  8090. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  8091. // Add an additional bit if the signedness isn't uniformly agreed to. We
  8092. // could do this ONLY if there is a signed and an unsigned that both have
  8093. // MaxBits, but the code to check that is pretty nasty. The issue will be
  8094. // caught in the shrink-to-result later anyway.
  8095. if (IsSigned && !AllSigned)
  8096. ++MaxBits;
  8097. LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
  8098. !IsSigned);
  8099. RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
  8100. !IsSigned);
  8101. Result = APSInt(MaxBits, !IsSigned);
  8102. }
  8103. // Find largest int.
  8104. switch (BuiltinOp) {
  8105. default:
  8106. llvm_unreachable("Invalid value for BuiltinOp");
  8107. case Builtin::BI__builtin_add_overflow:
  8108. case Builtin::BI__builtin_sadd_overflow:
  8109. case Builtin::BI__builtin_saddl_overflow:
  8110. case Builtin::BI__builtin_saddll_overflow:
  8111. case Builtin::BI__builtin_uadd_overflow:
  8112. case Builtin::BI__builtin_uaddl_overflow:
  8113. case Builtin::BI__builtin_uaddll_overflow:
  8114. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  8115. : LHS.uadd_ov(RHS, DidOverflow);
  8116. break;
  8117. case Builtin::BI__builtin_sub_overflow:
  8118. case Builtin::BI__builtin_ssub_overflow:
  8119. case Builtin::BI__builtin_ssubl_overflow:
  8120. case Builtin::BI__builtin_ssubll_overflow:
  8121. case Builtin::BI__builtin_usub_overflow:
  8122. case Builtin::BI__builtin_usubl_overflow:
  8123. case Builtin::BI__builtin_usubll_overflow:
  8124. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  8125. : LHS.usub_ov(RHS, DidOverflow);
  8126. break;
  8127. case Builtin::BI__builtin_mul_overflow:
  8128. case Builtin::BI__builtin_smul_overflow:
  8129. case Builtin::BI__builtin_smull_overflow:
  8130. case Builtin::BI__builtin_smulll_overflow:
  8131. case Builtin::BI__builtin_umul_overflow:
  8132. case Builtin::BI__builtin_umull_overflow:
  8133. case Builtin::BI__builtin_umulll_overflow:
  8134. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  8135. : LHS.umul_ov(RHS, DidOverflow);
  8136. break;
  8137. }
  8138. // In the case where multiple sizes are allowed, truncate and see if
  8139. // the values are the same.
  8140. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8141. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8142. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8143. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  8144. // since it will give us the behavior of a TruncOrSelf in the case where
  8145. // its parameter <= its size. We previously set Result to be at least the
  8146. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  8147. // will work exactly like TruncOrSelf.
  8148. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  8149. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  8150. if (!APSInt::isSameValue(Temp, Result))
  8151. DidOverflow = true;
  8152. Result = Temp;
  8153. }
  8154. APValue APV{Result};
  8155. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  8156. return false;
  8157. return Success(DidOverflow, E);
  8158. }
  8159. }
  8160. }
  8161. /// Determine whether this is a pointer past the end of the complete
  8162. /// object referred to by the lvalue.
  8163. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  8164. const LValue &LV) {
  8165. // A null pointer can be viewed as being "past the end" but we don't
  8166. // choose to look at it that way here.
  8167. if (!LV.getLValueBase())
  8168. return false;
  8169. // If the designator is valid and refers to a subobject, we're not pointing
  8170. // past the end.
  8171. if (!LV.getLValueDesignator().Invalid &&
  8172. !LV.getLValueDesignator().isOnePastTheEnd())
  8173. return false;
  8174. // A pointer to an incomplete type might be past-the-end if the type's size is
  8175. // zero. We cannot tell because the type is incomplete.
  8176. QualType Ty = getType(LV.getLValueBase());
  8177. if (Ty->isIncompleteType())
  8178. return true;
  8179. // We're a past-the-end pointer if we point to the byte after the object,
  8180. // no matter what our type or path is.
  8181. auto Size = Ctx.getTypeSizeInChars(Ty);
  8182. return LV.getLValueOffset() == Size;
  8183. }
  8184. namespace {
  8185. /// Data recursive integer evaluator of certain binary operators.
  8186. ///
  8187. /// We use a data recursive algorithm for binary operators so that we are able
  8188. /// to handle extreme cases of chained binary operators without causing stack
  8189. /// overflow.
  8190. class DataRecursiveIntBinOpEvaluator {
  8191. struct EvalResult {
  8192. APValue Val;
  8193. bool Failed;
  8194. EvalResult() : Failed(false) { }
  8195. void swap(EvalResult &RHS) {
  8196. Val.swap(RHS.Val);
  8197. Failed = RHS.Failed;
  8198. RHS.Failed = false;
  8199. }
  8200. };
  8201. struct Job {
  8202. const Expr *E;
  8203. EvalResult LHSResult; // meaningful only for binary operator expression.
  8204. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  8205. Job() = default;
  8206. Job(Job &&) = default;
  8207. void startSpeculativeEval(EvalInfo &Info) {
  8208. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  8209. }
  8210. private:
  8211. SpeculativeEvaluationRAII SpecEvalRAII;
  8212. };
  8213. SmallVector<Job, 16> Queue;
  8214. IntExprEvaluator &IntEval;
  8215. EvalInfo &Info;
  8216. APValue &FinalResult;
  8217. public:
  8218. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  8219. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  8220. /// True if \param E is a binary operator that we are going to handle
  8221. /// data recursively.
  8222. /// We handle binary operators that are comma, logical, or that have operands
  8223. /// with integral or enumeration type.
  8224. static bool shouldEnqueue(const BinaryOperator *E) {
  8225. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  8226. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  8227. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8228. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8229. }
  8230. bool Traverse(const BinaryOperator *E) {
  8231. enqueue(E);
  8232. EvalResult PrevResult;
  8233. while (!Queue.empty())
  8234. process(PrevResult);
  8235. if (PrevResult.Failed) return false;
  8236. FinalResult.swap(PrevResult.Val);
  8237. return true;
  8238. }
  8239. private:
  8240. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8241. return IntEval.Success(Value, E, Result);
  8242. }
  8243. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  8244. return IntEval.Success(Value, E, Result);
  8245. }
  8246. bool Error(const Expr *E) {
  8247. return IntEval.Error(E);
  8248. }
  8249. bool Error(const Expr *E, diag::kind D) {
  8250. return IntEval.Error(E, D);
  8251. }
  8252. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  8253. return Info.CCEDiag(E, D);
  8254. }
  8255. // Returns true if visiting the RHS is necessary, false otherwise.
  8256. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8257. bool &SuppressRHSDiags);
  8258. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8259. const BinaryOperator *E, APValue &Result);
  8260. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  8261. Result.Failed = !Evaluate(Result.Val, Info, E);
  8262. if (Result.Failed)
  8263. Result.Val = APValue();
  8264. }
  8265. void process(EvalResult &Result);
  8266. void enqueue(const Expr *E) {
  8267. E = E->IgnoreParens();
  8268. Queue.resize(Queue.size()+1);
  8269. Queue.back().E = E;
  8270. Queue.back().Kind = Job::AnyExprKind;
  8271. }
  8272. };
  8273. }
  8274. bool DataRecursiveIntBinOpEvaluator::
  8275. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8276. bool &SuppressRHSDiags) {
  8277. if (E->getOpcode() == BO_Comma) {
  8278. // Ignore LHS but note if we could not evaluate it.
  8279. if (LHSResult.Failed)
  8280. return Info.noteSideEffect();
  8281. return true;
  8282. }
  8283. if (E->isLogicalOp()) {
  8284. bool LHSAsBool;
  8285. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  8286. // We were able to evaluate the LHS, see if we can get away with not
  8287. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  8288. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  8289. Success(LHSAsBool, E, LHSResult.Val);
  8290. return false; // Ignore RHS
  8291. }
  8292. } else {
  8293. LHSResult.Failed = true;
  8294. // Since we weren't able to evaluate the left hand side, it
  8295. // might have had side effects.
  8296. if (!Info.noteSideEffect())
  8297. return false;
  8298. // We can't evaluate the LHS; however, sometimes the result
  8299. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8300. // Don't ignore RHS and suppress diagnostics from this arm.
  8301. SuppressRHSDiags = true;
  8302. }
  8303. return true;
  8304. }
  8305. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8306. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8307. if (LHSResult.Failed && !Info.noteFailure())
  8308. return false; // Ignore RHS;
  8309. return true;
  8310. }
  8311. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  8312. bool IsSub) {
  8313. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  8314. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  8315. // offsets.
  8316. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  8317. CharUnits &Offset = LVal.getLValueOffset();
  8318. uint64_t Offset64 = Offset.getQuantity();
  8319. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  8320. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  8321. : Offset64 + Index64);
  8322. }
  8323. bool DataRecursiveIntBinOpEvaluator::
  8324. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8325. const BinaryOperator *E, APValue &Result) {
  8326. if (E->getOpcode() == BO_Comma) {
  8327. if (RHSResult.Failed)
  8328. return false;
  8329. Result = RHSResult.Val;
  8330. return true;
  8331. }
  8332. if (E->isLogicalOp()) {
  8333. bool lhsResult, rhsResult;
  8334. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  8335. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  8336. if (LHSIsOK) {
  8337. if (RHSIsOK) {
  8338. if (E->getOpcode() == BO_LOr)
  8339. return Success(lhsResult || rhsResult, E, Result);
  8340. else
  8341. return Success(lhsResult && rhsResult, E, Result);
  8342. }
  8343. } else {
  8344. if (RHSIsOK) {
  8345. // We can't evaluate the LHS; however, sometimes the result
  8346. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8347. if (rhsResult == (E->getOpcode() == BO_LOr))
  8348. return Success(rhsResult, E, Result);
  8349. }
  8350. }
  8351. return false;
  8352. }
  8353. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8354. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8355. if (LHSResult.Failed || RHSResult.Failed)
  8356. return false;
  8357. const APValue &LHSVal = LHSResult.Val;
  8358. const APValue &RHSVal = RHSResult.Val;
  8359. // Handle cases like (unsigned long)&a + 4.
  8360. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  8361. Result = LHSVal;
  8362. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  8363. return true;
  8364. }
  8365. // Handle cases like 4 + (unsigned long)&a
  8366. if (E->getOpcode() == BO_Add &&
  8367. RHSVal.isLValue() && LHSVal.isInt()) {
  8368. Result = RHSVal;
  8369. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  8370. return true;
  8371. }
  8372. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  8373. // Handle (intptr_t)&&A - (intptr_t)&&B.
  8374. if (!LHSVal.getLValueOffset().isZero() ||
  8375. !RHSVal.getLValueOffset().isZero())
  8376. return false;
  8377. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  8378. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  8379. if (!LHSExpr || !RHSExpr)
  8380. return false;
  8381. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8382. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8383. if (!LHSAddrExpr || !RHSAddrExpr)
  8384. return false;
  8385. // Make sure both labels come from the same function.
  8386. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8387. RHSAddrExpr->getLabel()->getDeclContext())
  8388. return false;
  8389. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  8390. return true;
  8391. }
  8392. // All the remaining cases expect both operands to be an integer
  8393. if (!LHSVal.isInt() || !RHSVal.isInt())
  8394. return Error(E);
  8395. // Set up the width and signedness manually, in case it can't be deduced
  8396. // from the operation we're performing.
  8397. // FIXME: Don't do this in the cases where we can deduce it.
  8398. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  8399. E->getType()->isUnsignedIntegerOrEnumerationType());
  8400. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  8401. RHSVal.getInt(), Value))
  8402. return false;
  8403. return Success(Value, E, Result);
  8404. }
  8405. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  8406. Job &job = Queue.back();
  8407. switch (job.Kind) {
  8408. case Job::AnyExprKind: {
  8409. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  8410. if (shouldEnqueue(Bop)) {
  8411. job.Kind = Job::BinOpKind;
  8412. enqueue(Bop->getLHS());
  8413. return;
  8414. }
  8415. }
  8416. EvaluateExpr(job.E, Result);
  8417. Queue.pop_back();
  8418. return;
  8419. }
  8420. case Job::BinOpKind: {
  8421. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  8422. bool SuppressRHSDiags = false;
  8423. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  8424. Queue.pop_back();
  8425. return;
  8426. }
  8427. if (SuppressRHSDiags)
  8428. job.startSpeculativeEval(Info);
  8429. job.LHSResult.swap(Result);
  8430. job.Kind = Job::BinOpVisitedLHSKind;
  8431. enqueue(Bop->getRHS());
  8432. return;
  8433. }
  8434. case Job::BinOpVisitedLHSKind: {
  8435. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  8436. EvalResult RHS;
  8437. RHS.swap(Result);
  8438. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  8439. Queue.pop_back();
  8440. return;
  8441. }
  8442. }
  8443. llvm_unreachable("Invalid Job::Kind!");
  8444. }
  8445. namespace {
  8446. /// Used when we determine that we should fail, but can keep evaluating prior to
  8447. /// noting that we had a failure.
  8448. class DelayedNoteFailureRAII {
  8449. EvalInfo &Info;
  8450. bool NoteFailure;
  8451. public:
  8452. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  8453. : Info(Info), NoteFailure(NoteFailure) {}
  8454. ~DelayedNoteFailureRAII() {
  8455. if (NoteFailure) {
  8456. bool ContinueAfterFailure = Info.noteFailure();
  8457. (void)ContinueAfterFailure;
  8458. assert(ContinueAfterFailure &&
  8459. "Shouldn't have kept evaluating on failure.");
  8460. }
  8461. }
  8462. };
  8463. }
  8464. template <class SuccessCB, class AfterCB>
  8465. static bool
  8466. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  8467. SuccessCB &&Success, AfterCB &&DoAfter) {
  8468. assert(E->isComparisonOp() && "expected comparison operator");
  8469. assert((E->getOpcode() == BO_Cmp ||
  8470. E->getType()->isIntegralOrEnumerationType()) &&
  8471. "unsupported binary expression evaluation");
  8472. auto Error = [&](const Expr *E) {
  8473. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8474. return false;
  8475. };
  8476. using CCR = ComparisonCategoryResult;
  8477. bool IsRelational = E->isRelationalOp();
  8478. bool IsEquality = E->isEqualityOp();
  8479. if (E->getOpcode() == BO_Cmp) {
  8480. const ComparisonCategoryInfo &CmpInfo =
  8481. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8482. IsRelational = CmpInfo.isOrdered();
  8483. IsEquality = CmpInfo.isEquality();
  8484. }
  8485. QualType LHSTy = E->getLHS()->getType();
  8486. QualType RHSTy = E->getRHS()->getType();
  8487. if (LHSTy->isIntegralOrEnumerationType() &&
  8488. RHSTy->isIntegralOrEnumerationType()) {
  8489. APSInt LHS, RHS;
  8490. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  8491. if (!LHSOK && !Info.noteFailure())
  8492. return false;
  8493. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  8494. return false;
  8495. if (LHS < RHS)
  8496. return Success(CCR::Less, E);
  8497. if (LHS > RHS)
  8498. return Success(CCR::Greater, E);
  8499. return Success(CCR::Equal, E);
  8500. }
  8501. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  8502. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  8503. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  8504. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  8505. if (!LHSOK && !Info.noteFailure())
  8506. return false;
  8507. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  8508. return false;
  8509. if (LHSFX < RHSFX)
  8510. return Success(CCR::Less, E);
  8511. if (LHSFX > RHSFX)
  8512. return Success(CCR::Greater, E);
  8513. return Success(CCR::Equal, E);
  8514. }
  8515. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  8516. ComplexValue LHS, RHS;
  8517. bool LHSOK;
  8518. if (E->isAssignmentOp()) {
  8519. LValue LV;
  8520. EvaluateLValue(E->getLHS(), LV, Info);
  8521. LHSOK = false;
  8522. } else if (LHSTy->isRealFloatingType()) {
  8523. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  8524. if (LHSOK) {
  8525. LHS.makeComplexFloat();
  8526. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  8527. }
  8528. } else {
  8529. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  8530. }
  8531. if (!LHSOK && !Info.noteFailure())
  8532. return false;
  8533. if (E->getRHS()->getType()->isRealFloatingType()) {
  8534. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  8535. return false;
  8536. RHS.makeComplexFloat();
  8537. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  8538. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  8539. return false;
  8540. if (LHS.isComplexFloat()) {
  8541. APFloat::cmpResult CR_r =
  8542. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  8543. APFloat::cmpResult CR_i =
  8544. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  8545. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  8546. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  8547. } else {
  8548. assert(IsEquality && "invalid complex comparison");
  8549. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  8550. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  8551. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  8552. }
  8553. }
  8554. if (LHSTy->isRealFloatingType() &&
  8555. RHSTy->isRealFloatingType()) {
  8556. APFloat RHS(0.0), LHS(0.0);
  8557. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  8558. if (!LHSOK && !Info.noteFailure())
  8559. return false;
  8560. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  8561. return false;
  8562. assert(E->isComparisonOp() && "Invalid binary operator!");
  8563. auto GetCmpRes = [&]() {
  8564. switch (LHS.compare(RHS)) {
  8565. case APFloat::cmpEqual:
  8566. return CCR::Equal;
  8567. case APFloat::cmpLessThan:
  8568. return CCR::Less;
  8569. case APFloat::cmpGreaterThan:
  8570. return CCR::Greater;
  8571. case APFloat::cmpUnordered:
  8572. return CCR::Unordered;
  8573. }
  8574. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  8575. };
  8576. return Success(GetCmpRes(), E);
  8577. }
  8578. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  8579. LValue LHSValue, RHSValue;
  8580. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8581. if (!LHSOK && !Info.noteFailure())
  8582. return false;
  8583. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8584. return false;
  8585. // Reject differing bases from the normal codepath; we special-case
  8586. // comparisons to null.
  8587. if (!HasSameBase(LHSValue, RHSValue)) {
  8588. // Inequalities and subtractions between unrelated pointers have
  8589. // unspecified or undefined behavior.
  8590. if (!IsEquality)
  8591. return Error(E);
  8592. // A constant address may compare equal to the address of a symbol.
  8593. // The one exception is that address of an object cannot compare equal
  8594. // to a null pointer constant.
  8595. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  8596. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  8597. return Error(E);
  8598. // It's implementation-defined whether distinct literals will have
  8599. // distinct addresses. In clang, the result of such a comparison is
  8600. // unspecified, so it is not a constant expression. However, we do know
  8601. // that the address of a literal will be non-null.
  8602. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  8603. LHSValue.Base && RHSValue.Base)
  8604. return Error(E);
  8605. // We can't tell whether weak symbols will end up pointing to the same
  8606. // object.
  8607. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  8608. return Error(E);
  8609. // We can't compare the address of the start of one object with the
  8610. // past-the-end address of another object, per C++ DR1652.
  8611. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  8612. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  8613. (RHSValue.Base && RHSValue.Offset.isZero() &&
  8614. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  8615. return Error(E);
  8616. // We can't tell whether an object is at the same address as another
  8617. // zero sized object.
  8618. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  8619. (LHSValue.Base && isZeroSized(RHSValue)))
  8620. return Error(E);
  8621. return Success(CCR::Nonequal, E);
  8622. }
  8623. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8624. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8625. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8626. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8627. // C++11 [expr.rel]p3:
  8628. // Pointers to void (after pointer conversions) can be compared, with a
  8629. // result defined as follows: If both pointers represent the same
  8630. // address or are both the null pointer value, the result is true if the
  8631. // operator is <= or >= and false otherwise; otherwise the result is
  8632. // unspecified.
  8633. // We interpret this as applying to pointers to *cv* void.
  8634. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  8635. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  8636. // C++11 [expr.rel]p2:
  8637. // - If two pointers point to non-static data members of the same object,
  8638. // or to subobjects or array elements fo such members, recursively, the
  8639. // pointer to the later declared member compares greater provided the
  8640. // two members have the same access control and provided their class is
  8641. // not a union.
  8642. // [...]
  8643. // - Otherwise pointer comparisons are unspecified.
  8644. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  8645. bool WasArrayIndex;
  8646. unsigned Mismatch = FindDesignatorMismatch(
  8647. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  8648. // At the point where the designators diverge, the comparison has a
  8649. // specified value if:
  8650. // - we are comparing array indices
  8651. // - we are comparing fields of a union, or fields with the same access
  8652. // Otherwise, the result is unspecified and thus the comparison is not a
  8653. // constant expression.
  8654. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  8655. Mismatch < RHSDesignator.Entries.size()) {
  8656. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  8657. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  8658. if (!LF && !RF)
  8659. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  8660. else if (!LF)
  8661. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8662. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  8663. << RF->getParent() << RF;
  8664. else if (!RF)
  8665. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8666. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  8667. << LF->getParent() << LF;
  8668. else if (!LF->getParent()->isUnion() &&
  8669. LF->getAccess() != RF->getAccess())
  8670. Info.CCEDiag(E,
  8671. diag::note_constexpr_pointer_comparison_differing_access)
  8672. << LF << LF->getAccess() << RF << RF->getAccess()
  8673. << LF->getParent();
  8674. }
  8675. }
  8676. // The comparison here must be unsigned, and performed with the same
  8677. // width as the pointer.
  8678. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  8679. uint64_t CompareLHS = LHSOffset.getQuantity();
  8680. uint64_t CompareRHS = RHSOffset.getQuantity();
  8681. assert(PtrSize <= 64 && "Unexpected pointer width");
  8682. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  8683. CompareLHS &= Mask;
  8684. CompareRHS &= Mask;
  8685. // If there is a base and this is a relational operator, we can only
  8686. // compare pointers within the object in question; otherwise, the result
  8687. // depends on where the object is located in memory.
  8688. if (!LHSValue.Base.isNull() && IsRelational) {
  8689. QualType BaseTy = getType(LHSValue.Base);
  8690. if (BaseTy->isIncompleteType())
  8691. return Error(E);
  8692. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  8693. uint64_t OffsetLimit = Size.getQuantity();
  8694. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  8695. return Error(E);
  8696. }
  8697. if (CompareLHS < CompareRHS)
  8698. return Success(CCR::Less, E);
  8699. if (CompareLHS > CompareRHS)
  8700. return Success(CCR::Greater, E);
  8701. return Success(CCR::Equal, E);
  8702. }
  8703. if (LHSTy->isMemberPointerType()) {
  8704. assert(IsEquality && "unexpected member pointer operation");
  8705. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  8706. MemberPtr LHSValue, RHSValue;
  8707. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  8708. if (!LHSOK && !Info.noteFailure())
  8709. return false;
  8710. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8711. return false;
  8712. // C++11 [expr.eq]p2:
  8713. // If both operands are null, they compare equal. Otherwise if only one is
  8714. // null, they compare unequal.
  8715. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  8716. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  8717. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8718. }
  8719. // Otherwise if either is a pointer to a virtual member function, the
  8720. // result is unspecified.
  8721. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  8722. if (MD->isVirtual())
  8723. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8724. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  8725. if (MD->isVirtual())
  8726. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8727. // Otherwise they compare equal if and only if they would refer to the
  8728. // same member of the same most derived object or the same subobject if
  8729. // they were dereferenced with a hypothetical object of the associated
  8730. // class type.
  8731. bool Equal = LHSValue == RHSValue;
  8732. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8733. }
  8734. if (LHSTy->isNullPtrType()) {
  8735. assert(E->isComparisonOp() && "unexpected nullptr operation");
  8736. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  8737. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  8738. // are compared, the result is true of the operator is <=, >= or ==, and
  8739. // false otherwise.
  8740. return Success(CCR::Equal, E);
  8741. }
  8742. return DoAfter();
  8743. }
  8744. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  8745. if (!CheckLiteralType(Info, E))
  8746. return false;
  8747. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8748. const BinaryOperator *E) {
  8749. // Evaluation succeeded. Lookup the information for the comparison category
  8750. // type and fetch the VarDecl for the result.
  8751. const ComparisonCategoryInfo &CmpInfo =
  8752. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8753. const VarDecl *VD =
  8754. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  8755. // Check and evaluate the result as a constant expression.
  8756. LValue LV;
  8757. LV.set(VD);
  8758. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8759. return false;
  8760. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8761. };
  8762. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8763. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  8764. });
  8765. }
  8766. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8767. // We don't call noteFailure immediately because the assignment happens after
  8768. // we evaluate LHS and RHS.
  8769. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  8770. return Error(E);
  8771. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  8772. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  8773. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  8774. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  8775. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  8776. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  8777. if (E->isComparisonOp()) {
  8778. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  8779. // comparisons and then translating the result.
  8780. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8781. const BinaryOperator *E) {
  8782. using CCR = ComparisonCategoryResult;
  8783. bool IsEqual = ResKind == CCR::Equal,
  8784. IsLess = ResKind == CCR::Less,
  8785. IsGreater = ResKind == CCR::Greater;
  8786. auto Op = E->getOpcode();
  8787. switch (Op) {
  8788. default:
  8789. llvm_unreachable("unsupported binary operator");
  8790. case BO_EQ:
  8791. case BO_NE:
  8792. return Success(IsEqual == (Op == BO_EQ), E);
  8793. case BO_LT: return Success(IsLess, E);
  8794. case BO_GT: return Success(IsGreater, E);
  8795. case BO_LE: return Success(IsEqual || IsLess, E);
  8796. case BO_GE: return Success(IsEqual || IsGreater, E);
  8797. }
  8798. };
  8799. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8800. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8801. });
  8802. }
  8803. QualType LHSTy = E->getLHS()->getType();
  8804. QualType RHSTy = E->getRHS()->getType();
  8805. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  8806. E->getOpcode() == BO_Sub) {
  8807. LValue LHSValue, RHSValue;
  8808. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8809. if (!LHSOK && !Info.noteFailure())
  8810. return false;
  8811. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8812. return false;
  8813. // Reject differing bases from the normal codepath; we special-case
  8814. // comparisons to null.
  8815. if (!HasSameBase(LHSValue, RHSValue)) {
  8816. // Handle &&A - &&B.
  8817. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  8818. return Error(E);
  8819. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  8820. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  8821. if (!LHSExpr || !RHSExpr)
  8822. return Error(E);
  8823. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8824. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8825. if (!LHSAddrExpr || !RHSAddrExpr)
  8826. return Error(E);
  8827. // Make sure both labels come from the same function.
  8828. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8829. RHSAddrExpr->getLabel()->getDeclContext())
  8830. return Error(E);
  8831. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  8832. }
  8833. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8834. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8835. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8836. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8837. // C++11 [expr.add]p6:
  8838. // Unless both pointers point to elements of the same array object, or
  8839. // one past the last element of the array object, the behavior is
  8840. // undefined.
  8841. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  8842. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  8843. RHSDesignator))
  8844. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  8845. QualType Type = E->getLHS()->getType();
  8846. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  8847. CharUnits ElementSize;
  8848. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  8849. return false;
  8850. // As an extension, a type may have zero size (empty struct or union in
  8851. // C, array of zero length). Pointer subtraction in such cases has
  8852. // undefined behavior, so is not constant.
  8853. if (ElementSize.isZero()) {
  8854. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  8855. << ElementType;
  8856. return false;
  8857. }
  8858. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  8859. // and produce incorrect results when it overflows. Such behavior
  8860. // appears to be non-conforming, but is common, so perhaps we should
  8861. // assume the standard intended for such cases to be undefined behavior
  8862. // and check for them.
  8863. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  8864. // overflow in the final conversion to ptrdiff_t.
  8865. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  8866. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  8867. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  8868. false);
  8869. APSInt TrueResult = (LHS - RHS) / ElemSize;
  8870. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  8871. if (Result.extend(65) != TrueResult &&
  8872. !HandleOverflow(Info, E, TrueResult, E->getType()))
  8873. return false;
  8874. return Success(Result, E);
  8875. }
  8876. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  8877. }
  8878. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  8879. /// a result as the expression's type.
  8880. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  8881. const UnaryExprOrTypeTraitExpr *E) {
  8882. switch(E->getKind()) {
  8883. case UETT_PreferredAlignOf:
  8884. case UETT_AlignOf: {
  8885. if (E->isArgumentType())
  8886. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  8887. E);
  8888. else
  8889. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  8890. E);
  8891. }
  8892. case UETT_VecStep: {
  8893. QualType Ty = E->getTypeOfArgument();
  8894. if (Ty->isVectorType()) {
  8895. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  8896. // The vec_step built-in functions that take a 3-component
  8897. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  8898. if (n == 3)
  8899. n = 4;
  8900. return Success(n, E);
  8901. } else
  8902. return Success(1, E);
  8903. }
  8904. case UETT_SizeOf: {
  8905. QualType SrcTy = E->getTypeOfArgument();
  8906. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  8907. // the result is the size of the referenced type."
  8908. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  8909. SrcTy = Ref->getPointeeType();
  8910. CharUnits Sizeof;
  8911. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  8912. return false;
  8913. return Success(Sizeof, E);
  8914. }
  8915. case UETT_OpenMPRequiredSimdAlign:
  8916. assert(E->isArgumentType());
  8917. return Success(
  8918. Info.Ctx.toCharUnitsFromBits(
  8919. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  8920. .getQuantity(),
  8921. E);
  8922. }
  8923. llvm_unreachable("unknown expr/type trait");
  8924. }
  8925. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  8926. CharUnits Result;
  8927. unsigned n = OOE->getNumComponents();
  8928. if (n == 0)
  8929. return Error(OOE);
  8930. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  8931. for (unsigned i = 0; i != n; ++i) {
  8932. OffsetOfNode ON = OOE->getComponent(i);
  8933. switch (ON.getKind()) {
  8934. case OffsetOfNode::Array: {
  8935. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  8936. APSInt IdxResult;
  8937. if (!EvaluateInteger(Idx, IdxResult, Info))
  8938. return false;
  8939. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  8940. if (!AT)
  8941. return Error(OOE);
  8942. CurrentType = AT->getElementType();
  8943. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  8944. Result += IdxResult.getSExtValue() * ElementSize;
  8945. break;
  8946. }
  8947. case OffsetOfNode::Field: {
  8948. FieldDecl *MemberDecl = ON.getField();
  8949. const RecordType *RT = CurrentType->getAs<RecordType>();
  8950. if (!RT)
  8951. return Error(OOE);
  8952. RecordDecl *RD = RT->getDecl();
  8953. if (RD->isInvalidDecl()) return false;
  8954. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8955. unsigned i = MemberDecl->getFieldIndex();
  8956. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  8957. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  8958. CurrentType = MemberDecl->getType().getNonReferenceType();
  8959. break;
  8960. }
  8961. case OffsetOfNode::Identifier:
  8962. llvm_unreachable("dependent __builtin_offsetof");
  8963. case OffsetOfNode::Base: {
  8964. CXXBaseSpecifier *BaseSpec = ON.getBase();
  8965. if (BaseSpec->isVirtual())
  8966. return Error(OOE);
  8967. // Find the layout of the class whose base we are looking into.
  8968. const RecordType *RT = CurrentType->getAs<RecordType>();
  8969. if (!RT)
  8970. return Error(OOE);
  8971. RecordDecl *RD = RT->getDecl();
  8972. if (RD->isInvalidDecl()) return false;
  8973. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  8974. // Find the base class itself.
  8975. CurrentType = BaseSpec->getType();
  8976. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  8977. if (!BaseRT)
  8978. return Error(OOE);
  8979. // Add the offset to the base.
  8980. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  8981. break;
  8982. }
  8983. }
  8984. }
  8985. return Success(Result, OOE);
  8986. }
  8987. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  8988. switch (E->getOpcode()) {
  8989. default:
  8990. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  8991. // See C99 6.6p3.
  8992. return Error(E);
  8993. case UO_Extension:
  8994. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  8995. // If so, we could clear the diagnostic ID.
  8996. return Visit(E->getSubExpr());
  8997. case UO_Plus:
  8998. // The result is just the value.
  8999. return Visit(E->getSubExpr());
  9000. case UO_Minus: {
  9001. if (!Visit(E->getSubExpr()))
  9002. return false;
  9003. if (!Result.isInt()) return Error(E);
  9004. const APSInt &Value = Result.getInt();
  9005. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  9006. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  9007. E->getType()))
  9008. return false;
  9009. return Success(-Value, E);
  9010. }
  9011. case UO_Not: {
  9012. if (!Visit(E->getSubExpr()))
  9013. return false;
  9014. if (!Result.isInt()) return Error(E);
  9015. return Success(~Result.getInt(), E);
  9016. }
  9017. case UO_LNot: {
  9018. bool bres;
  9019. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9020. return false;
  9021. return Success(!bres, E);
  9022. }
  9023. }
  9024. }
  9025. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  9026. /// result type is integer.
  9027. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9028. const Expr *SubExpr = E->getSubExpr();
  9029. QualType DestType = E->getType();
  9030. QualType SrcType = SubExpr->getType();
  9031. switch (E->getCastKind()) {
  9032. case CK_BaseToDerived:
  9033. case CK_DerivedToBase:
  9034. case CK_UncheckedDerivedToBase:
  9035. case CK_Dynamic:
  9036. case CK_ToUnion:
  9037. case CK_ArrayToPointerDecay:
  9038. case CK_FunctionToPointerDecay:
  9039. case CK_NullToPointer:
  9040. case CK_NullToMemberPointer:
  9041. case CK_BaseToDerivedMemberPointer:
  9042. case CK_DerivedToBaseMemberPointer:
  9043. case CK_ReinterpretMemberPointer:
  9044. case CK_ConstructorConversion:
  9045. case CK_IntegralToPointer:
  9046. case CK_ToVoid:
  9047. case CK_VectorSplat:
  9048. case CK_IntegralToFloating:
  9049. case CK_FloatingCast:
  9050. case CK_CPointerToObjCPointerCast:
  9051. case CK_BlockPointerToObjCPointerCast:
  9052. case CK_AnyPointerToBlockPointerCast:
  9053. case CK_ObjCObjectLValueCast:
  9054. case CK_FloatingRealToComplex:
  9055. case CK_FloatingComplexToReal:
  9056. case CK_FloatingComplexCast:
  9057. case CK_FloatingComplexToIntegralComplex:
  9058. case CK_IntegralRealToComplex:
  9059. case CK_IntegralComplexCast:
  9060. case CK_IntegralComplexToFloatingComplex:
  9061. case CK_BuiltinFnToFnPtr:
  9062. case CK_ZeroToOCLOpaqueType:
  9063. case CK_NonAtomicToAtomic:
  9064. case CK_AddressSpaceConversion:
  9065. case CK_IntToOCLSampler:
  9066. case CK_FixedPointCast:
  9067. case CK_IntegralToFixedPoint:
  9068. llvm_unreachable("invalid cast kind for integral value");
  9069. case CK_BitCast:
  9070. case CK_Dependent:
  9071. case CK_LValueBitCast:
  9072. case CK_ARCProduceObject:
  9073. case CK_ARCConsumeObject:
  9074. case CK_ARCReclaimReturnedObject:
  9075. case CK_ARCExtendBlockObject:
  9076. case CK_CopyAndAutoreleaseBlockObject:
  9077. return Error(E);
  9078. case CK_UserDefinedConversion:
  9079. case CK_LValueToRValue:
  9080. case CK_AtomicToNonAtomic:
  9081. case CK_NoOp:
  9082. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9083. case CK_MemberPointerToBoolean:
  9084. case CK_PointerToBoolean:
  9085. case CK_IntegralToBoolean:
  9086. case CK_FloatingToBoolean:
  9087. case CK_BooleanToSignedIntegral:
  9088. case CK_FloatingComplexToBoolean:
  9089. case CK_IntegralComplexToBoolean: {
  9090. bool BoolResult;
  9091. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  9092. return false;
  9093. uint64_t IntResult = BoolResult;
  9094. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  9095. IntResult = (uint64_t)-1;
  9096. return Success(IntResult, E);
  9097. }
  9098. case CK_FixedPointToIntegral: {
  9099. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  9100. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9101. return false;
  9102. bool Overflowed;
  9103. llvm::APSInt Result = Src.convertToInt(
  9104. Info.Ctx.getIntWidth(DestType),
  9105. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  9106. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9107. return false;
  9108. return Success(Result, E);
  9109. }
  9110. case CK_FixedPointToBoolean: {
  9111. // Unsigned padding does not affect this.
  9112. APValue Val;
  9113. if (!Evaluate(Val, Info, SubExpr))
  9114. return false;
  9115. return Success(Val.getFixedPoint().getBoolValue(), E);
  9116. }
  9117. case CK_IntegralCast: {
  9118. if (!Visit(SubExpr))
  9119. return false;
  9120. if (!Result.isInt()) {
  9121. // Allow casts of address-of-label differences if they are no-ops
  9122. // or narrowing. (The narrowing case isn't actually guaranteed to
  9123. // be constant-evaluatable except in some narrow cases which are hard
  9124. // to detect here. We let it through on the assumption the user knows
  9125. // what they are doing.)
  9126. if (Result.isAddrLabelDiff())
  9127. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  9128. // Only allow casts of lvalues if they are lossless.
  9129. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  9130. }
  9131. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  9132. Result.getInt()), E);
  9133. }
  9134. case CK_PointerToIntegral: {
  9135. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  9136. LValue LV;
  9137. if (!EvaluatePointer(SubExpr, LV, Info))
  9138. return false;
  9139. if (LV.getLValueBase()) {
  9140. // Only allow based lvalue casts if they are lossless.
  9141. // FIXME: Allow a larger integer size than the pointer size, and allow
  9142. // narrowing back down to pointer width in subsequent integral casts.
  9143. // FIXME: Check integer type's active bits, not its type size.
  9144. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  9145. return Error(E);
  9146. LV.Designator.setInvalid();
  9147. LV.moveInto(Result);
  9148. return true;
  9149. }
  9150. APSInt AsInt;
  9151. APValue V;
  9152. LV.moveInto(V);
  9153. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  9154. llvm_unreachable("Can't cast this!");
  9155. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  9156. }
  9157. case CK_IntegralComplexToReal: {
  9158. ComplexValue C;
  9159. if (!EvaluateComplex(SubExpr, C, Info))
  9160. return false;
  9161. return Success(C.getComplexIntReal(), E);
  9162. }
  9163. case CK_FloatingToIntegral: {
  9164. APFloat F(0.0);
  9165. if (!EvaluateFloat(SubExpr, F, Info))
  9166. return false;
  9167. APSInt Value;
  9168. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  9169. return false;
  9170. return Success(Value, E);
  9171. }
  9172. }
  9173. llvm_unreachable("unknown cast resulting in integral value");
  9174. }
  9175. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9176. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9177. ComplexValue LV;
  9178. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9179. return false;
  9180. if (!LV.isComplexInt())
  9181. return Error(E);
  9182. return Success(LV.getComplexIntReal(), E);
  9183. }
  9184. return Visit(E->getSubExpr());
  9185. }
  9186. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9187. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  9188. ComplexValue LV;
  9189. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9190. return false;
  9191. if (!LV.isComplexInt())
  9192. return Error(E);
  9193. return Success(LV.getComplexIntImag(), E);
  9194. }
  9195. VisitIgnoredValue(E->getSubExpr());
  9196. return Success(0, E);
  9197. }
  9198. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  9199. return Success(E->getPackLength(), E);
  9200. }
  9201. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  9202. return Success(E->getValue(), E);
  9203. }
  9204. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9205. switch (E->getOpcode()) {
  9206. default:
  9207. // Invalid unary operators
  9208. return Error(E);
  9209. case UO_Plus:
  9210. // The result is just the value.
  9211. return Visit(E->getSubExpr());
  9212. case UO_Minus: {
  9213. if (!Visit(E->getSubExpr())) return false;
  9214. if (!Result.isFixedPoint())
  9215. return Error(E);
  9216. bool Overflowed;
  9217. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  9218. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  9219. return false;
  9220. return Success(Negated, E);
  9221. }
  9222. case UO_LNot: {
  9223. bool bres;
  9224. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9225. return false;
  9226. return Success(!bres, E);
  9227. }
  9228. }
  9229. }
  9230. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9231. const Expr *SubExpr = E->getSubExpr();
  9232. QualType DestType = E->getType();
  9233. assert(DestType->isFixedPointType() &&
  9234. "Expected destination type to be a fixed point type");
  9235. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  9236. switch (E->getCastKind()) {
  9237. case CK_FixedPointCast: {
  9238. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  9239. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9240. return false;
  9241. bool Overflowed;
  9242. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  9243. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9244. return false;
  9245. return Success(Result, E);
  9246. }
  9247. case CK_IntegralToFixedPoint: {
  9248. APSInt Src;
  9249. if (!EvaluateInteger(SubExpr, Src, Info))
  9250. return false;
  9251. bool Overflowed;
  9252. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  9253. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  9254. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  9255. return false;
  9256. return Success(IntResult, E);
  9257. }
  9258. case CK_NoOp:
  9259. case CK_LValueToRValue:
  9260. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9261. default:
  9262. return Error(E);
  9263. }
  9264. }
  9265. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9266. const Expr *LHS = E->getLHS();
  9267. const Expr *RHS = E->getRHS();
  9268. FixedPointSemantics ResultFXSema =
  9269. Info.Ctx.getFixedPointSemantics(E->getType());
  9270. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  9271. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  9272. return false;
  9273. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  9274. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  9275. return false;
  9276. switch (E->getOpcode()) {
  9277. case BO_Add: {
  9278. bool AddOverflow, ConversionOverflow;
  9279. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  9280. .convert(ResultFXSema, &ConversionOverflow);
  9281. if ((AddOverflow || ConversionOverflow) &&
  9282. !HandleOverflow(Info, E, Result, E->getType()))
  9283. return false;
  9284. return Success(Result, E);
  9285. }
  9286. default:
  9287. return false;
  9288. }
  9289. llvm_unreachable("Should've exited before this");
  9290. }
  9291. //===----------------------------------------------------------------------===//
  9292. // Float Evaluation
  9293. //===----------------------------------------------------------------------===//
  9294. namespace {
  9295. class FloatExprEvaluator
  9296. : public ExprEvaluatorBase<FloatExprEvaluator> {
  9297. APFloat &Result;
  9298. public:
  9299. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  9300. : ExprEvaluatorBaseTy(info), Result(result) {}
  9301. bool Success(const APValue &V, const Expr *e) {
  9302. Result = V.getFloat();
  9303. return true;
  9304. }
  9305. bool ZeroInitialization(const Expr *E) {
  9306. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  9307. return true;
  9308. }
  9309. bool VisitCallExpr(const CallExpr *E);
  9310. bool VisitUnaryOperator(const UnaryOperator *E);
  9311. bool VisitBinaryOperator(const BinaryOperator *E);
  9312. bool VisitFloatingLiteral(const FloatingLiteral *E);
  9313. bool VisitCastExpr(const CastExpr *E);
  9314. bool VisitUnaryReal(const UnaryOperator *E);
  9315. bool VisitUnaryImag(const UnaryOperator *E);
  9316. // FIXME: Missing: array subscript of vector, member of vector
  9317. };
  9318. } // end anonymous namespace
  9319. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  9320. assert(E->isRValue() && E->getType()->isRealFloatingType());
  9321. return FloatExprEvaluator(Info, Result).Visit(E);
  9322. }
  9323. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  9324. QualType ResultTy,
  9325. const Expr *Arg,
  9326. bool SNaN,
  9327. llvm::APFloat &Result) {
  9328. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  9329. if (!S) return false;
  9330. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  9331. llvm::APInt fill;
  9332. // Treat empty strings as if they were zero.
  9333. if (S->getString().empty())
  9334. fill = llvm::APInt(32, 0);
  9335. else if (S->getString().getAsInteger(0, fill))
  9336. return false;
  9337. if (Context.getTargetInfo().isNan2008()) {
  9338. if (SNaN)
  9339. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  9340. else
  9341. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  9342. } else {
  9343. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  9344. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  9345. // a different encoding to what became a standard in 2008, and for pre-
  9346. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  9347. // sNaN. This is now known as "legacy NaN" encoding.
  9348. if (SNaN)
  9349. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  9350. else
  9351. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  9352. }
  9353. return true;
  9354. }
  9355. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  9356. switch (E->getBuiltinCallee()) {
  9357. default:
  9358. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9359. case Builtin::BI__builtin_huge_val:
  9360. case Builtin::BI__builtin_huge_valf:
  9361. case Builtin::BI__builtin_huge_vall:
  9362. case Builtin::BI__builtin_huge_valf128:
  9363. case Builtin::BI__builtin_inf:
  9364. case Builtin::BI__builtin_inff:
  9365. case Builtin::BI__builtin_infl:
  9366. case Builtin::BI__builtin_inff128: {
  9367. const llvm::fltSemantics &Sem =
  9368. Info.Ctx.getFloatTypeSemantics(E->getType());
  9369. Result = llvm::APFloat::getInf(Sem);
  9370. return true;
  9371. }
  9372. case Builtin::BI__builtin_nans:
  9373. case Builtin::BI__builtin_nansf:
  9374. case Builtin::BI__builtin_nansl:
  9375. case Builtin::BI__builtin_nansf128:
  9376. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  9377. true, Result))
  9378. return Error(E);
  9379. return true;
  9380. case Builtin::BI__builtin_nan:
  9381. case Builtin::BI__builtin_nanf:
  9382. case Builtin::BI__builtin_nanl:
  9383. case Builtin::BI__builtin_nanf128:
  9384. // If this is __builtin_nan() turn this into a nan, otherwise we
  9385. // can't constant fold it.
  9386. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  9387. false, Result))
  9388. return Error(E);
  9389. return true;
  9390. case Builtin::BI__builtin_fabs:
  9391. case Builtin::BI__builtin_fabsf:
  9392. case Builtin::BI__builtin_fabsl:
  9393. case Builtin::BI__builtin_fabsf128:
  9394. if (!EvaluateFloat(E->getArg(0), Result, Info))
  9395. return false;
  9396. if (Result.isNegative())
  9397. Result.changeSign();
  9398. return true;
  9399. // FIXME: Builtin::BI__builtin_powi
  9400. // FIXME: Builtin::BI__builtin_powif
  9401. // FIXME: Builtin::BI__builtin_powil
  9402. case Builtin::BI__builtin_copysign:
  9403. case Builtin::BI__builtin_copysignf:
  9404. case Builtin::BI__builtin_copysignl:
  9405. case Builtin::BI__builtin_copysignf128: {
  9406. APFloat RHS(0.);
  9407. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  9408. !EvaluateFloat(E->getArg(1), RHS, Info))
  9409. return false;
  9410. Result.copySign(RHS);
  9411. return true;
  9412. }
  9413. }
  9414. }
  9415. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9416. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9417. ComplexValue CV;
  9418. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  9419. return false;
  9420. Result = CV.FloatReal;
  9421. return true;
  9422. }
  9423. return Visit(E->getSubExpr());
  9424. }
  9425. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9426. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9427. ComplexValue CV;
  9428. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  9429. return false;
  9430. Result = CV.FloatImag;
  9431. return true;
  9432. }
  9433. VisitIgnoredValue(E->getSubExpr());
  9434. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  9435. Result = llvm::APFloat::getZero(Sem);
  9436. return true;
  9437. }
  9438. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9439. switch (E->getOpcode()) {
  9440. default: return Error(E);
  9441. case UO_Plus:
  9442. return EvaluateFloat(E->getSubExpr(), Result, Info);
  9443. case UO_Minus:
  9444. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  9445. return false;
  9446. Result.changeSign();
  9447. return true;
  9448. }
  9449. }
  9450. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9451. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  9452. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9453. APFloat RHS(0.0);
  9454. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  9455. if (!LHSOK && !Info.noteFailure())
  9456. return false;
  9457. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  9458. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  9459. }
  9460. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  9461. Result = E->getValue();
  9462. return true;
  9463. }
  9464. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9465. const Expr* SubExpr = E->getSubExpr();
  9466. switch (E->getCastKind()) {
  9467. default:
  9468. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9469. case CK_IntegralToFloating: {
  9470. APSInt IntResult;
  9471. return EvaluateInteger(SubExpr, IntResult, Info) &&
  9472. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  9473. E->getType(), Result);
  9474. }
  9475. case CK_FloatingCast: {
  9476. if (!Visit(SubExpr))
  9477. return false;
  9478. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  9479. Result);
  9480. }
  9481. case CK_FloatingComplexToReal: {
  9482. ComplexValue V;
  9483. if (!EvaluateComplex(SubExpr, V, Info))
  9484. return false;
  9485. Result = V.getComplexFloatReal();
  9486. return true;
  9487. }
  9488. }
  9489. }
  9490. //===----------------------------------------------------------------------===//
  9491. // Complex Evaluation (for float and integer)
  9492. //===----------------------------------------------------------------------===//
  9493. namespace {
  9494. class ComplexExprEvaluator
  9495. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  9496. ComplexValue &Result;
  9497. public:
  9498. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  9499. : ExprEvaluatorBaseTy(info), Result(Result) {}
  9500. bool Success(const APValue &V, const Expr *e) {
  9501. Result.setFrom(V);
  9502. return true;
  9503. }
  9504. bool ZeroInitialization(const Expr *E);
  9505. //===--------------------------------------------------------------------===//
  9506. // Visitor Methods
  9507. //===--------------------------------------------------------------------===//
  9508. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  9509. bool VisitCastExpr(const CastExpr *E);
  9510. bool VisitBinaryOperator(const BinaryOperator *E);
  9511. bool VisitUnaryOperator(const UnaryOperator *E);
  9512. bool VisitInitListExpr(const InitListExpr *E);
  9513. };
  9514. } // end anonymous namespace
  9515. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  9516. EvalInfo &Info) {
  9517. assert(E->isRValue() && E->getType()->isAnyComplexType());
  9518. return ComplexExprEvaluator(Info, Result).Visit(E);
  9519. }
  9520. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  9521. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  9522. if (ElemTy->isRealFloatingType()) {
  9523. Result.makeComplexFloat();
  9524. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  9525. Result.FloatReal = Zero;
  9526. Result.FloatImag = Zero;
  9527. } else {
  9528. Result.makeComplexInt();
  9529. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  9530. Result.IntReal = Zero;
  9531. Result.IntImag = Zero;
  9532. }
  9533. return true;
  9534. }
  9535. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  9536. const Expr* SubExpr = E->getSubExpr();
  9537. if (SubExpr->getType()->isRealFloatingType()) {
  9538. Result.makeComplexFloat();
  9539. APFloat &Imag = Result.FloatImag;
  9540. if (!EvaluateFloat(SubExpr, Imag, Info))
  9541. return false;
  9542. Result.FloatReal = APFloat(Imag.getSemantics());
  9543. return true;
  9544. } else {
  9545. assert(SubExpr->getType()->isIntegerType() &&
  9546. "Unexpected imaginary literal.");
  9547. Result.makeComplexInt();
  9548. APSInt &Imag = Result.IntImag;
  9549. if (!EvaluateInteger(SubExpr, Imag, Info))
  9550. return false;
  9551. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  9552. return true;
  9553. }
  9554. }
  9555. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9556. switch (E->getCastKind()) {
  9557. case CK_BitCast:
  9558. case CK_BaseToDerived:
  9559. case CK_DerivedToBase:
  9560. case CK_UncheckedDerivedToBase:
  9561. case CK_Dynamic:
  9562. case CK_ToUnion:
  9563. case CK_ArrayToPointerDecay:
  9564. case CK_FunctionToPointerDecay:
  9565. case CK_NullToPointer:
  9566. case CK_NullToMemberPointer:
  9567. case CK_BaseToDerivedMemberPointer:
  9568. case CK_DerivedToBaseMemberPointer:
  9569. case CK_MemberPointerToBoolean:
  9570. case CK_ReinterpretMemberPointer:
  9571. case CK_ConstructorConversion:
  9572. case CK_IntegralToPointer:
  9573. case CK_PointerToIntegral:
  9574. case CK_PointerToBoolean:
  9575. case CK_ToVoid:
  9576. case CK_VectorSplat:
  9577. case CK_IntegralCast:
  9578. case CK_BooleanToSignedIntegral:
  9579. case CK_IntegralToBoolean:
  9580. case CK_IntegralToFloating:
  9581. case CK_FloatingToIntegral:
  9582. case CK_FloatingToBoolean:
  9583. case CK_FloatingCast:
  9584. case CK_CPointerToObjCPointerCast:
  9585. case CK_BlockPointerToObjCPointerCast:
  9586. case CK_AnyPointerToBlockPointerCast:
  9587. case CK_ObjCObjectLValueCast:
  9588. case CK_FloatingComplexToReal:
  9589. case CK_FloatingComplexToBoolean:
  9590. case CK_IntegralComplexToReal:
  9591. case CK_IntegralComplexToBoolean:
  9592. case CK_ARCProduceObject:
  9593. case CK_ARCConsumeObject:
  9594. case CK_ARCReclaimReturnedObject:
  9595. case CK_ARCExtendBlockObject:
  9596. case CK_CopyAndAutoreleaseBlockObject:
  9597. case CK_BuiltinFnToFnPtr:
  9598. case CK_ZeroToOCLOpaqueType:
  9599. case CK_NonAtomicToAtomic:
  9600. case CK_AddressSpaceConversion:
  9601. case CK_IntToOCLSampler:
  9602. case CK_FixedPointCast:
  9603. case CK_FixedPointToBoolean:
  9604. case CK_FixedPointToIntegral:
  9605. case CK_IntegralToFixedPoint:
  9606. llvm_unreachable("invalid cast kind for complex value");
  9607. case CK_LValueToRValue:
  9608. case CK_AtomicToNonAtomic:
  9609. case CK_NoOp:
  9610. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9611. case CK_Dependent:
  9612. case CK_LValueBitCast:
  9613. case CK_UserDefinedConversion:
  9614. return Error(E);
  9615. case CK_FloatingRealToComplex: {
  9616. APFloat &Real = Result.FloatReal;
  9617. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  9618. return false;
  9619. Result.makeComplexFloat();
  9620. Result.FloatImag = APFloat(Real.getSemantics());
  9621. return true;
  9622. }
  9623. case CK_FloatingComplexCast: {
  9624. if (!Visit(E->getSubExpr()))
  9625. return false;
  9626. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  9627. QualType From
  9628. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  9629. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  9630. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  9631. }
  9632. case CK_FloatingComplexToIntegralComplex: {
  9633. if (!Visit(E->getSubExpr()))
  9634. return false;
  9635. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  9636. QualType From
  9637. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  9638. Result.makeComplexInt();
  9639. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  9640. To, Result.IntReal) &&
  9641. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  9642. To, Result.IntImag);
  9643. }
  9644. case CK_IntegralRealToComplex: {
  9645. APSInt &Real = Result.IntReal;
  9646. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  9647. return false;
  9648. Result.makeComplexInt();
  9649. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  9650. return true;
  9651. }
  9652. case CK_IntegralComplexCast: {
  9653. if (!Visit(E->getSubExpr()))
  9654. return false;
  9655. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  9656. QualType From
  9657. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  9658. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  9659. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  9660. return true;
  9661. }
  9662. case CK_IntegralComplexToFloatingComplex: {
  9663. if (!Visit(E->getSubExpr()))
  9664. return false;
  9665. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  9666. QualType From
  9667. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  9668. Result.makeComplexFloat();
  9669. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  9670. To, Result.FloatReal) &&
  9671. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  9672. To, Result.FloatImag);
  9673. }
  9674. }
  9675. llvm_unreachable("unknown cast resulting in complex value");
  9676. }
  9677. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9678. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  9679. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9680. // Track whether the LHS or RHS is real at the type system level. When this is
  9681. // the case we can simplify our evaluation strategy.
  9682. bool LHSReal = false, RHSReal = false;
  9683. bool LHSOK;
  9684. if (E->getLHS()->getType()->isRealFloatingType()) {
  9685. LHSReal = true;
  9686. APFloat &Real = Result.FloatReal;
  9687. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  9688. if (LHSOK) {
  9689. Result.makeComplexFloat();
  9690. Result.FloatImag = APFloat(Real.getSemantics());
  9691. }
  9692. } else {
  9693. LHSOK = Visit(E->getLHS());
  9694. }
  9695. if (!LHSOK && !Info.noteFailure())
  9696. return false;
  9697. ComplexValue RHS;
  9698. if (E->getRHS()->getType()->isRealFloatingType()) {
  9699. RHSReal = true;
  9700. APFloat &Real = RHS.FloatReal;
  9701. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  9702. return false;
  9703. RHS.makeComplexFloat();
  9704. RHS.FloatImag = APFloat(Real.getSemantics());
  9705. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9706. return false;
  9707. assert(!(LHSReal && RHSReal) &&
  9708. "Cannot have both operands of a complex operation be real.");
  9709. switch (E->getOpcode()) {
  9710. default: return Error(E);
  9711. case BO_Add:
  9712. if (Result.isComplexFloat()) {
  9713. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  9714. APFloat::rmNearestTiesToEven);
  9715. if (LHSReal)
  9716. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9717. else if (!RHSReal)
  9718. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  9719. APFloat::rmNearestTiesToEven);
  9720. } else {
  9721. Result.getComplexIntReal() += RHS.getComplexIntReal();
  9722. Result.getComplexIntImag() += RHS.getComplexIntImag();
  9723. }
  9724. break;
  9725. case BO_Sub:
  9726. if (Result.isComplexFloat()) {
  9727. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  9728. APFloat::rmNearestTiesToEven);
  9729. if (LHSReal) {
  9730. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9731. Result.getComplexFloatImag().changeSign();
  9732. } else if (!RHSReal) {
  9733. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  9734. APFloat::rmNearestTiesToEven);
  9735. }
  9736. } else {
  9737. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  9738. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  9739. }
  9740. break;
  9741. case BO_Mul:
  9742. if (Result.isComplexFloat()) {
  9743. // This is an implementation of complex multiplication according to the
  9744. // constraints laid out in C11 Annex G. The implementation uses the
  9745. // following naming scheme:
  9746. // (a + ib) * (c + id)
  9747. ComplexValue LHS = Result;
  9748. APFloat &A = LHS.getComplexFloatReal();
  9749. APFloat &B = LHS.getComplexFloatImag();
  9750. APFloat &C = RHS.getComplexFloatReal();
  9751. APFloat &D = RHS.getComplexFloatImag();
  9752. APFloat &ResR = Result.getComplexFloatReal();
  9753. APFloat &ResI = Result.getComplexFloatImag();
  9754. if (LHSReal) {
  9755. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  9756. ResR = A * C;
  9757. ResI = A * D;
  9758. } else if (RHSReal) {
  9759. ResR = C * A;
  9760. ResI = C * B;
  9761. } else {
  9762. // In the fully general case, we need to handle NaNs and infinities
  9763. // robustly.
  9764. APFloat AC = A * C;
  9765. APFloat BD = B * D;
  9766. APFloat AD = A * D;
  9767. APFloat BC = B * C;
  9768. ResR = AC - BD;
  9769. ResI = AD + BC;
  9770. if (ResR.isNaN() && ResI.isNaN()) {
  9771. bool Recalc = false;
  9772. if (A.isInfinity() || B.isInfinity()) {
  9773. A = APFloat::copySign(
  9774. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9775. B = APFloat::copySign(
  9776. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9777. if (C.isNaN())
  9778. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9779. if (D.isNaN())
  9780. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9781. Recalc = true;
  9782. }
  9783. if (C.isInfinity() || D.isInfinity()) {
  9784. C = APFloat::copySign(
  9785. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9786. D = APFloat::copySign(
  9787. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9788. if (A.isNaN())
  9789. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9790. if (B.isNaN())
  9791. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9792. Recalc = true;
  9793. }
  9794. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  9795. AD.isInfinity() || BC.isInfinity())) {
  9796. if (A.isNaN())
  9797. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  9798. if (B.isNaN())
  9799. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  9800. if (C.isNaN())
  9801. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  9802. if (D.isNaN())
  9803. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  9804. Recalc = true;
  9805. }
  9806. if (Recalc) {
  9807. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  9808. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  9809. }
  9810. }
  9811. }
  9812. } else {
  9813. ComplexValue LHS = Result;
  9814. Result.getComplexIntReal() =
  9815. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  9816. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  9817. Result.getComplexIntImag() =
  9818. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  9819. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  9820. }
  9821. break;
  9822. case BO_Div:
  9823. if (Result.isComplexFloat()) {
  9824. // This is an implementation of complex division according to the
  9825. // constraints laid out in C11 Annex G. The implementation uses the
  9826. // following naming scheme:
  9827. // (a + ib) / (c + id)
  9828. ComplexValue LHS = Result;
  9829. APFloat &A = LHS.getComplexFloatReal();
  9830. APFloat &B = LHS.getComplexFloatImag();
  9831. APFloat &C = RHS.getComplexFloatReal();
  9832. APFloat &D = RHS.getComplexFloatImag();
  9833. APFloat &ResR = Result.getComplexFloatReal();
  9834. APFloat &ResI = Result.getComplexFloatImag();
  9835. if (RHSReal) {
  9836. ResR = A / C;
  9837. ResI = B / C;
  9838. } else {
  9839. if (LHSReal) {
  9840. // No real optimizations we can do here, stub out with zero.
  9841. B = APFloat::getZero(A.getSemantics());
  9842. }
  9843. int DenomLogB = 0;
  9844. APFloat MaxCD = maxnum(abs(C), abs(D));
  9845. if (MaxCD.isFinite()) {
  9846. DenomLogB = ilogb(MaxCD);
  9847. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  9848. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  9849. }
  9850. APFloat Denom = C * C + D * D;
  9851. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  9852. APFloat::rmNearestTiesToEven);
  9853. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  9854. APFloat::rmNearestTiesToEven);
  9855. if (ResR.isNaN() && ResI.isNaN()) {
  9856. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  9857. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  9858. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  9859. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  9860. D.isFinite()) {
  9861. A = APFloat::copySign(
  9862. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  9863. B = APFloat::copySign(
  9864. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  9865. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  9866. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  9867. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  9868. C = APFloat::copySign(
  9869. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  9870. D = APFloat::copySign(
  9871. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  9872. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  9873. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  9874. }
  9875. }
  9876. }
  9877. } else {
  9878. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  9879. return Error(E, diag::note_expr_divide_by_zero);
  9880. ComplexValue LHS = Result;
  9881. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9882. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  9883. Result.getComplexIntReal() =
  9884. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  9885. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  9886. Result.getComplexIntImag() =
  9887. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  9888. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  9889. }
  9890. break;
  9891. }
  9892. return true;
  9893. }
  9894. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9895. // Get the operand value into 'Result'.
  9896. if (!Visit(E->getSubExpr()))
  9897. return false;
  9898. switch (E->getOpcode()) {
  9899. default:
  9900. return Error(E);
  9901. case UO_Extension:
  9902. return true;
  9903. case UO_Plus:
  9904. // The result is always just the subexpr.
  9905. return true;
  9906. case UO_Minus:
  9907. if (Result.isComplexFloat()) {
  9908. Result.getComplexFloatReal().changeSign();
  9909. Result.getComplexFloatImag().changeSign();
  9910. }
  9911. else {
  9912. Result.getComplexIntReal() = -Result.getComplexIntReal();
  9913. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9914. }
  9915. return true;
  9916. case UO_Not:
  9917. if (Result.isComplexFloat())
  9918. Result.getComplexFloatImag().changeSign();
  9919. else
  9920. Result.getComplexIntImag() = -Result.getComplexIntImag();
  9921. return true;
  9922. }
  9923. }
  9924. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  9925. if (E->getNumInits() == 2) {
  9926. if (E->getType()->isComplexType()) {
  9927. Result.makeComplexFloat();
  9928. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  9929. return false;
  9930. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  9931. return false;
  9932. } else {
  9933. Result.makeComplexInt();
  9934. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  9935. return false;
  9936. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  9937. return false;
  9938. }
  9939. return true;
  9940. }
  9941. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  9942. }
  9943. //===----------------------------------------------------------------------===//
  9944. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  9945. // implicit conversion.
  9946. //===----------------------------------------------------------------------===//
  9947. namespace {
  9948. class AtomicExprEvaluator :
  9949. public ExprEvaluatorBase<AtomicExprEvaluator> {
  9950. const LValue *This;
  9951. APValue &Result;
  9952. public:
  9953. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  9954. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  9955. bool Success(const APValue &V, const Expr *E) {
  9956. Result = V;
  9957. return true;
  9958. }
  9959. bool ZeroInitialization(const Expr *E) {
  9960. ImplicitValueInitExpr VIE(
  9961. E->getType()->castAs<AtomicType>()->getValueType());
  9962. // For atomic-qualified class (and array) types in C++, initialize the
  9963. // _Atomic-wrapped subobject directly, in-place.
  9964. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  9965. : Evaluate(Result, Info, &VIE);
  9966. }
  9967. bool VisitCastExpr(const CastExpr *E) {
  9968. switch (E->getCastKind()) {
  9969. default:
  9970. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9971. case CK_NonAtomicToAtomic:
  9972. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  9973. : Evaluate(Result, Info, E->getSubExpr());
  9974. }
  9975. }
  9976. };
  9977. } // end anonymous namespace
  9978. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  9979. EvalInfo &Info) {
  9980. assert(E->isRValue() && E->getType()->isAtomicType());
  9981. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  9982. }
  9983. //===----------------------------------------------------------------------===//
  9984. // Void expression evaluation, primarily for a cast to void on the LHS of a
  9985. // comma operator
  9986. //===----------------------------------------------------------------------===//
  9987. namespace {
  9988. class VoidExprEvaluator
  9989. : public ExprEvaluatorBase<VoidExprEvaluator> {
  9990. public:
  9991. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  9992. bool Success(const APValue &V, const Expr *e) { return true; }
  9993. bool ZeroInitialization(const Expr *E) { return true; }
  9994. bool VisitCastExpr(const CastExpr *E) {
  9995. switch (E->getCastKind()) {
  9996. default:
  9997. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9998. case CK_ToVoid:
  9999. VisitIgnoredValue(E->getSubExpr());
  10000. return true;
  10001. }
  10002. }
  10003. bool VisitCallExpr(const CallExpr *E) {
  10004. switch (E->getBuiltinCallee()) {
  10005. default:
  10006. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10007. case Builtin::BI__assume:
  10008. case Builtin::BI__builtin_assume:
  10009. // The argument is not evaluated!
  10010. return true;
  10011. }
  10012. }
  10013. };
  10014. } // end anonymous namespace
  10015. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  10016. assert(E->isRValue() && E->getType()->isVoidType());
  10017. return VoidExprEvaluator(Info).Visit(E);
  10018. }
  10019. //===----------------------------------------------------------------------===//
  10020. // Top level Expr::EvaluateAsRValue method.
  10021. //===----------------------------------------------------------------------===//
  10022. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  10023. // In C, function designators are not lvalues, but we evaluate them as if they
  10024. // are.
  10025. QualType T = E->getType();
  10026. if (E->isGLValue() || T->isFunctionType()) {
  10027. LValue LV;
  10028. if (!EvaluateLValue(E, LV, Info))
  10029. return false;
  10030. LV.moveInto(Result);
  10031. } else if (T->isVectorType()) {
  10032. if (!EvaluateVector(E, Result, Info))
  10033. return false;
  10034. } else if (T->isIntegralOrEnumerationType()) {
  10035. if (!IntExprEvaluator(Info, Result).Visit(E))
  10036. return false;
  10037. } else if (T->hasPointerRepresentation()) {
  10038. LValue LV;
  10039. if (!EvaluatePointer(E, LV, Info))
  10040. return false;
  10041. LV.moveInto(Result);
  10042. } else if (T->isRealFloatingType()) {
  10043. llvm::APFloat F(0.0);
  10044. if (!EvaluateFloat(E, F, Info))
  10045. return false;
  10046. Result = APValue(F);
  10047. } else if (T->isAnyComplexType()) {
  10048. ComplexValue C;
  10049. if (!EvaluateComplex(E, C, Info))
  10050. return false;
  10051. C.moveInto(Result);
  10052. } else if (T->isFixedPointType()) {
  10053. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  10054. } else if (T->isMemberPointerType()) {
  10055. MemberPtr P;
  10056. if (!EvaluateMemberPointer(E, P, Info))
  10057. return false;
  10058. P.moveInto(Result);
  10059. return true;
  10060. } else if (T->isArrayType()) {
  10061. LValue LV;
  10062. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10063. if (!EvaluateArray(E, LV, Value, Info))
  10064. return false;
  10065. Result = Value;
  10066. } else if (T->isRecordType()) {
  10067. LValue LV;
  10068. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10069. if (!EvaluateRecord(E, LV, Value, Info))
  10070. return false;
  10071. Result = Value;
  10072. } else if (T->isVoidType()) {
  10073. if (!Info.getLangOpts().CPlusPlus11)
  10074. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  10075. << E->getType();
  10076. if (!EvaluateVoid(E, Info))
  10077. return false;
  10078. } else if (T->isAtomicType()) {
  10079. QualType Unqual = T.getAtomicUnqualifiedType();
  10080. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  10081. LValue LV;
  10082. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10083. if (!EvaluateAtomic(E, &LV, Value, Info))
  10084. return false;
  10085. } else {
  10086. if (!EvaluateAtomic(E, nullptr, Result, Info))
  10087. return false;
  10088. }
  10089. } else if (Info.getLangOpts().CPlusPlus11) {
  10090. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  10091. return false;
  10092. } else {
  10093. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10094. return false;
  10095. }
  10096. return true;
  10097. }
  10098. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  10099. /// cases, the in-place evaluation is essential, since later initializers for
  10100. /// an object can indirectly refer to subobjects which were initialized earlier.
  10101. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  10102. const Expr *E, bool AllowNonLiteralTypes) {
  10103. assert(!E->isValueDependent());
  10104. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  10105. return false;
  10106. if (E->isRValue()) {
  10107. // Evaluate arrays and record types in-place, so that later initializers can
  10108. // refer to earlier-initialized members of the object.
  10109. QualType T = E->getType();
  10110. if (T->isArrayType())
  10111. return EvaluateArray(E, This, Result, Info);
  10112. else if (T->isRecordType())
  10113. return EvaluateRecord(E, This, Result, Info);
  10114. else if (T->isAtomicType()) {
  10115. QualType Unqual = T.getAtomicUnqualifiedType();
  10116. if (Unqual->isArrayType() || Unqual->isRecordType())
  10117. return EvaluateAtomic(E, &This, Result, Info);
  10118. }
  10119. }
  10120. // For any other type, in-place evaluation is unimportant.
  10121. return Evaluate(Result, Info, E);
  10122. }
  10123. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  10124. /// lvalue-to-rvalue cast if it is an lvalue.
  10125. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  10126. if (E->getType().isNull())
  10127. return false;
  10128. if (!CheckLiteralType(Info, E))
  10129. return false;
  10130. if (!::Evaluate(Result, Info, E))
  10131. return false;
  10132. if (E->isGLValue()) {
  10133. LValue LV;
  10134. LV.setFrom(Info.Ctx, Result);
  10135. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10136. return false;
  10137. }
  10138. // Check this core constant expression is a constant expression.
  10139. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10140. }
  10141. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  10142. const ASTContext &Ctx, bool &IsConst) {
  10143. // Fast-path evaluations of integer literals, since we sometimes see files
  10144. // containing vast quantities of these.
  10145. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  10146. Result.Val = APValue(APSInt(L->getValue(),
  10147. L->getType()->isUnsignedIntegerType()));
  10148. IsConst = true;
  10149. return true;
  10150. }
  10151. // This case should be rare, but we need to check it before we check on
  10152. // the type below.
  10153. if (Exp->getType().isNull()) {
  10154. IsConst = false;
  10155. return true;
  10156. }
  10157. // FIXME: Evaluating values of large array and record types can cause
  10158. // performance problems. Only do so in C++11 for now.
  10159. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  10160. Exp->getType()->isRecordType()) &&
  10161. !Ctx.getLangOpts().CPlusPlus11) {
  10162. IsConst = false;
  10163. return true;
  10164. }
  10165. return false;
  10166. }
  10167. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  10168. Expr::SideEffectsKind SEK) {
  10169. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  10170. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  10171. }
  10172. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  10173. const ASTContext &Ctx, EvalInfo &Info) {
  10174. bool IsConst;
  10175. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  10176. return IsConst;
  10177. return EvaluateAsRValue(Info, E, Result.Val);
  10178. }
  10179. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  10180. const ASTContext &Ctx,
  10181. Expr::SideEffectsKind AllowSideEffects,
  10182. EvalInfo &Info) {
  10183. if (!E->getType()->isIntegralOrEnumerationType())
  10184. return false;
  10185. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  10186. !ExprResult.Val.isInt() ||
  10187. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10188. return false;
  10189. return true;
  10190. }
  10191. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  10192. const ASTContext &Ctx,
  10193. Expr::SideEffectsKind AllowSideEffects,
  10194. EvalInfo &Info) {
  10195. if (!E->getType()->isFixedPointType())
  10196. return false;
  10197. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  10198. return false;
  10199. if (!ExprResult.Val.isFixedPoint() ||
  10200. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10201. return false;
  10202. return true;
  10203. }
  10204. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  10205. /// any crazy technique (that has nothing to do with language standards) that
  10206. /// we want to. If this function returns true, it returns the folded constant
  10207. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  10208. /// will be applied to the result.
  10209. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  10210. bool InConstantContext) const {
  10211. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10212. Info.InConstantContext = InConstantContext;
  10213. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  10214. }
  10215. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  10216. const ASTContext &Ctx) const {
  10217. EvalResult Scratch;
  10218. return EvaluateAsRValue(Scratch, Ctx) &&
  10219. HandleConversionToBool(Scratch.Val, Result);
  10220. }
  10221. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  10222. SideEffectsKind AllowSideEffects) const {
  10223. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10224. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  10225. }
  10226. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  10227. SideEffectsKind AllowSideEffects) const {
  10228. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10229. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  10230. }
  10231. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  10232. SideEffectsKind AllowSideEffects) const {
  10233. if (!getType()->isRealFloatingType())
  10234. return false;
  10235. EvalResult ExprResult;
  10236. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  10237. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10238. return false;
  10239. Result = ExprResult.Val.getFloat();
  10240. return true;
  10241. }
  10242. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  10243. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  10244. LValue LV;
  10245. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  10246. !CheckLValueConstantExpression(Info, getExprLoc(),
  10247. Ctx.getLValueReferenceType(getType()), LV,
  10248. Expr::EvaluateForCodeGen))
  10249. return false;
  10250. LV.moveInto(Result.Val);
  10251. return true;
  10252. }
  10253. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  10254. const ASTContext &Ctx) const {
  10255. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  10256. EvalInfo Info(Ctx, Result, EM);
  10257. Info.InConstantContext = true;
  10258. if (!::Evaluate(Result.Val, Info, this))
  10259. return false;
  10260. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  10261. Usage);
  10262. }
  10263. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  10264. const VarDecl *VD,
  10265. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  10266. // FIXME: Evaluating initializers for large array and record types can cause
  10267. // performance problems. Only do so in C++11 for now.
  10268. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  10269. !Ctx.getLangOpts().CPlusPlus11)
  10270. return false;
  10271. Expr::EvalStatus EStatus;
  10272. EStatus.Diag = &Notes;
  10273. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  10274. ? EvalInfo::EM_ConstantExpression
  10275. : EvalInfo::EM_ConstantFold);
  10276. InitInfo.setEvaluatingDecl(VD, Value);
  10277. InitInfo.InConstantContext = true;
  10278. LValue LVal;
  10279. LVal.set(VD);
  10280. // C++11 [basic.start.init]p2:
  10281. // Variables with static storage duration or thread storage duration shall be
  10282. // zero-initialized before any other initialization takes place.
  10283. // This behavior is not present in C.
  10284. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  10285. !VD->getType()->isReferenceType()) {
  10286. ImplicitValueInitExpr VIE(VD->getType());
  10287. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  10288. /*AllowNonLiteralTypes=*/true))
  10289. return false;
  10290. }
  10291. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  10292. /*AllowNonLiteralTypes=*/true) ||
  10293. EStatus.HasSideEffects)
  10294. return false;
  10295. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  10296. Value);
  10297. }
  10298. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  10299. /// constant folded, but discard the result.
  10300. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  10301. EvalResult Result;
  10302. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  10303. !hasUnacceptableSideEffect(Result, SEK);
  10304. }
  10305. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  10306. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  10307. EvalResult EVResult;
  10308. EVResult.Diag = Diag;
  10309. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  10310. Info.InConstantContext = true;
  10311. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  10312. (void)Result;
  10313. assert(Result && "Could not evaluate expression");
  10314. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  10315. return EVResult.Val.getInt();
  10316. }
  10317. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  10318. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  10319. EvalResult EVResult;
  10320. EVResult.Diag = Diag;
  10321. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  10322. Info.InConstantContext = true;
  10323. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  10324. (void)Result;
  10325. assert(Result && "Could not evaluate expression");
  10326. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  10327. return EVResult.Val.getInt();
  10328. }
  10329. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  10330. bool IsConst;
  10331. EvalResult EVResult;
  10332. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  10333. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  10334. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  10335. }
  10336. }
  10337. bool Expr::EvalResult::isGlobalLValue() const {
  10338. assert(Val.isLValue());
  10339. return IsGlobalLValue(Val.getLValueBase());
  10340. }
  10341. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  10342. /// an integer constant expression.
  10343. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  10344. /// comma, etc
  10345. // CheckICE - This function does the fundamental ICE checking: the returned
  10346. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  10347. // and a (possibly null) SourceLocation indicating the location of the problem.
  10348. //
  10349. // Note that to reduce code duplication, this helper does no evaluation
  10350. // itself; the caller checks whether the expression is evaluatable, and
  10351. // in the rare cases where CheckICE actually cares about the evaluated
  10352. // value, it calls into Evaluate.
  10353. namespace {
  10354. enum ICEKind {
  10355. /// This expression is an ICE.
  10356. IK_ICE,
  10357. /// This expression is not an ICE, but if it isn't evaluated, it's
  10358. /// a legal subexpression for an ICE. This return value is used to handle
  10359. /// the comma operator in C99 mode, and non-constant subexpressions.
  10360. IK_ICEIfUnevaluated,
  10361. /// This expression is not an ICE, and is not a legal subexpression for one.
  10362. IK_NotICE
  10363. };
  10364. struct ICEDiag {
  10365. ICEKind Kind;
  10366. SourceLocation Loc;
  10367. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  10368. };
  10369. }
  10370. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  10371. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  10372. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  10373. Expr::EvalResult EVResult;
  10374. Expr::EvalStatus Status;
  10375. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10376. Info.InConstantContext = true;
  10377. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  10378. !EVResult.Val.isInt())
  10379. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10380. return NoDiag();
  10381. }
  10382. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  10383. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  10384. if (!E->getType()->isIntegralOrEnumerationType())
  10385. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10386. switch (E->getStmtClass()) {
  10387. #define ABSTRACT_STMT(Node)
  10388. #define STMT(Node, Base) case Expr::Node##Class:
  10389. #define EXPR(Node, Base)
  10390. #include "clang/AST/StmtNodes.inc"
  10391. case Expr::PredefinedExprClass:
  10392. case Expr::FloatingLiteralClass:
  10393. case Expr::ImaginaryLiteralClass:
  10394. case Expr::StringLiteralClass:
  10395. case Expr::ArraySubscriptExprClass:
  10396. case Expr::OMPArraySectionExprClass:
  10397. case Expr::MemberExprClass:
  10398. case Expr::CompoundAssignOperatorClass:
  10399. case Expr::CompoundLiteralExprClass:
  10400. case Expr::ExtVectorElementExprClass:
  10401. case Expr::DesignatedInitExprClass:
  10402. case Expr::ArrayInitLoopExprClass:
  10403. case Expr::ArrayInitIndexExprClass:
  10404. case Expr::NoInitExprClass:
  10405. case Expr::DesignatedInitUpdateExprClass:
  10406. case Expr::ImplicitValueInitExprClass:
  10407. case Expr::ParenListExprClass:
  10408. case Expr::VAArgExprClass:
  10409. case Expr::AddrLabelExprClass:
  10410. case Expr::StmtExprClass:
  10411. case Expr::CXXMemberCallExprClass:
  10412. case Expr::CUDAKernelCallExprClass:
  10413. case Expr::CXXDynamicCastExprClass:
  10414. case Expr::CXXTypeidExprClass:
  10415. case Expr::CXXUuidofExprClass:
  10416. case Expr::MSPropertyRefExprClass:
  10417. case Expr::MSPropertySubscriptExprClass:
  10418. case Expr::CXXNullPtrLiteralExprClass:
  10419. case Expr::UserDefinedLiteralClass:
  10420. case Expr::CXXThisExprClass:
  10421. case Expr::CXXThrowExprClass:
  10422. case Expr::CXXNewExprClass:
  10423. case Expr::CXXDeleteExprClass:
  10424. case Expr::CXXPseudoDestructorExprClass:
  10425. case Expr::UnresolvedLookupExprClass:
  10426. case Expr::TypoExprClass:
  10427. case Expr::DependentScopeDeclRefExprClass:
  10428. case Expr::CXXConstructExprClass:
  10429. case Expr::CXXInheritedCtorInitExprClass:
  10430. case Expr::CXXStdInitializerListExprClass:
  10431. case Expr::CXXBindTemporaryExprClass:
  10432. case Expr::ExprWithCleanupsClass:
  10433. case Expr::CXXTemporaryObjectExprClass:
  10434. case Expr::CXXUnresolvedConstructExprClass:
  10435. case Expr::CXXDependentScopeMemberExprClass:
  10436. case Expr::UnresolvedMemberExprClass:
  10437. case Expr::ObjCStringLiteralClass:
  10438. case Expr::ObjCBoxedExprClass:
  10439. case Expr::ObjCArrayLiteralClass:
  10440. case Expr::ObjCDictionaryLiteralClass:
  10441. case Expr::ObjCEncodeExprClass:
  10442. case Expr::ObjCMessageExprClass:
  10443. case Expr::ObjCSelectorExprClass:
  10444. case Expr::ObjCProtocolExprClass:
  10445. case Expr::ObjCIvarRefExprClass:
  10446. case Expr::ObjCPropertyRefExprClass:
  10447. case Expr::ObjCSubscriptRefExprClass:
  10448. case Expr::ObjCIsaExprClass:
  10449. case Expr::ObjCAvailabilityCheckExprClass:
  10450. case Expr::ShuffleVectorExprClass:
  10451. case Expr::ConvertVectorExprClass:
  10452. case Expr::BlockExprClass:
  10453. case Expr::NoStmtClass:
  10454. case Expr::OpaqueValueExprClass:
  10455. case Expr::PackExpansionExprClass:
  10456. case Expr::SubstNonTypeTemplateParmPackExprClass:
  10457. case Expr::FunctionParmPackExprClass:
  10458. case Expr::AsTypeExprClass:
  10459. case Expr::ObjCIndirectCopyRestoreExprClass:
  10460. case Expr::MaterializeTemporaryExprClass:
  10461. case Expr::PseudoObjectExprClass:
  10462. case Expr::AtomicExprClass:
  10463. case Expr::LambdaExprClass:
  10464. case Expr::CXXFoldExprClass:
  10465. case Expr::CoawaitExprClass:
  10466. case Expr::DependentCoawaitExprClass:
  10467. case Expr::CoyieldExprClass:
  10468. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10469. case Expr::InitListExprClass: {
  10470. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  10471. // form "T x = { a };" is equivalent to "T x = a;".
  10472. // Unless we're initializing a reference, T is a scalar as it is known to be
  10473. // of integral or enumeration type.
  10474. if (E->isRValue())
  10475. if (cast<InitListExpr>(E)->getNumInits() == 1)
  10476. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  10477. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10478. }
  10479. case Expr::SizeOfPackExprClass:
  10480. case Expr::GNUNullExprClass:
  10481. // GCC considers the GNU __null value to be an integral constant expression.
  10482. return NoDiag();
  10483. case Expr::SubstNonTypeTemplateParmExprClass:
  10484. return
  10485. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  10486. case Expr::ConstantExprClass:
  10487. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  10488. case Expr::ParenExprClass:
  10489. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  10490. case Expr::GenericSelectionExprClass:
  10491. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  10492. case Expr::IntegerLiteralClass:
  10493. case Expr::FixedPointLiteralClass:
  10494. case Expr::CharacterLiteralClass:
  10495. case Expr::ObjCBoolLiteralExprClass:
  10496. case Expr::CXXBoolLiteralExprClass:
  10497. case Expr::CXXScalarValueInitExprClass:
  10498. case Expr::TypeTraitExprClass:
  10499. case Expr::ArrayTypeTraitExprClass:
  10500. case Expr::ExpressionTraitExprClass:
  10501. case Expr::CXXNoexceptExprClass:
  10502. return NoDiag();
  10503. case Expr::CallExprClass:
  10504. case Expr::CXXOperatorCallExprClass: {
  10505. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  10506. // constant expressions, but they can never be ICEs because an ICE cannot
  10507. // contain an operand of (pointer to) function type.
  10508. const CallExpr *CE = cast<CallExpr>(E);
  10509. if (CE->getBuiltinCallee())
  10510. return CheckEvalInICE(E, Ctx);
  10511. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10512. }
  10513. case Expr::DeclRefExprClass: {
  10514. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  10515. return NoDiag();
  10516. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  10517. if (Ctx.getLangOpts().CPlusPlus &&
  10518. D && IsConstNonVolatile(D->getType())) {
  10519. // Parameter variables are never constants. Without this check,
  10520. // getAnyInitializer() can find a default argument, which leads
  10521. // to chaos.
  10522. if (isa<ParmVarDecl>(D))
  10523. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  10524. // C++ 7.1.5.1p2
  10525. // A variable of non-volatile const-qualified integral or enumeration
  10526. // type initialized by an ICE can be used in ICEs.
  10527. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  10528. if (!Dcl->getType()->isIntegralOrEnumerationType())
  10529. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  10530. const VarDecl *VD;
  10531. // Look for a declaration of this variable that has an initializer, and
  10532. // check whether it is an ICE.
  10533. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  10534. return NoDiag();
  10535. else
  10536. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  10537. }
  10538. }
  10539. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10540. }
  10541. case Expr::UnaryOperatorClass: {
  10542. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  10543. switch (Exp->getOpcode()) {
  10544. case UO_PostInc:
  10545. case UO_PostDec:
  10546. case UO_PreInc:
  10547. case UO_PreDec:
  10548. case UO_AddrOf:
  10549. case UO_Deref:
  10550. case UO_Coawait:
  10551. // C99 6.6/3 allows increment and decrement within unevaluated
  10552. // subexpressions of constant expressions, but they can never be ICEs
  10553. // because an ICE cannot contain an lvalue operand.
  10554. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10555. case UO_Extension:
  10556. case UO_LNot:
  10557. case UO_Plus:
  10558. case UO_Minus:
  10559. case UO_Not:
  10560. case UO_Real:
  10561. case UO_Imag:
  10562. return CheckICE(Exp->getSubExpr(), Ctx);
  10563. }
  10564. llvm_unreachable("invalid unary operator class");
  10565. }
  10566. case Expr::OffsetOfExprClass: {
  10567. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  10568. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  10569. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  10570. // compliance: we should warn earlier for offsetof expressions with
  10571. // array subscripts that aren't ICEs, and if the array subscripts
  10572. // are ICEs, the value of the offsetof must be an integer constant.
  10573. return CheckEvalInICE(E, Ctx);
  10574. }
  10575. case Expr::UnaryExprOrTypeTraitExprClass: {
  10576. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  10577. if ((Exp->getKind() == UETT_SizeOf) &&
  10578. Exp->getTypeOfArgument()->isVariableArrayType())
  10579. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10580. return NoDiag();
  10581. }
  10582. case Expr::BinaryOperatorClass: {
  10583. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  10584. switch (Exp->getOpcode()) {
  10585. case BO_PtrMemD:
  10586. case BO_PtrMemI:
  10587. case BO_Assign:
  10588. case BO_MulAssign:
  10589. case BO_DivAssign:
  10590. case BO_RemAssign:
  10591. case BO_AddAssign:
  10592. case BO_SubAssign:
  10593. case BO_ShlAssign:
  10594. case BO_ShrAssign:
  10595. case BO_AndAssign:
  10596. case BO_XorAssign:
  10597. case BO_OrAssign:
  10598. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  10599. // constant expressions, but they can never be ICEs because an ICE cannot
  10600. // contain an lvalue operand.
  10601. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10602. case BO_Mul:
  10603. case BO_Div:
  10604. case BO_Rem:
  10605. case BO_Add:
  10606. case BO_Sub:
  10607. case BO_Shl:
  10608. case BO_Shr:
  10609. case BO_LT:
  10610. case BO_GT:
  10611. case BO_LE:
  10612. case BO_GE:
  10613. case BO_EQ:
  10614. case BO_NE:
  10615. case BO_And:
  10616. case BO_Xor:
  10617. case BO_Or:
  10618. case BO_Comma:
  10619. case BO_Cmp: {
  10620. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  10621. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  10622. if (Exp->getOpcode() == BO_Div ||
  10623. Exp->getOpcode() == BO_Rem) {
  10624. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  10625. // we don't evaluate one.
  10626. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  10627. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  10628. if (REval == 0)
  10629. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  10630. if (REval.isSigned() && REval.isAllOnesValue()) {
  10631. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  10632. if (LEval.isMinSignedValue())
  10633. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  10634. }
  10635. }
  10636. }
  10637. if (Exp->getOpcode() == BO_Comma) {
  10638. if (Ctx.getLangOpts().C99) {
  10639. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  10640. // if it isn't evaluated.
  10641. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  10642. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  10643. } else {
  10644. // In both C89 and C++, commas in ICEs are illegal.
  10645. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10646. }
  10647. }
  10648. return Worst(LHSResult, RHSResult);
  10649. }
  10650. case BO_LAnd:
  10651. case BO_LOr: {
  10652. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  10653. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  10654. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  10655. // Rare case where the RHS has a comma "side-effect"; we need
  10656. // to actually check the condition to see whether the side
  10657. // with the comma is evaluated.
  10658. if ((Exp->getOpcode() == BO_LAnd) !=
  10659. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  10660. return RHSResult;
  10661. return NoDiag();
  10662. }
  10663. return Worst(LHSResult, RHSResult);
  10664. }
  10665. }
  10666. llvm_unreachable("invalid binary operator kind");
  10667. }
  10668. case Expr::ImplicitCastExprClass:
  10669. case Expr::CStyleCastExprClass:
  10670. case Expr::CXXFunctionalCastExprClass:
  10671. case Expr::CXXStaticCastExprClass:
  10672. case Expr::CXXReinterpretCastExprClass:
  10673. case Expr::CXXConstCastExprClass:
  10674. case Expr::ObjCBridgedCastExprClass: {
  10675. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  10676. if (isa<ExplicitCastExpr>(E)) {
  10677. if (const FloatingLiteral *FL
  10678. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  10679. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  10680. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  10681. APSInt IgnoredVal(DestWidth, !DestSigned);
  10682. bool Ignored;
  10683. // If the value does not fit in the destination type, the behavior is
  10684. // undefined, so we are not required to treat it as a constant
  10685. // expression.
  10686. if (FL->getValue().convertToInteger(IgnoredVal,
  10687. llvm::APFloat::rmTowardZero,
  10688. &Ignored) & APFloat::opInvalidOp)
  10689. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10690. return NoDiag();
  10691. }
  10692. }
  10693. switch (cast<CastExpr>(E)->getCastKind()) {
  10694. case CK_LValueToRValue:
  10695. case CK_AtomicToNonAtomic:
  10696. case CK_NonAtomicToAtomic:
  10697. case CK_NoOp:
  10698. case CK_IntegralToBoolean:
  10699. case CK_IntegralCast:
  10700. return CheckICE(SubExpr, Ctx);
  10701. default:
  10702. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10703. }
  10704. }
  10705. case Expr::BinaryConditionalOperatorClass: {
  10706. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  10707. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  10708. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  10709. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  10710. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  10711. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  10712. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  10713. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  10714. return FalseResult;
  10715. }
  10716. case Expr::ConditionalOperatorClass: {
  10717. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  10718. // If the condition (ignoring parens) is a __builtin_constant_p call,
  10719. // then only the true side is actually considered in an integer constant
  10720. // expression, and it is fully evaluated. This is an important GNU
  10721. // extension. See GCC PR38377 for discussion.
  10722. if (const CallExpr *CallCE
  10723. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  10724. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  10725. return CheckEvalInICE(E, Ctx);
  10726. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  10727. if (CondResult.Kind == IK_NotICE)
  10728. return CondResult;
  10729. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  10730. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  10731. if (TrueResult.Kind == IK_NotICE)
  10732. return TrueResult;
  10733. if (FalseResult.Kind == IK_NotICE)
  10734. return FalseResult;
  10735. if (CondResult.Kind == IK_ICEIfUnevaluated)
  10736. return CondResult;
  10737. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  10738. return NoDiag();
  10739. // Rare case where the diagnostics depend on which side is evaluated
  10740. // Note that if we get here, CondResult is 0, and at least one of
  10741. // TrueResult and FalseResult is non-zero.
  10742. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  10743. return FalseResult;
  10744. return TrueResult;
  10745. }
  10746. case Expr::CXXDefaultArgExprClass:
  10747. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  10748. case Expr::CXXDefaultInitExprClass:
  10749. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  10750. case Expr::ChooseExprClass: {
  10751. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  10752. }
  10753. }
  10754. llvm_unreachable("Invalid StmtClass!");
  10755. }
  10756. /// Evaluate an expression as a C++11 integral constant expression.
  10757. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  10758. const Expr *E,
  10759. llvm::APSInt *Value,
  10760. SourceLocation *Loc) {
  10761. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10762. if (Loc) *Loc = E->getExprLoc();
  10763. return false;
  10764. }
  10765. APValue Result;
  10766. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  10767. return false;
  10768. if (!Result.isInt()) {
  10769. if (Loc) *Loc = E->getExprLoc();
  10770. return false;
  10771. }
  10772. if (Value) *Value = Result.getInt();
  10773. return true;
  10774. }
  10775. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  10776. SourceLocation *Loc) const {
  10777. if (Ctx.getLangOpts().CPlusPlus11)
  10778. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  10779. ICEDiag D = CheckICE(this, Ctx);
  10780. if (D.Kind != IK_ICE) {
  10781. if (Loc) *Loc = D.Loc;
  10782. return false;
  10783. }
  10784. return true;
  10785. }
  10786. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  10787. SourceLocation *Loc, bool isEvaluated) const {
  10788. if (Ctx.getLangOpts().CPlusPlus11)
  10789. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  10790. if (!isIntegerConstantExpr(Ctx, Loc))
  10791. return false;
  10792. // The only possible side-effects here are due to UB discovered in the
  10793. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  10794. // required to treat the expression as an ICE, so we produce the folded
  10795. // value.
  10796. EvalResult ExprResult;
  10797. Expr::EvalStatus Status;
  10798. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  10799. Info.InConstantContext = true;
  10800. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  10801. llvm_unreachable("ICE cannot be evaluated!");
  10802. Value = ExprResult.Val.getInt();
  10803. return true;
  10804. }
  10805. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  10806. return CheckICE(this, Ctx).Kind == IK_ICE;
  10807. }
  10808. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  10809. SourceLocation *Loc) const {
  10810. // We support this checking in C++98 mode in order to diagnose compatibility
  10811. // issues.
  10812. assert(Ctx.getLangOpts().CPlusPlus);
  10813. // Build evaluation settings.
  10814. Expr::EvalStatus Status;
  10815. SmallVector<PartialDiagnosticAt, 8> Diags;
  10816. Status.Diag = &Diags;
  10817. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10818. APValue Scratch;
  10819. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  10820. if (!Diags.empty()) {
  10821. IsConstExpr = false;
  10822. if (Loc) *Loc = Diags[0].first;
  10823. } else if (!IsConstExpr) {
  10824. // FIXME: This shouldn't happen.
  10825. if (Loc) *Loc = getExprLoc();
  10826. }
  10827. return IsConstExpr;
  10828. }
  10829. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  10830. const FunctionDecl *Callee,
  10831. ArrayRef<const Expr*> Args,
  10832. const Expr *This) const {
  10833. Expr::EvalStatus Status;
  10834. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  10835. Info.InConstantContext = true;
  10836. LValue ThisVal;
  10837. const LValue *ThisPtr = nullptr;
  10838. if (This) {
  10839. #ifndef NDEBUG
  10840. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  10841. assert(MD && "Don't provide `this` for non-methods.");
  10842. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  10843. #endif
  10844. if (EvaluateObjectArgument(Info, This, ThisVal))
  10845. ThisPtr = &ThisVal;
  10846. if (Info.EvalStatus.HasSideEffects)
  10847. return false;
  10848. }
  10849. ArgVector ArgValues(Args.size());
  10850. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  10851. I != E; ++I) {
  10852. if ((*I)->isValueDependent() ||
  10853. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  10854. // If evaluation fails, throw away the argument entirely.
  10855. ArgValues[I - Args.begin()] = APValue();
  10856. if (Info.EvalStatus.HasSideEffects)
  10857. return false;
  10858. }
  10859. // Build fake call to Callee.
  10860. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  10861. ArgValues.data());
  10862. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  10863. }
  10864. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  10865. SmallVectorImpl<
  10866. PartialDiagnosticAt> &Diags) {
  10867. // FIXME: It would be useful to check constexpr function templates, but at the
  10868. // moment the constant expression evaluator cannot cope with the non-rigorous
  10869. // ASTs which we build for dependent expressions.
  10870. if (FD->isDependentContext())
  10871. return true;
  10872. Expr::EvalStatus Status;
  10873. Status.Diag = &Diags;
  10874. EvalInfo Info(FD->getASTContext(), Status,
  10875. EvalInfo::EM_PotentialConstantExpression);
  10876. Info.InConstantContext = true;
  10877. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  10878. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  10879. // Fabricate an arbitrary expression on the stack and pretend that it
  10880. // is a temporary being used as the 'this' pointer.
  10881. LValue This;
  10882. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  10883. This.set({&VIE, Info.CurrentCall->Index});
  10884. ArrayRef<const Expr*> Args;
  10885. APValue Scratch;
  10886. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  10887. // Evaluate the call as a constant initializer, to allow the construction
  10888. // of objects of non-literal types.
  10889. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  10890. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  10891. } else {
  10892. SourceLocation Loc = FD->getLocation();
  10893. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  10894. Args, FD->getBody(), Info, Scratch, nullptr);
  10895. }
  10896. return Diags.empty();
  10897. }
  10898. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  10899. const FunctionDecl *FD,
  10900. SmallVectorImpl<
  10901. PartialDiagnosticAt> &Diags) {
  10902. Expr::EvalStatus Status;
  10903. Status.Diag = &Diags;
  10904. EvalInfo Info(FD->getASTContext(), Status,
  10905. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  10906. Info.InConstantContext = true;
  10907. // Fabricate a call stack frame to give the arguments a plausible cover story.
  10908. ArrayRef<const Expr*> Args;
  10909. ArgVector ArgValues(0);
  10910. bool Success = EvaluateArgs(Args, ArgValues, Info);
  10911. (void)Success;
  10912. assert(Success &&
  10913. "Failed to set up arguments for potential constant evaluation");
  10914. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  10915. APValue ResultScratch;
  10916. Evaluate(ResultScratch, Info, E);
  10917. return Diags.empty();
  10918. }
  10919. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  10920. unsigned Type) const {
  10921. if (!getType()->isPointerType())
  10922. return false;
  10923. Expr::EvalStatus Status;
  10924. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  10925. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  10926. }