ExprConstant.cpp 452 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707
  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/CurrentSourceLocExprScope.h"
  40. #include "clang/AST/CXXInheritance.h"
  41. #include "clang/AST/Expr.h"
  42. #include "clang/AST/OSLog.h"
  43. #include "clang/AST/RecordLayout.h"
  44. #include "clang/AST/StmtVisitor.h"
  45. #include "clang/AST/TypeLoc.h"
  46. #include "clang/Basic/Builtins.h"
  47. #include "clang/Basic/FixedPoint.h"
  48. #include "clang/Basic/TargetInfo.h"
  49. #include "llvm/Support/SaveAndRestore.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include <cstring>
  52. #include <functional>
  53. #define DEBUG_TYPE "exprconstant"
  54. using namespace clang;
  55. using llvm::APSInt;
  56. using llvm::APFloat;
  57. static bool IsGlobalLValue(APValue::LValueBase B);
  58. namespace {
  59. struct LValue;
  60. struct CallStackFrame;
  61. struct EvalInfo;
  62. using SourceLocExprScopeGuard =
  63. CurrentSourceLocExprScope::SourceLocExprScopeGuard;
  64. static QualType getType(APValue::LValueBase B) {
  65. if (!B) return QualType();
  66. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  67. // FIXME: It's unclear where we're supposed to take the type from, and
  68. // this actually matters for arrays of unknown bound. Eg:
  69. //
  70. // extern int arr[]; void f() { extern int arr[3]; };
  71. // constexpr int *p = &arr[1]; // valid?
  72. //
  73. // For now, we take the array bound from the most recent declaration.
  74. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  75. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  76. QualType T = Redecl->getType();
  77. if (!T->isIncompleteArrayType())
  78. return T;
  79. }
  80. return D->getType();
  81. }
  82. if (B.is<TypeInfoLValue>())
  83. return B.getTypeInfoType();
  84. const Expr *Base = B.get<const Expr*>();
  85. // For a materialized temporary, the type of the temporary we materialized
  86. // may not be the type of the expression.
  87. if (const MaterializeTemporaryExpr *MTE =
  88. dyn_cast<MaterializeTemporaryExpr>(Base)) {
  89. SmallVector<const Expr *, 2> CommaLHSs;
  90. SmallVector<SubobjectAdjustment, 2> Adjustments;
  91. const Expr *Temp = MTE->GetTemporaryExpr();
  92. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  93. Adjustments);
  94. // Keep any cv-qualifiers from the reference if we generated a temporary
  95. // for it directly. Otherwise use the type after adjustment.
  96. if (!Adjustments.empty())
  97. return Inner->getType();
  98. }
  99. return Base->getType();
  100. }
  101. /// Get an LValue path entry, which is known to not be an array index, as a
  102. /// field declaration.
  103. static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
  104. return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
  105. }
  106. /// Get an LValue path entry, which is known to not be an array index, as a
  107. /// base class declaration.
  108. static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
  109. return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
  110. }
  111. /// Determine whether this LValue path entry for a base class names a virtual
  112. /// base class.
  113. static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
  114. return E.getAsBaseOrMember().getInt();
  115. }
  116. /// Given a CallExpr, try to get the alloc_size attribute. May return null.
  117. static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
  118. const FunctionDecl *Callee = CE->getDirectCallee();
  119. return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
  120. }
  121. /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
  122. /// This will look through a single cast.
  123. ///
  124. /// Returns null if we couldn't unwrap a function with alloc_size.
  125. static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
  126. if (!E->getType()->isPointerType())
  127. return nullptr;
  128. E = E->IgnoreParens();
  129. // If we're doing a variable assignment from e.g. malloc(N), there will
  130. // probably be a cast of some kind. In exotic cases, we might also see a
  131. // top-level ExprWithCleanups. Ignore them either way.
  132. if (const auto *FE = dyn_cast<FullExpr>(E))
  133. E = FE->getSubExpr()->IgnoreParens();
  134. if (const auto *Cast = dyn_cast<CastExpr>(E))
  135. E = Cast->getSubExpr()->IgnoreParens();
  136. if (const auto *CE = dyn_cast<CallExpr>(E))
  137. return getAllocSizeAttr(CE) ? CE : nullptr;
  138. return nullptr;
  139. }
  140. /// Determines whether or not the given Base contains a call to a function
  141. /// with the alloc_size attribute.
  142. static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
  143. const auto *E = Base.dyn_cast<const Expr *>();
  144. return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
  145. }
  146. /// The bound to claim that an array of unknown bound has.
  147. /// The value in MostDerivedArraySize is undefined in this case. So, set it
  148. /// to an arbitrary value that's likely to loudly break things if it's used.
  149. static const uint64_t AssumedSizeForUnsizedArray =
  150. std::numeric_limits<uint64_t>::max() / 2;
  151. /// Determines if an LValue with the given LValueBase will have an unsized
  152. /// array in its designator.
  153. /// Find the path length and type of the most-derived subobject in the given
  154. /// path, and find the size of the containing array, if any.
  155. static unsigned
  156. findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
  157. ArrayRef<APValue::LValuePathEntry> Path,
  158. uint64_t &ArraySize, QualType &Type, bool &IsArray,
  159. bool &FirstEntryIsUnsizedArray) {
  160. // This only accepts LValueBases from APValues, and APValues don't support
  161. // arrays that lack size info.
  162. assert(!isBaseAnAllocSizeCall(Base) &&
  163. "Unsized arrays shouldn't appear here");
  164. unsigned MostDerivedLength = 0;
  165. Type = getType(Base);
  166. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  167. if (Type->isArrayType()) {
  168. const ArrayType *AT = Ctx.getAsArrayType(Type);
  169. Type = AT->getElementType();
  170. MostDerivedLength = I + 1;
  171. IsArray = true;
  172. if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  173. ArraySize = CAT->getSize().getZExtValue();
  174. } else {
  175. assert(I == 0 && "unexpected unsized array designator");
  176. FirstEntryIsUnsizedArray = true;
  177. ArraySize = AssumedSizeForUnsizedArray;
  178. }
  179. } else if (Type->isAnyComplexType()) {
  180. const ComplexType *CT = Type->castAs<ComplexType>();
  181. Type = CT->getElementType();
  182. ArraySize = 2;
  183. MostDerivedLength = I + 1;
  184. IsArray = true;
  185. } else if (const FieldDecl *FD = getAsField(Path[I])) {
  186. Type = FD->getType();
  187. ArraySize = 0;
  188. MostDerivedLength = I + 1;
  189. IsArray = false;
  190. } else {
  191. // Path[I] describes a base class.
  192. ArraySize = 0;
  193. IsArray = false;
  194. }
  195. }
  196. return MostDerivedLength;
  197. }
  198. // The order of this enum is important for diagnostics.
  199. enum CheckSubobjectKind {
  200. CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
  201. CSK_Real, CSK_Imag
  202. };
  203. /// A path from a glvalue to a subobject of that glvalue.
  204. struct SubobjectDesignator {
  205. /// True if the subobject was named in a manner not supported by C++11. Such
  206. /// lvalues can still be folded, but they are not core constant expressions
  207. /// and we cannot perform lvalue-to-rvalue conversions on them.
  208. unsigned Invalid : 1;
  209. /// Is this a pointer one past the end of an object?
  210. unsigned IsOnePastTheEnd : 1;
  211. /// Indicator of whether the first entry is an unsized array.
  212. unsigned FirstEntryIsAnUnsizedArray : 1;
  213. /// Indicator of whether the most-derived object is an array element.
  214. unsigned MostDerivedIsArrayElement : 1;
  215. /// The length of the path to the most-derived object of which this is a
  216. /// subobject.
  217. unsigned MostDerivedPathLength : 28;
  218. /// The size of the array of which the most-derived object is an element.
  219. /// This will always be 0 if the most-derived object is not an array
  220. /// element. 0 is not an indicator of whether or not the most-derived object
  221. /// is an array, however, because 0-length arrays are allowed.
  222. ///
  223. /// If the current array is an unsized array, the value of this is
  224. /// undefined.
  225. uint64_t MostDerivedArraySize;
  226. /// The type of the most derived object referred to by this address.
  227. QualType MostDerivedType;
  228. typedef APValue::LValuePathEntry PathEntry;
  229. /// The entries on the path from the glvalue to the designated subobject.
  230. SmallVector<PathEntry, 8> Entries;
  231. SubobjectDesignator() : Invalid(true) {}
  232. explicit SubobjectDesignator(QualType T)
  233. : Invalid(false), IsOnePastTheEnd(false),
  234. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  235. MostDerivedPathLength(0), MostDerivedArraySize(0),
  236. MostDerivedType(T) {}
  237. SubobjectDesignator(ASTContext &Ctx, const APValue &V)
  238. : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
  239. FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
  240. MostDerivedPathLength(0), MostDerivedArraySize(0) {
  241. assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
  242. if (!Invalid) {
  243. IsOnePastTheEnd = V.isLValueOnePastTheEnd();
  244. ArrayRef<PathEntry> VEntries = V.getLValuePath();
  245. Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
  246. if (V.getLValueBase()) {
  247. bool IsArray = false;
  248. bool FirstIsUnsizedArray = false;
  249. MostDerivedPathLength = findMostDerivedSubobject(
  250. Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
  251. MostDerivedType, IsArray, FirstIsUnsizedArray);
  252. MostDerivedIsArrayElement = IsArray;
  253. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  254. }
  255. }
  256. }
  257. void truncate(ASTContext &Ctx, APValue::LValueBase Base,
  258. unsigned NewLength) {
  259. if (Invalid)
  260. return;
  261. assert(Base && "cannot truncate path for null pointer");
  262. assert(NewLength <= Entries.size() && "not a truncation");
  263. if (NewLength == Entries.size())
  264. return;
  265. Entries.resize(NewLength);
  266. bool IsArray = false;
  267. bool FirstIsUnsizedArray = false;
  268. MostDerivedPathLength = findMostDerivedSubobject(
  269. Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
  270. FirstIsUnsizedArray);
  271. MostDerivedIsArrayElement = IsArray;
  272. FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
  273. }
  274. void setInvalid() {
  275. Invalid = true;
  276. Entries.clear();
  277. }
  278. /// Determine whether the most derived subobject is an array without a
  279. /// known bound.
  280. bool isMostDerivedAnUnsizedArray() const {
  281. assert(!Invalid && "Calling this makes no sense on invalid designators");
  282. return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
  283. }
  284. /// Determine what the most derived array's size is. Results in an assertion
  285. /// failure if the most derived array lacks a size.
  286. uint64_t getMostDerivedArraySize() const {
  287. assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
  288. return MostDerivedArraySize;
  289. }
  290. /// Determine whether this is a one-past-the-end pointer.
  291. bool isOnePastTheEnd() const {
  292. assert(!Invalid);
  293. if (IsOnePastTheEnd)
  294. return true;
  295. if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
  296. Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
  297. MostDerivedArraySize)
  298. return true;
  299. return false;
  300. }
  301. /// Get the range of valid index adjustments in the form
  302. /// {maximum value that can be subtracted from this pointer,
  303. /// maximum value that can be added to this pointer}
  304. std::pair<uint64_t, uint64_t> validIndexAdjustments() {
  305. if (Invalid || isMostDerivedAnUnsizedArray())
  306. return {0, 0};
  307. // [expr.add]p4: For the purposes of these operators, a pointer to a
  308. // nonarray object behaves the same as a pointer to the first element of
  309. // an array of length one with the type of the object as its element type.
  310. bool IsArray = MostDerivedPathLength == Entries.size() &&
  311. MostDerivedIsArrayElement;
  312. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  313. : (uint64_t)IsOnePastTheEnd;
  314. uint64_t ArraySize =
  315. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  316. return {ArrayIndex, ArraySize - ArrayIndex};
  317. }
  318. /// Check that this refers to a valid subobject.
  319. bool isValidSubobject() const {
  320. if (Invalid)
  321. return false;
  322. return !isOnePastTheEnd();
  323. }
  324. /// Check that this refers to a valid subobject, and if not, produce a
  325. /// relevant diagnostic and set the designator as invalid.
  326. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
  327. /// Get the type of the designated object.
  328. QualType getType(ASTContext &Ctx) const {
  329. assert(!Invalid && "invalid designator has no subobject type");
  330. return MostDerivedPathLength == Entries.size()
  331. ? MostDerivedType
  332. : Ctx.getRecordType(getAsBaseClass(Entries.back()));
  333. }
  334. /// Update this designator to refer to the first element within this array.
  335. void addArrayUnchecked(const ConstantArrayType *CAT) {
  336. Entries.push_back(PathEntry::ArrayIndex(0));
  337. // This is a most-derived object.
  338. MostDerivedType = CAT->getElementType();
  339. MostDerivedIsArrayElement = true;
  340. MostDerivedArraySize = CAT->getSize().getZExtValue();
  341. MostDerivedPathLength = Entries.size();
  342. }
  343. /// Update this designator to refer to the first element within the array of
  344. /// elements of type T. This is an array of unknown size.
  345. void addUnsizedArrayUnchecked(QualType ElemTy) {
  346. Entries.push_back(PathEntry::ArrayIndex(0));
  347. MostDerivedType = ElemTy;
  348. MostDerivedIsArrayElement = true;
  349. // The value in MostDerivedArraySize is undefined in this case. So, set it
  350. // to an arbitrary value that's likely to loudly break things if it's
  351. // used.
  352. MostDerivedArraySize = AssumedSizeForUnsizedArray;
  353. MostDerivedPathLength = Entries.size();
  354. }
  355. /// Update this designator to refer to the given base or member of this
  356. /// object.
  357. void addDeclUnchecked(const Decl *D, bool Virtual = false) {
  358. Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
  359. // If this isn't a base class, it's a new most-derived object.
  360. if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
  361. MostDerivedType = FD->getType();
  362. MostDerivedIsArrayElement = false;
  363. MostDerivedArraySize = 0;
  364. MostDerivedPathLength = Entries.size();
  365. }
  366. }
  367. /// Update this designator to refer to the given complex component.
  368. void addComplexUnchecked(QualType EltTy, bool Imag) {
  369. Entries.push_back(PathEntry::ArrayIndex(Imag));
  370. // This is technically a most-derived object, though in practice this
  371. // is unlikely to matter.
  372. MostDerivedType = EltTy;
  373. MostDerivedIsArrayElement = true;
  374. MostDerivedArraySize = 2;
  375. MostDerivedPathLength = Entries.size();
  376. }
  377. void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
  378. void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
  379. const APSInt &N);
  380. /// Add N to the address of this subobject.
  381. void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
  382. if (Invalid || !N) return;
  383. uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
  384. if (isMostDerivedAnUnsizedArray()) {
  385. diagnoseUnsizedArrayPointerArithmetic(Info, E);
  386. // Can't verify -- trust that the user is doing the right thing (or if
  387. // not, trust that the caller will catch the bad behavior).
  388. // FIXME: Should we reject if this overflows, at least?
  389. Entries.back() = PathEntry::ArrayIndex(
  390. Entries.back().getAsArrayIndex() + TruncatedN);
  391. return;
  392. }
  393. // [expr.add]p4: For the purposes of these operators, a pointer to a
  394. // nonarray object behaves the same as a pointer to the first element of
  395. // an array of length one with the type of the object as its element type.
  396. bool IsArray = MostDerivedPathLength == Entries.size() &&
  397. MostDerivedIsArrayElement;
  398. uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
  399. : (uint64_t)IsOnePastTheEnd;
  400. uint64_t ArraySize =
  401. IsArray ? getMostDerivedArraySize() : (uint64_t)1;
  402. if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
  403. // Calculate the actual index in a wide enough type, so we can include
  404. // it in the note.
  405. N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
  406. (llvm::APInt&)N += ArrayIndex;
  407. assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
  408. diagnosePointerArithmetic(Info, E, N);
  409. setInvalid();
  410. return;
  411. }
  412. ArrayIndex += TruncatedN;
  413. assert(ArrayIndex <= ArraySize &&
  414. "bounds check succeeded for out-of-bounds index");
  415. if (IsArray)
  416. Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
  417. else
  418. IsOnePastTheEnd = (ArrayIndex != 0);
  419. }
  420. };
  421. /// A stack frame in the constexpr call stack.
  422. struct CallStackFrame {
  423. EvalInfo &Info;
  424. /// Parent - The caller of this stack frame.
  425. CallStackFrame *Caller;
  426. /// Callee - The function which was called.
  427. const FunctionDecl *Callee;
  428. /// This - The binding for the this pointer in this call, if any.
  429. const LValue *This;
  430. /// Arguments - Parameter bindings for this function call, indexed by
  431. /// parameters' function scope indices.
  432. APValue *Arguments;
  433. /// Source location information about the default argument or default
  434. /// initializer expression we're evaluating, if any.
  435. CurrentSourceLocExprScope CurSourceLocExprScope;
  436. // Note that we intentionally use std::map here so that references to
  437. // values are stable.
  438. typedef std::pair<const void *, unsigned> MapKeyTy;
  439. typedef std::map<MapKeyTy, APValue> MapTy;
  440. /// Temporaries - Temporary lvalues materialized within this stack frame.
  441. MapTy Temporaries;
  442. /// CallLoc - The location of the call expression for this call.
  443. SourceLocation CallLoc;
  444. /// Index - The call index of this call.
  445. unsigned Index;
  446. /// The stack of integers for tracking version numbers for temporaries.
  447. SmallVector<unsigned, 2> TempVersionStack = {1};
  448. unsigned CurTempVersion = TempVersionStack.back();
  449. unsigned getTempVersion() const { return TempVersionStack.back(); }
  450. void pushTempVersion() {
  451. TempVersionStack.push_back(++CurTempVersion);
  452. }
  453. void popTempVersion() {
  454. TempVersionStack.pop_back();
  455. }
  456. // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
  457. // on the overall stack usage of deeply-recursing constexpr evaluations.
  458. // (We should cache this map rather than recomputing it repeatedly.)
  459. // But let's try this and see how it goes; we can look into caching the map
  460. // as a later change.
  461. /// LambdaCaptureFields - Mapping from captured variables/this to
  462. /// corresponding data members in the closure class.
  463. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  464. FieldDecl *LambdaThisCaptureField;
  465. CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  466. const FunctionDecl *Callee, const LValue *This,
  467. APValue *Arguments);
  468. ~CallStackFrame();
  469. // Return the temporary for Key whose version number is Version.
  470. APValue *getTemporary(const void *Key, unsigned Version) {
  471. MapKeyTy KV(Key, Version);
  472. auto LB = Temporaries.lower_bound(KV);
  473. if (LB != Temporaries.end() && LB->first == KV)
  474. return &LB->second;
  475. // Pair (Key,Version) wasn't found in the map. Check that no elements
  476. // in the map have 'Key' as their key.
  477. assert((LB == Temporaries.end() || LB->first.first != Key) &&
  478. (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
  479. "Element with key 'Key' found in map");
  480. return nullptr;
  481. }
  482. // Return the current temporary for Key in the map.
  483. APValue *getCurrentTemporary(const void *Key) {
  484. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  485. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  486. return &std::prev(UB)->second;
  487. return nullptr;
  488. }
  489. // Return the version number of the current temporary for Key.
  490. unsigned getCurrentTemporaryVersion(const void *Key) const {
  491. auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
  492. if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
  493. return std::prev(UB)->first.second;
  494. return 0;
  495. }
  496. APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
  497. };
  498. /// Temporarily override 'this'.
  499. class ThisOverrideRAII {
  500. public:
  501. ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
  502. : Frame(Frame), OldThis(Frame.This) {
  503. if (Enable)
  504. Frame.This = NewThis;
  505. }
  506. ~ThisOverrideRAII() {
  507. Frame.This = OldThis;
  508. }
  509. private:
  510. CallStackFrame &Frame;
  511. const LValue *OldThis;
  512. };
  513. /// A partial diagnostic which we might know in advance that we are not going
  514. /// to emit.
  515. class OptionalDiagnostic {
  516. PartialDiagnostic *Diag;
  517. public:
  518. explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
  519. : Diag(Diag) {}
  520. template<typename T>
  521. OptionalDiagnostic &operator<<(const T &v) {
  522. if (Diag)
  523. *Diag << v;
  524. return *this;
  525. }
  526. OptionalDiagnostic &operator<<(const APSInt &I) {
  527. if (Diag) {
  528. SmallVector<char, 32> Buffer;
  529. I.toString(Buffer);
  530. *Diag << StringRef(Buffer.data(), Buffer.size());
  531. }
  532. return *this;
  533. }
  534. OptionalDiagnostic &operator<<(const APFloat &F) {
  535. if (Diag) {
  536. // FIXME: Force the precision of the source value down so we don't
  537. // print digits which are usually useless (we don't really care here if
  538. // we truncate a digit by accident in edge cases). Ideally,
  539. // APFloat::toString would automatically print the shortest
  540. // representation which rounds to the correct value, but it's a bit
  541. // tricky to implement.
  542. unsigned precision =
  543. llvm::APFloat::semanticsPrecision(F.getSemantics());
  544. precision = (precision * 59 + 195) / 196;
  545. SmallVector<char, 32> Buffer;
  546. F.toString(Buffer, precision);
  547. *Diag << StringRef(Buffer.data(), Buffer.size());
  548. }
  549. return *this;
  550. }
  551. OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
  552. if (Diag) {
  553. SmallVector<char, 32> Buffer;
  554. FX.toString(Buffer);
  555. *Diag << StringRef(Buffer.data(), Buffer.size());
  556. }
  557. return *this;
  558. }
  559. };
  560. /// A cleanup, and a flag indicating whether it is lifetime-extended.
  561. class Cleanup {
  562. llvm::PointerIntPair<APValue*, 1, bool> Value;
  563. public:
  564. Cleanup(APValue *Val, bool IsLifetimeExtended)
  565. : Value(Val, IsLifetimeExtended) {}
  566. bool isLifetimeExtended() const { return Value.getInt(); }
  567. void endLifetime() {
  568. *Value.getPointer() = APValue();
  569. }
  570. };
  571. /// A reference to an object whose construction we are currently evaluating.
  572. struct ObjectUnderConstruction {
  573. APValue::LValueBase Base;
  574. ArrayRef<APValue::LValuePathEntry> Path;
  575. friend bool operator==(const ObjectUnderConstruction &LHS,
  576. const ObjectUnderConstruction &RHS) {
  577. return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
  578. }
  579. friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
  580. return llvm::hash_combine(Obj.Base, Obj.Path);
  581. }
  582. };
  583. enum class ConstructionPhase { None, Bases, AfterBases };
  584. }
  585. namespace llvm {
  586. template<> struct DenseMapInfo<ObjectUnderConstruction> {
  587. using Base = DenseMapInfo<APValue::LValueBase>;
  588. static ObjectUnderConstruction getEmptyKey() {
  589. return {Base::getEmptyKey(), {}}; }
  590. static ObjectUnderConstruction getTombstoneKey() {
  591. return {Base::getTombstoneKey(), {}};
  592. }
  593. static unsigned getHashValue(const ObjectUnderConstruction &Object) {
  594. return hash_value(Object);
  595. }
  596. static bool isEqual(const ObjectUnderConstruction &LHS,
  597. const ObjectUnderConstruction &RHS) {
  598. return LHS == RHS;
  599. }
  600. };
  601. }
  602. namespace {
  603. /// EvalInfo - This is a private struct used by the evaluator to capture
  604. /// information about a subexpression as it is folded. It retains information
  605. /// about the AST context, but also maintains information about the folded
  606. /// expression.
  607. ///
  608. /// If an expression could be evaluated, it is still possible it is not a C
  609. /// "integer constant expression" or constant expression. If not, this struct
  610. /// captures information about how and why not.
  611. ///
  612. /// One bit of information passed *into* the request for constant folding
  613. /// indicates whether the subexpression is "evaluated" or not according to C
  614. /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
  615. /// evaluate the expression regardless of what the RHS is, but C only allows
  616. /// certain things in certain situations.
  617. struct EvalInfo {
  618. ASTContext &Ctx;
  619. /// EvalStatus - Contains information about the evaluation.
  620. Expr::EvalStatus &EvalStatus;
  621. /// CurrentCall - The top of the constexpr call stack.
  622. CallStackFrame *CurrentCall;
  623. /// CallStackDepth - The number of calls in the call stack right now.
  624. unsigned CallStackDepth;
  625. /// NextCallIndex - The next call index to assign.
  626. unsigned NextCallIndex;
  627. /// StepsLeft - The remaining number of evaluation steps we're permitted
  628. /// to perform. This is essentially a limit for the number of statements
  629. /// we will evaluate.
  630. unsigned StepsLeft;
  631. /// BottomFrame - The frame in which evaluation started. This must be
  632. /// initialized after CurrentCall and CallStackDepth.
  633. CallStackFrame BottomFrame;
  634. /// A stack of values whose lifetimes end at the end of some surrounding
  635. /// evaluation frame.
  636. llvm::SmallVector<Cleanup, 16> CleanupStack;
  637. /// EvaluatingDecl - This is the declaration whose initializer is being
  638. /// evaluated, if any.
  639. APValue::LValueBase EvaluatingDecl;
  640. /// EvaluatingDeclValue - This is the value being constructed for the
  641. /// declaration whose initializer is being evaluated, if any.
  642. APValue *EvaluatingDeclValue;
  643. /// Set of objects that are currently being constructed.
  644. llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
  645. ObjectsUnderConstruction;
  646. struct EvaluatingConstructorRAII {
  647. EvalInfo &EI;
  648. ObjectUnderConstruction Object;
  649. bool DidInsert;
  650. EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
  651. bool HasBases)
  652. : EI(EI), Object(Object) {
  653. DidInsert =
  654. EI.ObjectsUnderConstruction
  655. .insert({Object, HasBases ? ConstructionPhase::Bases
  656. : ConstructionPhase::AfterBases})
  657. .second;
  658. }
  659. void finishedConstructingBases() {
  660. EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
  661. }
  662. ~EvaluatingConstructorRAII() {
  663. if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
  664. }
  665. };
  666. ConstructionPhase
  667. isEvaluatingConstructor(APValue::LValueBase Base,
  668. ArrayRef<APValue::LValuePathEntry> Path) {
  669. return ObjectsUnderConstruction.lookup({Base, Path});
  670. }
  671. /// If we're currently speculatively evaluating, the outermost call stack
  672. /// depth at which we can mutate state, otherwise 0.
  673. unsigned SpeculativeEvaluationDepth = 0;
  674. /// The current array initialization index, if we're performing array
  675. /// initialization.
  676. uint64_t ArrayInitIndex = -1;
  677. /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
  678. /// notes attached to it will also be stored, otherwise they will not be.
  679. bool HasActiveDiagnostic;
  680. /// Have we emitted a diagnostic explaining why we couldn't constant
  681. /// fold (not just why it's not strictly a constant expression)?
  682. bool HasFoldFailureDiagnostic;
  683. /// Whether or not we're in a context where the front end requires a
  684. /// constant value.
  685. bool InConstantContext;
  686. enum EvaluationMode {
  687. /// Evaluate as a constant expression. Stop if we find that the expression
  688. /// is not a constant expression.
  689. EM_ConstantExpression,
  690. /// Evaluate as a potential constant expression. Keep going if we hit a
  691. /// construct that we can't evaluate yet (because we don't yet know the
  692. /// value of something) but stop if we hit something that could never be
  693. /// a constant expression.
  694. EM_PotentialConstantExpression,
  695. /// Fold the expression to a constant. Stop if we hit a side-effect that
  696. /// we can't model.
  697. EM_ConstantFold,
  698. /// Evaluate the expression looking for integer overflow and similar
  699. /// issues. Don't worry about side-effects, and try to visit all
  700. /// subexpressions.
  701. EM_EvaluateForOverflow,
  702. /// Evaluate in any way we know how. Don't worry about side-effects that
  703. /// can't be modeled.
  704. EM_IgnoreSideEffects,
  705. /// Evaluate as a constant expression. Stop if we find that the expression
  706. /// is not a constant expression. Some expressions can be retried in the
  707. /// optimizer if we don't constant fold them here, but in an unevaluated
  708. /// context we try to fold them immediately since the optimizer never
  709. /// gets a chance to look at it.
  710. EM_ConstantExpressionUnevaluated,
  711. /// Evaluate as a potential constant expression. Keep going if we hit a
  712. /// construct that we can't evaluate yet (because we don't yet know the
  713. /// value of something) but stop if we hit something that could never be
  714. /// a constant expression. Some expressions can be retried in the
  715. /// optimizer if we don't constant fold them here, but in an unevaluated
  716. /// context we try to fold them immediately since the optimizer never
  717. /// gets a chance to look at it.
  718. EM_PotentialConstantExpressionUnevaluated,
  719. } EvalMode;
  720. /// Are we checking whether the expression is a potential constant
  721. /// expression?
  722. bool checkingPotentialConstantExpression() const {
  723. return EvalMode == EM_PotentialConstantExpression ||
  724. EvalMode == EM_PotentialConstantExpressionUnevaluated;
  725. }
  726. /// Are we checking an expression for overflow?
  727. // FIXME: We should check for any kind of undefined or suspicious behavior
  728. // in such constructs, not just overflow.
  729. bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
  730. EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
  731. : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
  732. CallStackDepth(0), NextCallIndex(1),
  733. StepsLeft(getLangOpts().ConstexprStepLimit),
  734. BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
  735. EvaluatingDecl((const ValueDecl *)nullptr),
  736. EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
  737. HasFoldFailureDiagnostic(false),
  738. InConstantContext(false), EvalMode(Mode) {}
  739. void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
  740. EvaluatingDecl = Base;
  741. EvaluatingDeclValue = &Value;
  742. }
  743. const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
  744. bool CheckCallLimit(SourceLocation Loc) {
  745. // Don't perform any constexpr calls (other than the call we're checking)
  746. // when checking a potential constant expression.
  747. if (checkingPotentialConstantExpression() && CallStackDepth > 1)
  748. return false;
  749. if (NextCallIndex == 0) {
  750. // NextCallIndex has wrapped around.
  751. FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
  752. return false;
  753. }
  754. if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
  755. return true;
  756. FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
  757. << getLangOpts().ConstexprCallDepth;
  758. return false;
  759. }
  760. std::pair<CallStackFrame *, unsigned>
  761. getCallFrameAndDepth(unsigned CallIndex) {
  762. assert(CallIndex && "no call index in getCallFrameAndDepth");
  763. // We will eventually hit BottomFrame, which has Index 1, so Frame can't
  764. // be null in this loop.
  765. unsigned Depth = CallStackDepth;
  766. CallStackFrame *Frame = CurrentCall;
  767. while (Frame->Index > CallIndex) {
  768. Frame = Frame->Caller;
  769. --Depth;
  770. }
  771. if (Frame->Index == CallIndex)
  772. return {Frame, Depth};
  773. return {nullptr, 0};
  774. }
  775. bool nextStep(const Stmt *S) {
  776. if (!StepsLeft) {
  777. FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
  778. return false;
  779. }
  780. --StepsLeft;
  781. return true;
  782. }
  783. private:
  784. /// Add a diagnostic to the diagnostics list.
  785. PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
  786. PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
  787. EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
  788. return EvalStatus.Diag->back().second;
  789. }
  790. /// Add notes containing a call stack to the current point of evaluation.
  791. void addCallStack(unsigned Limit);
  792. private:
  793. OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
  794. unsigned ExtraNotes, bool IsCCEDiag) {
  795. if (EvalStatus.Diag) {
  796. // If we have a prior diagnostic, it will be noting that the expression
  797. // isn't a constant expression. This diagnostic is more important,
  798. // unless we require this evaluation to produce a constant expression.
  799. //
  800. // FIXME: We might want to show both diagnostics to the user in
  801. // EM_ConstantFold mode.
  802. if (!EvalStatus.Diag->empty()) {
  803. switch (EvalMode) {
  804. case EM_ConstantFold:
  805. case EM_IgnoreSideEffects:
  806. case EM_EvaluateForOverflow:
  807. if (!HasFoldFailureDiagnostic)
  808. break;
  809. // We've already failed to fold something. Keep that diagnostic.
  810. LLVM_FALLTHROUGH;
  811. case EM_ConstantExpression:
  812. case EM_PotentialConstantExpression:
  813. case EM_ConstantExpressionUnevaluated:
  814. case EM_PotentialConstantExpressionUnevaluated:
  815. HasActiveDiagnostic = false;
  816. return OptionalDiagnostic();
  817. }
  818. }
  819. unsigned CallStackNotes = CallStackDepth - 1;
  820. unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
  821. if (Limit)
  822. CallStackNotes = std::min(CallStackNotes, Limit + 1);
  823. if (checkingPotentialConstantExpression())
  824. CallStackNotes = 0;
  825. HasActiveDiagnostic = true;
  826. HasFoldFailureDiagnostic = !IsCCEDiag;
  827. EvalStatus.Diag->clear();
  828. EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
  829. addDiag(Loc, DiagId);
  830. if (!checkingPotentialConstantExpression())
  831. addCallStack(Limit);
  832. return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
  833. }
  834. HasActiveDiagnostic = false;
  835. return OptionalDiagnostic();
  836. }
  837. public:
  838. // Diagnose that the evaluation could not be folded (FF => FoldFailure)
  839. OptionalDiagnostic
  840. FFDiag(SourceLocation Loc,
  841. diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
  842. unsigned ExtraNotes = 0) {
  843. return Diag(Loc, DiagId, ExtraNotes, false);
  844. }
  845. OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
  846. = diag::note_invalid_subexpr_in_const_expr,
  847. unsigned ExtraNotes = 0) {
  848. if (EvalStatus.Diag)
  849. return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
  850. HasActiveDiagnostic = false;
  851. return OptionalDiagnostic();
  852. }
  853. /// Diagnose that the evaluation does not produce a C++11 core constant
  854. /// expression.
  855. ///
  856. /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
  857. /// EM_PotentialConstantExpression mode and we produce one of these.
  858. OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
  859. = diag::note_invalid_subexpr_in_const_expr,
  860. unsigned ExtraNotes = 0) {
  861. // Don't override a previous diagnostic. Don't bother collecting
  862. // diagnostics if we're evaluating for overflow.
  863. if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
  864. HasActiveDiagnostic = false;
  865. return OptionalDiagnostic();
  866. }
  867. return Diag(Loc, DiagId, ExtraNotes, true);
  868. }
  869. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
  870. = diag::note_invalid_subexpr_in_const_expr,
  871. unsigned ExtraNotes = 0) {
  872. return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
  873. }
  874. /// Add a note to a prior diagnostic.
  875. OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
  876. if (!HasActiveDiagnostic)
  877. return OptionalDiagnostic();
  878. return OptionalDiagnostic(&addDiag(Loc, DiagId));
  879. }
  880. /// Add a stack of notes to a prior diagnostic.
  881. void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
  882. if (HasActiveDiagnostic) {
  883. EvalStatus.Diag->insert(EvalStatus.Diag->end(),
  884. Diags.begin(), Diags.end());
  885. }
  886. }
  887. /// Should we continue evaluation after encountering a side-effect that we
  888. /// couldn't model?
  889. bool keepEvaluatingAfterSideEffect() {
  890. switch (EvalMode) {
  891. case EM_PotentialConstantExpression:
  892. case EM_PotentialConstantExpressionUnevaluated:
  893. case EM_EvaluateForOverflow:
  894. case EM_IgnoreSideEffects:
  895. return true;
  896. case EM_ConstantExpression:
  897. case EM_ConstantExpressionUnevaluated:
  898. case EM_ConstantFold:
  899. return false;
  900. }
  901. llvm_unreachable("Missed EvalMode case");
  902. }
  903. /// Note that we have had a side-effect, and determine whether we should
  904. /// keep evaluating.
  905. bool noteSideEffect() {
  906. EvalStatus.HasSideEffects = true;
  907. return keepEvaluatingAfterSideEffect();
  908. }
  909. /// Should we continue evaluation after encountering undefined behavior?
  910. bool keepEvaluatingAfterUndefinedBehavior() {
  911. switch (EvalMode) {
  912. case EM_EvaluateForOverflow:
  913. case EM_IgnoreSideEffects:
  914. case EM_ConstantFold:
  915. return true;
  916. case EM_PotentialConstantExpression:
  917. case EM_PotentialConstantExpressionUnevaluated:
  918. case EM_ConstantExpression:
  919. case EM_ConstantExpressionUnevaluated:
  920. return false;
  921. }
  922. llvm_unreachable("Missed EvalMode case");
  923. }
  924. /// Note that we hit something that was technically undefined behavior, but
  925. /// that we can evaluate past it (such as signed overflow or floating-point
  926. /// division by zero.)
  927. bool noteUndefinedBehavior() {
  928. EvalStatus.HasUndefinedBehavior = true;
  929. return keepEvaluatingAfterUndefinedBehavior();
  930. }
  931. /// Should we continue evaluation as much as possible after encountering a
  932. /// construct which can't be reduced to a value?
  933. bool keepEvaluatingAfterFailure() {
  934. if (!StepsLeft)
  935. return false;
  936. switch (EvalMode) {
  937. case EM_PotentialConstantExpression:
  938. case EM_PotentialConstantExpressionUnevaluated:
  939. case EM_EvaluateForOverflow:
  940. return true;
  941. case EM_ConstantExpression:
  942. case EM_ConstantExpressionUnevaluated:
  943. case EM_ConstantFold:
  944. case EM_IgnoreSideEffects:
  945. return false;
  946. }
  947. llvm_unreachable("Missed EvalMode case");
  948. }
  949. /// Notes that we failed to evaluate an expression that other expressions
  950. /// directly depend on, and determine if we should keep evaluating. This
  951. /// should only be called if we actually intend to keep evaluating.
  952. ///
  953. /// Call noteSideEffect() instead if we may be able to ignore the value that
  954. /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
  955. ///
  956. /// (Foo(), 1) // use noteSideEffect
  957. /// (Foo() || true) // use noteSideEffect
  958. /// Foo() + 1 // use noteFailure
  959. LLVM_NODISCARD bool noteFailure() {
  960. // Failure when evaluating some expression often means there is some
  961. // subexpression whose evaluation was skipped. Therefore, (because we
  962. // don't track whether we skipped an expression when unwinding after an
  963. // evaluation failure) every evaluation failure that bubbles up from a
  964. // subexpression implies that a side-effect has potentially happened. We
  965. // skip setting the HasSideEffects flag to true until we decide to
  966. // continue evaluating after that point, which happens here.
  967. bool KeepGoing = keepEvaluatingAfterFailure();
  968. EvalStatus.HasSideEffects |= KeepGoing;
  969. return KeepGoing;
  970. }
  971. class ArrayInitLoopIndex {
  972. EvalInfo &Info;
  973. uint64_t OuterIndex;
  974. public:
  975. ArrayInitLoopIndex(EvalInfo &Info)
  976. : Info(Info), OuterIndex(Info.ArrayInitIndex) {
  977. Info.ArrayInitIndex = 0;
  978. }
  979. ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
  980. operator uint64_t&() { return Info.ArrayInitIndex; }
  981. };
  982. };
  983. /// Object used to treat all foldable expressions as constant expressions.
  984. struct FoldConstant {
  985. EvalInfo &Info;
  986. bool Enabled;
  987. bool HadNoPriorDiags;
  988. EvalInfo::EvaluationMode OldMode;
  989. explicit FoldConstant(EvalInfo &Info, bool Enabled)
  990. : Info(Info),
  991. Enabled(Enabled),
  992. HadNoPriorDiags(Info.EvalStatus.Diag &&
  993. Info.EvalStatus.Diag->empty() &&
  994. !Info.EvalStatus.HasSideEffects),
  995. OldMode(Info.EvalMode) {
  996. if (Enabled &&
  997. (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
  998. Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
  999. Info.EvalMode = EvalInfo::EM_ConstantFold;
  1000. }
  1001. void keepDiagnostics() { Enabled = false; }
  1002. ~FoldConstant() {
  1003. if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
  1004. !Info.EvalStatus.HasSideEffects)
  1005. Info.EvalStatus.Diag->clear();
  1006. Info.EvalMode = OldMode;
  1007. }
  1008. };
  1009. /// RAII object used to set the current evaluation mode to ignore
  1010. /// side-effects.
  1011. struct IgnoreSideEffectsRAII {
  1012. EvalInfo &Info;
  1013. EvalInfo::EvaluationMode OldMode;
  1014. explicit IgnoreSideEffectsRAII(EvalInfo &Info)
  1015. : Info(Info), OldMode(Info.EvalMode) {
  1016. if (!Info.checkingPotentialConstantExpression())
  1017. Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
  1018. }
  1019. ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
  1020. };
  1021. /// RAII object used to optionally suppress diagnostics and side-effects from
  1022. /// a speculative evaluation.
  1023. class SpeculativeEvaluationRAII {
  1024. EvalInfo *Info = nullptr;
  1025. Expr::EvalStatus OldStatus;
  1026. unsigned OldSpeculativeEvaluationDepth;
  1027. void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
  1028. Info = Other.Info;
  1029. OldStatus = Other.OldStatus;
  1030. OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
  1031. Other.Info = nullptr;
  1032. }
  1033. void maybeRestoreState() {
  1034. if (!Info)
  1035. return;
  1036. Info->EvalStatus = OldStatus;
  1037. Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
  1038. }
  1039. public:
  1040. SpeculativeEvaluationRAII() = default;
  1041. SpeculativeEvaluationRAII(
  1042. EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
  1043. : Info(&Info), OldStatus(Info.EvalStatus),
  1044. OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
  1045. Info.EvalStatus.Diag = NewDiag;
  1046. Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
  1047. }
  1048. SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
  1049. SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
  1050. moveFromAndCancel(std::move(Other));
  1051. }
  1052. SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
  1053. maybeRestoreState();
  1054. moveFromAndCancel(std::move(Other));
  1055. return *this;
  1056. }
  1057. ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
  1058. };
  1059. /// RAII object wrapping a full-expression or block scope, and handling
  1060. /// the ending of the lifetime of temporaries created within it.
  1061. template<bool IsFullExpression>
  1062. class ScopeRAII {
  1063. EvalInfo &Info;
  1064. unsigned OldStackSize;
  1065. public:
  1066. ScopeRAII(EvalInfo &Info)
  1067. : Info(Info), OldStackSize(Info.CleanupStack.size()) {
  1068. // Push a new temporary version. This is needed to distinguish between
  1069. // temporaries created in different iterations of a loop.
  1070. Info.CurrentCall->pushTempVersion();
  1071. }
  1072. ~ScopeRAII() {
  1073. // Body moved to a static method to encourage the compiler to inline away
  1074. // instances of this class.
  1075. cleanup(Info, OldStackSize);
  1076. Info.CurrentCall->popTempVersion();
  1077. }
  1078. private:
  1079. static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
  1080. unsigned NewEnd = OldStackSize;
  1081. for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
  1082. I != N; ++I) {
  1083. if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
  1084. // Full-expression cleanup of a lifetime-extended temporary: nothing
  1085. // to do, just move this cleanup to the right place in the stack.
  1086. std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
  1087. ++NewEnd;
  1088. } else {
  1089. // End the lifetime of the object.
  1090. Info.CleanupStack[I].endLifetime();
  1091. }
  1092. }
  1093. Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
  1094. Info.CleanupStack.end());
  1095. }
  1096. };
  1097. typedef ScopeRAII<false> BlockScopeRAII;
  1098. typedef ScopeRAII<true> FullExpressionRAII;
  1099. }
  1100. bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
  1101. CheckSubobjectKind CSK) {
  1102. if (Invalid)
  1103. return false;
  1104. if (isOnePastTheEnd()) {
  1105. Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
  1106. << CSK;
  1107. setInvalid();
  1108. return false;
  1109. }
  1110. // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
  1111. // must actually be at least one array element; even a VLA cannot have a
  1112. // bound of zero. And if our index is nonzero, we already had a CCEDiag.
  1113. return true;
  1114. }
  1115. void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
  1116. const Expr *E) {
  1117. Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
  1118. // Do not set the designator as invalid: we can represent this situation,
  1119. // and correct handling of __builtin_object_size requires us to do so.
  1120. }
  1121. void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
  1122. const Expr *E,
  1123. const APSInt &N) {
  1124. // If we're complaining, we must be able to statically determine the size of
  1125. // the most derived array.
  1126. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
  1127. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1128. << N << /*array*/ 0
  1129. << static_cast<unsigned>(getMostDerivedArraySize());
  1130. else
  1131. Info.CCEDiag(E, diag::note_constexpr_array_index)
  1132. << N << /*non-array*/ 1;
  1133. setInvalid();
  1134. }
  1135. CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
  1136. const FunctionDecl *Callee, const LValue *This,
  1137. APValue *Arguments)
  1138. : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
  1139. Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
  1140. Info.CurrentCall = this;
  1141. ++Info.CallStackDepth;
  1142. }
  1143. CallStackFrame::~CallStackFrame() {
  1144. assert(Info.CurrentCall == this && "calls retired out of order");
  1145. --Info.CallStackDepth;
  1146. Info.CurrentCall = Caller;
  1147. }
  1148. APValue &CallStackFrame::createTemporary(const void *Key,
  1149. bool IsLifetimeExtended) {
  1150. unsigned Version = Info.CurrentCall->getTempVersion();
  1151. APValue &Result = Temporaries[MapKeyTy(Key, Version)];
  1152. assert(Result.isAbsent() && "temporary created multiple times");
  1153. Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
  1154. return Result;
  1155. }
  1156. static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
  1157. void EvalInfo::addCallStack(unsigned Limit) {
  1158. // Determine which calls to skip, if any.
  1159. unsigned ActiveCalls = CallStackDepth - 1;
  1160. unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
  1161. if (Limit && Limit < ActiveCalls) {
  1162. SkipStart = Limit / 2 + Limit % 2;
  1163. SkipEnd = ActiveCalls - Limit / 2;
  1164. }
  1165. // Walk the call stack and add the diagnostics.
  1166. unsigned CallIdx = 0;
  1167. for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
  1168. Frame = Frame->Caller, ++CallIdx) {
  1169. // Skip this call?
  1170. if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
  1171. if (CallIdx == SkipStart) {
  1172. // Note that we're skipping calls.
  1173. addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
  1174. << unsigned(ActiveCalls - Limit);
  1175. }
  1176. continue;
  1177. }
  1178. // Use a different note for an inheriting constructor, because from the
  1179. // user's perspective it's not really a function at all.
  1180. if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
  1181. if (CD->isInheritingConstructor()) {
  1182. addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
  1183. << CD->getParent();
  1184. continue;
  1185. }
  1186. }
  1187. SmallVector<char, 128> Buffer;
  1188. llvm::raw_svector_ostream Out(Buffer);
  1189. describeCall(Frame, Out);
  1190. addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
  1191. }
  1192. }
  1193. /// Kinds of access we can perform on an object, for diagnostics. Note that
  1194. /// we consider a member function call to be a kind of access, even though
  1195. /// it is not formally an access of the object, because it has (largely) the
  1196. /// same set of semantic restrictions.
  1197. enum AccessKinds {
  1198. AK_Read,
  1199. AK_Assign,
  1200. AK_Increment,
  1201. AK_Decrement,
  1202. AK_MemberCall,
  1203. AK_DynamicCast,
  1204. AK_TypeId,
  1205. };
  1206. static bool isModification(AccessKinds AK) {
  1207. switch (AK) {
  1208. case AK_Read:
  1209. case AK_MemberCall:
  1210. case AK_DynamicCast:
  1211. case AK_TypeId:
  1212. return false;
  1213. case AK_Assign:
  1214. case AK_Increment:
  1215. case AK_Decrement:
  1216. return true;
  1217. }
  1218. llvm_unreachable("unknown access kind");
  1219. }
  1220. /// Is this an access per the C++ definition?
  1221. static bool isFormalAccess(AccessKinds AK) {
  1222. return AK == AK_Read || isModification(AK);
  1223. }
  1224. namespace {
  1225. struct ComplexValue {
  1226. private:
  1227. bool IsInt;
  1228. public:
  1229. APSInt IntReal, IntImag;
  1230. APFloat FloatReal, FloatImag;
  1231. ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
  1232. void makeComplexFloat() { IsInt = false; }
  1233. bool isComplexFloat() const { return !IsInt; }
  1234. APFloat &getComplexFloatReal() { return FloatReal; }
  1235. APFloat &getComplexFloatImag() { return FloatImag; }
  1236. void makeComplexInt() { IsInt = true; }
  1237. bool isComplexInt() const { return IsInt; }
  1238. APSInt &getComplexIntReal() { return IntReal; }
  1239. APSInt &getComplexIntImag() { return IntImag; }
  1240. void moveInto(APValue &v) const {
  1241. if (isComplexFloat())
  1242. v = APValue(FloatReal, FloatImag);
  1243. else
  1244. v = APValue(IntReal, IntImag);
  1245. }
  1246. void setFrom(const APValue &v) {
  1247. assert(v.isComplexFloat() || v.isComplexInt());
  1248. if (v.isComplexFloat()) {
  1249. makeComplexFloat();
  1250. FloatReal = v.getComplexFloatReal();
  1251. FloatImag = v.getComplexFloatImag();
  1252. } else {
  1253. makeComplexInt();
  1254. IntReal = v.getComplexIntReal();
  1255. IntImag = v.getComplexIntImag();
  1256. }
  1257. }
  1258. };
  1259. struct LValue {
  1260. APValue::LValueBase Base;
  1261. CharUnits Offset;
  1262. SubobjectDesignator Designator;
  1263. bool IsNullPtr : 1;
  1264. bool InvalidBase : 1;
  1265. const APValue::LValueBase getLValueBase() const { return Base; }
  1266. CharUnits &getLValueOffset() { return Offset; }
  1267. const CharUnits &getLValueOffset() const { return Offset; }
  1268. SubobjectDesignator &getLValueDesignator() { return Designator; }
  1269. const SubobjectDesignator &getLValueDesignator() const { return Designator;}
  1270. bool isNullPointer() const { return IsNullPtr;}
  1271. unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
  1272. unsigned getLValueVersion() const { return Base.getVersion(); }
  1273. void moveInto(APValue &V) const {
  1274. if (Designator.Invalid)
  1275. V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
  1276. else {
  1277. assert(!InvalidBase && "APValues can't handle invalid LValue bases");
  1278. V = APValue(Base, Offset, Designator.Entries,
  1279. Designator.IsOnePastTheEnd, IsNullPtr);
  1280. }
  1281. }
  1282. void setFrom(ASTContext &Ctx, const APValue &V) {
  1283. assert(V.isLValue() && "Setting LValue from a non-LValue?");
  1284. Base = V.getLValueBase();
  1285. Offset = V.getLValueOffset();
  1286. InvalidBase = false;
  1287. Designator = SubobjectDesignator(Ctx, V);
  1288. IsNullPtr = V.isNullPointer();
  1289. }
  1290. void set(APValue::LValueBase B, bool BInvalid = false) {
  1291. #ifndef NDEBUG
  1292. // We only allow a few types of invalid bases. Enforce that here.
  1293. if (BInvalid) {
  1294. const auto *E = B.get<const Expr *>();
  1295. assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
  1296. "Unexpected type of invalid base");
  1297. }
  1298. #endif
  1299. Base = B;
  1300. Offset = CharUnits::fromQuantity(0);
  1301. InvalidBase = BInvalid;
  1302. Designator = SubobjectDesignator(getType(B));
  1303. IsNullPtr = false;
  1304. }
  1305. void setNull(QualType PointerTy, uint64_t TargetVal) {
  1306. Base = (Expr *)nullptr;
  1307. Offset = CharUnits::fromQuantity(TargetVal);
  1308. InvalidBase = false;
  1309. Designator = SubobjectDesignator(PointerTy->getPointeeType());
  1310. IsNullPtr = true;
  1311. }
  1312. void setInvalid(APValue::LValueBase B, unsigned I = 0) {
  1313. set(B, true);
  1314. }
  1315. private:
  1316. // Check that this LValue is not based on a null pointer. If it is, produce
  1317. // a diagnostic and mark the designator as invalid.
  1318. template <typename GenDiagType>
  1319. bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
  1320. if (Designator.Invalid)
  1321. return false;
  1322. if (IsNullPtr) {
  1323. GenDiag();
  1324. Designator.setInvalid();
  1325. return false;
  1326. }
  1327. return true;
  1328. }
  1329. public:
  1330. bool checkNullPointer(EvalInfo &Info, const Expr *E,
  1331. CheckSubobjectKind CSK) {
  1332. return checkNullPointerDiagnosingWith([&Info, E, CSK] {
  1333. Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
  1334. });
  1335. }
  1336. bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
  1337. AccessKinds AK) {
  1338. return checkNullPointerDiagnosingWith([&Info, E, AK] {
  1339. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  1340. });
  1341. }
  1342. // Check this LValue refers to an object. If not, set the designator to be
  1343. // invalid and emit a diagnostic.
  1344. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
  1345. return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
  1346. Designator.checkSubobject(Info, E, CSK);
  1347. }
  1348. void addDecl(EvalInfo &Info, const Expr *E,
  1349. const Decl *D, bool Virtual = false) {
  1350. if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
  1351. Designator.addDeclUnchecked(D, Virtual);
  1352. }
  1353. void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
  1354. if (!Designator.Entries.empty()) {
  1355. Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
  1356. Designator.setInvalid();
  1357. return;
  1358. }
  1359. if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
  1360. assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
  1361. Designator.FirstEntryIsAnUnsizedArray = true;
  1362. Designator.addUnsizedArrayUnchecked(ElemTy);
  1363. }
  1364. }
  1365. void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
  1366. if (checkSubobject(Info, E, CSK_ArrayToPointer))
  1367. Designator.addArrayUnchecked(CAT);
  1368. }
  1369. void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
  1370. if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
  1371. Designator.addComplexUnchecked(EltTy, Imag);
  1372. }
  1373. void clearIsNullPointer() {
  1374. IsNullPtr = false;
  1375. }
  1376. void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
  1377. const APSInt &Index, CharUnits ElementSize) {
  1378. // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
  1379. // but we're not required to diagnose it and it's valid in C++.)
  1380. if (!Index)
  1381. return;
  1382. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  1383. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  1384. // offsets.
  1385. uint64_t Offset64 = Offset.getQuantity();
  1386. uint64_t ElemSize64 = ElementSize.getQuantity();
  1387. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  1388. Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
  1389. if (checkNullPointer(Info, E, CSK_ArrayIndex))
  1390. Designator.adjustIndex(Info, E, Index);
  1391. clearIsNullPointer();
  1392. }
  1393. void adjustOffset(CharUnits N) {
  1394. Offset += N;
  1395. if (N.getQuantity())
  1396. clearIsNullPointer();
  1397. }
  1398. };
  1399. struct MemberPtr {
  1400. MemberPtr() {}
  1401. explicit MemberPtr(const ValueDecl *Decl) :
  1402. DeclAndIsDerivedMember(Decl, false), Path() {}
  1403. /// The member or (direct or indirect) field referred to by this member
  1404. /// pointer, or 0 if this is a null member pointer.
  1405. const ValueDecl *getDecl() const {
  1406. return DeclAndIsDerivedMember.getPointer();
  1407. }
  1408. /// Is this actually a member of some type derived from the relevant class?
  1409. bool isDerivedMember() const {
  1410. return DeclAndIsDerivedMember.getInt();
  1411. }
  1412. /// Get the class which the declaration actually lives in.
  1413. const CXXRecordDecl *getContainingRecord() const {
  1414. return cast<CXXRecordDecl>(
  1415. DeclAndIsDerivedMember.getPointer()->getDeclContext());
  1416. }
  1417. void moveInto(APValue &V) const {
  1418. V = APValue(getDecl(), isDerivedMember(), Path);
  1419. }
  1420. void setFrom(const APValue &V) {
  1421. assert(V.isMemberPointer());
  1422. DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
  1423. DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
  1424. Path.clear();
  1425. ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
  1426. Path.insert(Path.end(), P.begin(), P.end());
  1427. }
  1428. /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
  1429. /// whether the member is a member of some class derived from the class type
  1430. /// of the member pointer.
  1431. llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
  1432. /// Path - The path of base/derived classes from the member declaration's
  1433. /// class (exclusive) to the class type of the member pointer (inclusive).
  1434. SmallVector<const CXXRecordDecl*, 4> Path;
  1435. /// Perform a cast towards the class of the Decl (either up or down the
  1436. /// hierarchy).
  1437. bool castBack(const CXXRecordDecl *Class) {
  1438. assert(!Path.empty());
  1439. const CXXRecordDecl *Expected;
  1440. if (Path.size() >= 2)
  1441. Expected = Path[Path.size() - 2];
  1442. else
  1443. Expected = getContainingRecord();
  1444. if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
  1445. // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
  1446. // if B does not contain the original member and is not a base or
  1447. // derived class of the class containing the original member, the result
  1448. // of the cast is undefined.
  1449. // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
  1450. // (D::*). We consider that to be a language defect.
  1451. return false;
  1452. }
  1453. Path.pop_back();
  1454. return true;
  1455. }
  1456. /// Perform a base-to-derived member pointer cast.
  1457. bool castToDerived(const CXXRecordDecl *Derived) {
  1458. if (!getDecl())
  1459. return true;
  1460. if (!isDerivedMember()) {
  1461. Path.push_back(Derived);
  1462. return true;
  1463. }
  1464. if (!castBack(Derived))
  1465. return false;
  1466. if (Path.empty())
  1467. DeclAndIsDerivedMember.setInt(false);
  1468. return true;
  1469. }
  1470. /// Perform a derived-to-base member pointer cast.
  1471. bool castToBase(const CXXRecordDecl *Base) {
  1472. if (!getDecl())
  1473. return true;
  1474. if (Path.empty())
  1475. DeclAndIsDerivedMember.setInt(true);
  1476. if (isDerivedMember()) {
  1477. Path.push_back(Base);
  1478. return true;
  1479. }
  1480. return castBack(Base);
  1481. }
  1482. };
  1483. /// Compare two member pointers, which are assumed to be of the same type.
  1484. static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
  1485. if (!LHS.getDecl() || !RHS.getDecl())
  1486. return !LHS.getDecl() && !RHS.getDecl();
  1487. if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
  1488. return false;
  1489. return LHS.Path == RHS.Path;
  1490. }
  1491. }
  1492. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
  1493. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
  1494. const LValue &This, const Expr *E,
  1495. bool AllowNonLiteralTypes = false);
  1496. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  1497. bool InvalidBaseOK = false);
  1498. static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
  1499. bool InvalidBaseOK = false);
  1500. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  1501. EvalInfo &Info);
  1502. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
  1503. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
  1504. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  1505. EvalInfo &Info);
  1506. static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
  1507. static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
  1508. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  1509. EvalInfo &Info);
  1510. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
  1511. /// Evaluate an integer or fixed point expression into an APResult.
  1512. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  1513. EvalInfo &Info);
  1514. /// Evaluate only a fixed point expression into an APResult.
  1515. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  1516. EvalInfo &Info);
  1517. //===----------------------------------------------------------------------===//
  1518. // Misc utilities
  1519. //===----------------------------------------------------------------------===//
  1520. /// A helper function to create a temporary and set an LValue.
  1521. template <class KeyTy>
  1522. static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
  1523. LValue &LV, CallStackFrame &Frame) {
  1524. LV.set({Key, Frame.Info.CurrentCall->Index,
  1525. Frame.Info.CurrentCall->getTempVersion()});
  1526. return Frame.createTemporary(Key, IsLifetimeExtended);
  1527. }
  1528. /// Negate an APSInt in place, converting it to a signed form if necessary, and
  1529. /// preserving its value (by extending by up to one bit as needed).
  1530. static void negateAsSigned(APSInt &Int) {
  1531. if (Int.isUnsigned() || Int.isMinSignedValue()) {
  1532. Int = Int.extend(Int.getBitWidth() + 1);
  1533. Int.setIsSigned(true);
  1534. }
  1535. Int = -Int;
  1536. }
  1537. /// Produce a string describing the given constexpr call.
  1538. static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
  1539. unsigned ArgIndex = 0;
  1540. bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
  1541. !isa<CXXConstructorDecl>(Frame->Callee) &&
  1542. cast<CXXMethodDecl>(Frame->Callee)->isInstance();
  1543. if (!IsMemberCall)
  1544. Out << *Frame->Callee << '(';
  1545. if (Frame->This && IsMemberCall) {
  1546. APValue Val;
  1547. Frame->This->moveInto(Val);
  1548. Val.printPretty(Out, Frame->Info.Ctx,
  1549. Frame->This->Designator.MostDerivedType);
  1550. // FIXME: Add parens around Val if needed.
  1551. Out << "->" << *Frame->Callee << '(';
  1552. IsMemberCall = false;
  1553. }
  1554. for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
  1555. E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
  1556. if (ArgIndex > (unsigned)IsMemberCall)
  1557. Out << ", ";
  1558. const ParmVarDecl *Param = *I;
  1559. const APValue &Arg = Frame->Arguments[ArgIndex];
  1560. Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
  1561. if (ArgIndex == 0 && IsMemberCall)
  1562. Out << "->" << *Frame->Callee << '(';
  1563. }
  1564. Out << ')';
  1565. }
  1566. /// Evaluate an expression to see if it had side-effects, and discard its
  1567. /// result.
  1568. /// \return \c true if the caller should keep evaluating.
  1569. static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
  1570. APValue Scratch;
  1571. if (!Evaluate(Scratch, Info, E))
  1572. // We don't need the value, but we might have skipped a side effect here.
  1573. return Info.noteSideEffect();
  1574. return true;
  1575. }
  1576. /// Should this call expression be treated as a string literal?
  1577. static bool IsStringLiteralCall(const CallExpr *E) {
  1578. unsigned Builtin = E->getBuiltinCallee();
  1579. return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
  1580. Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
  1581. }
  1582. static bool IsGlobalLValue(APValue::LValueBase B) {
  1583. // C++11 [expr.const]p3 An address constant expression is a prvalue core
  1584. // constant expression of pointer type that evaluates to...
  1585. // ... a null pointer value, or a prvalue core constant expression of type
  1586. // std::nullptr_t.
  1587. if (!B) return true;
  1588. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  1589. // ... the address of an object with static storage duration,
  1590. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1591. return VD->hasGlobalStorage();
  1592. // ... the address of a function,
  1593. return isa<FunctionDecl>(D);
  1594. }
  1595. if (B.is<TypeInfoLValue>())
  1596. return true;
  1597. const Expr *E = B.get<const Expr*>();
  1598. switch (E->getStmtClass()) {
  1599. default:
  1600. return false;
  1601. case Expr::CompoundLiteralExprClass: {
  1602. const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  1603. return CLE->isFileScope() && CLE->isLValue();
  1604. }
  1605. case Expr::MaterializeTemporaryExprClass:
  1606. // A materialized temporary might have been lifetime-extended to static
  1607. // storage duration.
  1608. return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
  1609. // A string literal has static storage duration.
  1610. case Expr::StringLiteralClass:
  1611. case Expr::PredefinedExprClass:
  1612. case Expr::ObjCStringLiteralClass:
  1613. case Expr::ObjCEncodeExprClass:
  1614. case Expr::CXXUuidofExprClass:
  1615. return true;
  1616. case Expr::ObjCBoxedExprClass:
  1617. return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
  1618. case Expr::CallExprClass:
  1619. return IsStringLiteralCall(cast<CallExpr>(E));
  1620. // For GCC compatibility, &&label has static storage duration.
  1621. case Expr::AddrLabelExprClass:
  1622. return true;
  1623. // A Block literal expression may be used as the initialization value for
  1624. // Block variables at global or local static scope.
  1625. case Expr::BlockExprClass:
  1626. return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
  1627. case Expr::ImplicitValueInitExprClass:
  1628. // FIXME:
  1629. // We can never form an lvalue with an implicit value initialization as its
  1630. // base through expression evaluation, so these only appear in one case: the
  1631. // implicit variable declaration we invent when checking whether a constexpr
  1632. // constructor can produce a constant expression. We must assume that such
  1633. // an expression might be a global lvalue.
  1634. return true;
  1635. }
  1636. }
  1637. static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
  1638. return LVal.Base.dyn_cast<const ValueDecl*>();
  1639. }
  1640. static bool IsLiteralLValue(const LValue &Value) {
  1641. if (Value.getLValueCallIndex())
  1642. return false;
  1643. const Expr *E = Value.Base.dyn_cast<const Expr*>();
  1644. return E && !isa<MaterializeTemporaryExpr>(E);
  1645. }
  1646. static bool IsWeakLValue(const LValue &Value) {
  1647. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1648. return Decl && Decl->isWeak();
  1649. }
  1650. static bool isZeroSized(const LValue &Value) {
  1651. const ValueDecl *Decl = GetLValueBaseDecl(Value);
  1652. if (Decl && isa<VarDecl>(Decl)) {
  1653. QualType Ty = Decl->getType();
  1654. if (Ty->isArrayType())
  1655. return Ty->isIncompleteType() ||
  1656. Decl->getASTContext().getTypeSize(Ty) == 0;
  1657. }
  1658. return false;
  1659. }
  1660. static bool HasSameBase(const LValue &A, const LValue &B) {
  1661. if (!A.getLValueBase())
  1662. return !B.getLValueBase();
  1663. if (!B.getLValueBase())
  1664. return false;
  1665. if (A.getLValueBase().getOpaqueValue() !=
  1666. B.getLValueBase().getOpaqueValue()) {
  1667. const Decl *ADecl = GetLValueBaseDecl(A);
  1668. if (!ADecl)
  1669. return false;
  1670. const Decl *BDecl = GetLValueBaseDecl(B);
  1671. if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
  1672. return false;
  1673. }
  1674. return IsGlobalLValue(A.getLValueBase()) ||
  1675. (A.getLValueCallIndex() == B.getLValueCallIndex() &&
  1676. A.getLValueVersion() == B.getLValueVersion());
  1677. }
  1678. static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
  1679. assert(Base && "no location for a null lvalue");
  1680. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1681. if (VD)
  1682. Info.Note(VD->getLocation(), diag::note_declared_at);
  1683. else if (const Expr *E = Base.dyn_cast<const Expr*>())
  1684. Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
  1685. // We have no information to show for a typeid(T) object.
  1686. }
  1687. /// Check that this reference or pointer core constant expression is a valid
  1688. /// value for an address or reference constant expression. Return true if we
  1689. /// can fold this expression, whether or not it's a constant expression.
  1690. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
  1691. QualType Type, const LValue &LVal,
  1692. Expr::ConstExprUsage Usage) {
  1693. bool IsReferenceType = Type->isReferenceType();
  1694. APValue::LValueBase Base = LVal.getLValueBase();
  1695. const SubobjectDesignator &Designator = LVal.getLValueDesignator();
  1696. // Check that the object is a global. Note that the fake 'this' object we
  1697. // manufacture when checking potential constant expressions is conservatively
  1698. // assumed to be global here.
  1699. if (!IsGlobalLValue(Base)) {
  1700. if (Info.getLangOpts().CPlusPlus11) {
  1701. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1702. Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
  1703. << IsReferenceType << !Designator.Entries.empty()
  1704. << !!VD << VD;
  1705. NoteLValueLocation(Info, Base);
  1706. } else {
  1707. Info.FFDiag(Loc);
  1708. }
  1709. // Don't allow references to temporaries to escape.
  1710. return false;
  1711. }
  1712. assert((Info.checkingPotentialConstantExpression() ||
  1713. LVal.getLValueCallIndex() == 0) &&
  1714. "have call index for global lvalue");
  1715. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  1716. if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
  1717. // Check if this is a thread-local variable.
  1718. if (Var->getTLSKind())
  1719. return false;
  1720. // A dllimport variable never acts like a constant.
  1721. if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
  1722. return false;
  1723. }
  1724. if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
  1725. // __declspec(dllimport) must be handled very carefully:
  1726. // We must never initialize an expression with the thunk in C++.
  1727. // Doing otherwise would allow the same id-expression to yield
  1728. // different addresses for the same function in different translation
  1729. // units. However, this means that we must dynamically initialize the
  1730. // expression with the contents of the import address table at runtime.
  1731. //
  1732. // The C language has no notion of ODR; furthermore, it has no notion of
  1733. // dynamic initialization. This means that we are permitted to
  1734. // perform initialization with the address of the thunk.
  1735. if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
  1736. FD->hasAttr<DLLImportAttr>())
  1737. return false;
  1738. }
  1739. }
  1740. // Allow address constant expressions to be past-the-end pointers. This is
  1741. // an extension: the standard requires them to point to an object.
  1742. if (!IsReferenceType)
  1743. return true;
  1744. // A reference constant expression must refer to an object.
  1745. if (!Base) {
  1746. // FIXME: diagnostic
  1747. Info.CCEDiag(Loc);
  1748. return true;
  1749. }
  1750. // Does this refer one past the end of some object?
  1751. if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
  1752. const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
  1753. Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
  1754. << !Designator.Entries.empty() << !!VD << VD;
  1755. NoteLValueLocation(Info, Base);
  1756. }
  1757. return true;
  1758. }
  1759. /// Member pointers are constant expressions unless they point to a
  1760. /// non-virtual dllimport member function.
  1761. static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
  1762. SourceLocation Loc,
  1763. QualType Type,
  1764. const APValue &Value,
  1765. Expr::ConstExprUsage Usage) {
  1766. const ValueDecl *Member = Value.getMemberPointerDecl();
  1767. const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
  1768. if (!FD)
  1769. return true;
  1770. return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
  1771. !FD->hasAttr<DLLImportAttr>();
  1772. }
  1773. /// Check that this core constant expression is of literal type, and if not,
  1774. /// produce an appropriate diagnostic.
  1775. static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
  1776. const LValue *This = nullptr) {
  1777. if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
  1778. return true;
  1779. // C++1y: A constant initializer for an object o [...] may also invoke
  1780. // constexpr constructors for o and its subobjects even if those objects
  1781. // are of non-literal class types.
  1782. //
  1783. // C++11 missed this detail for aggregates, so classes like this:
  1784. // struct foo_t { union { int i; volatile int j; } u; };
  1785. // are not (obviously) initializable like so:
  1786. // __attribute__((__require_constant_initialization__))
  1787. // static const foo_t x = {{0}};
  1788. // because "i" is a subobject with non-literal initialization (due to the
  1789. // volatile member of the union). See:
  1790. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
  1791. // Therefore, we use the C++1y behavior.
  1792. if (This && Info.EvaluatingDecl == This->getLValueBase())
  1793. return true;
  1794. // Prvalue constant expressions must be of literal types.
  1795. if (Info.getLangOpts().CPlusPlus11)
  1796. Info.FFDiag(E, diag::note_constexpr_nonliteral)
  1797. << E->getType();
  1798. else
  1799. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  1800. return false;
  1801. }
  1802. /// Check that this core constant expression value is a valid value for a
  1803. /// constant expression. If not, report an appropriate diagnostic. Does not
  1804. /// check that the expression is of literal type.
  1805. static bool
  1806. CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
  1807. const APValue &Value,
  1808. Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
  1809. SourceLocation SubobjectLoc = SourceLocation()) {
  1810. if (!Value.hasValue()) {
  1811. Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
  1812. << true << Type;
  1813. if (SubobjectLoc.isValid())
  1814. Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
  1815. return false;
  1816. }
  1817. // We allow _Atomic(T) to be initialized from anything that T can be
  1818. // initialized from.
  1819. if (const AtomicType *AT = Type->getAs<AtomicType>())
  1820. Type = AT->getValueType();
  1821. // Core issue 1454: For a literal constant expression of array or class type,
  1822. // each subobject of its value shall have been initialized by a constant
  1823. // expression.
  1824. if (Value.isArray()) {
  1825. QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
  1826. for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
  1827. if (!CheckConstantExpression(Info, DiagLoc, EltTy,
  1828. Value.getArrayInitializedElt(I), Usage,
  1829. SubobjectLoc))
  1830. return false;
  1831. }
  1832. if (!Value.hasArrayFiller())
  1833. return true;
  1834. return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
  1835. Usage, SubobjectLoc);
  1836. }
  1837. if (Value.isUnion() && Value.getUnionField()) {
  1838. return CheckConstantExpression(Info, DiagLoc,
  1839. Value.getUnionField()->getType(),
  1840. Value.getUnionValue(), Usage,
  1841. Value.getUnionField()->getLocation());
  1842. }
  1843. if (Value.isStruct()) {
  1844. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  1845. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  1846. unsigned BaseIndex = 0;
  1847. for (const CXXBaseSpecifier &BS : CD->bases()) {
  1848. if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
  1849. Value.getStructBase(BaseIndex), Usage,
  1850. BS.getBeginLoc()))
  1851. return false;
  1852. ++BaseIndex;
  1853. }
  1854. }
  1855. for (const auto *I : RD->fields()) {
  1856. if (I->isUnnamedBitfield())
  1857. continue;
  1858. if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
  1859. Value.getStructField(I->getFieldIndex()),
  1860. Usage, I->getLocation()))
  1861. return false;
  1862. }
  1863. }
  1864. if (Value.isLValue()) {
  1865. LValue LVal;
  1866. LVal.setFrom(Info.Ctx, Value);
  1867. return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
  1868. }
  1869. if (Value.isMemberPointer())
  1870. return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
  1871. // Everything else is fine.
  1872. return true;
  1873. }
  1874. static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
  1875. // A null base expression indicates a null pointer. These are always
  1876. // evaluatable, and they are false unless the offset is zero.
  1877. if (!Value.getLValueBase()) {
  1878. Result = !Value.getLValueOffset().isZero();
  1879. return true;
  1880. }
  1881. // We have a non-null base. These are generally known to be true, but if it's
  1882. // a weak declaration it can be null at runtime.
  1883. Result = true;
  1884. const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
  1885. return !Decl || !Decl->isWeak();
  1886. }
  1887. static bool HandleConversionToBool(const APValue &Val, bool &Result) {
  1888. switch (Val.getKind()) {
  1889. case APValue::None:
  1890. case APValue::Indeterminate:
  1891. return false;
  1892. case APValue::Int:
  1893. Result = Val.getInt().getBoolValue();
  1894. return true;
  1895. case APValue::FixedPoint:
  1896. Result = Val.getFixedPoint().getBoolValue();
  1897. return true;
  1898. case APValue::Float:
  1899. Result = !Val.getFloat().isZero();
  1900. return true;
  1901. case APValue::ComplexInt:
  1902. Result = Val.getComplexIntReal().getBoolValue() ||
  1903. Val.getComplexIntImag().getBoolValue();
  1904. return true;
  1905. case APValue::ComplexFloat:
  1906. Result = !Val.getComplexFloatReal().isZero() ||
  1907. !Val.getComplexFloatImag().isZero();
  1908. return true;
  1909. case APValue::LValue:
  1910. return EvalPointerValueAsBool(Val, Result);
  1911. case APValue::MemberPointer:
  1912. Result = Val.getMemberPointerDecl();
  1913. return true;
  1914. case APValue::Vector:
  1915. case APValue::Array:
  1916. case APValue::Struct:
  1917. case APValue::Union:
  1918. case APValue::AddrLabelDiff:
  1919. return false;
  1920. }
  1921. llvm_unreachable("unknown APValue kind");
  1922. }
  1923. static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
  1924. EvalInfo &Info) {
  1925. assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
  1926. APValue Val;
  1927. if (!Evaluate(Val, Info, E))
  1928. return false;
  1929. return HandleConversionToBool(Val, Result);
  1930. }
  1931. template<typename T>
  1932. static bool HandleOverflow(EvalInfo &Info, const Expr *E,
  1933. const T &SrcValue, QualType DestType) {
  1934. Info.CCEDiag(E, diag::note_constexpr_overflow)
  1935. << SrcValue << DestType;
  1936. return Info.noteUndefinedBehavior();
  1937. }
  1938. static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
  1939. QualType SrcType, const APFloat &Value,
  1940. QualType DestType, APSInt &Result) {
  1941. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1942. // Determine whether we are converting to unsigned or signed.
  1943. bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
  1944. Result = APSInt(DestWidth, !DestSigned);
  1945. bool ignored;
  1946. if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
  1947. & APFloat::opInvalidOp)
  1948. return HandleOverflow(Info, E, Value, DestType);
  1949. return true;
  1950. }
  1951. static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
  1952. QualType SrcType, QualType DestType,
  1953. APFloat &Result) {
  1954. APFloat Value = Result;
  1955. bool ignored;
  1956. if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
  1957. APFloat::rmNearestTiesToEven, &ignored)
  1958. & APFloat::opOverflow)
  1959. return HandleOverflow(Info, E, Value, DestType);
  1960. return true;
  1961. }
  1962. static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
  1963. QualType DestType, QualType SrcType,
  1964. const APSInt &Value) {
  1965. unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
  1966. // Figure out if this is a truncate, extend or noop cast.
  1967. // If the input is signed, do a sign extend, noop, or truncate.
  1968. APSInt Result = Value.extOrTrunc(DestWidth);
  1969. Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
  1970. if (DestType->isBooleanType())
  1971. Result = Value.getBoolValue();
  1972. return Result;
  1973. }
  1974. static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
  1975. QualType SrcType, const APSInt &Value,
  1976. QualType DestType, APFloat &Result) {
  1977. Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
  1978. if (Result.convertFromAPInt(Value, Value.isSigned(),
  1979. APFloat::rmNearestTiesToEven)
  1980. & APFloat::opOverflow)
  1981. return HandleOverflow(Info, E, Value, DestType);
  1982. return true;
  1983. }
  1984. static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
  1985. APValue &Value, const FieldDecl *FD) {
  1986. assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
  1987. if (!Value.isInt()) {
  1988. // Trying to store a pointer-cast-to-integer into a bitfield.
  1989. // FIXME: In this case, we should provide the diagnostic for casting
  1990. // a pointer to an integer.
  1991. assert(Value.isLValue() && "integral value neither int nor lvalue?");
  1992. Info.FFDiag(E);
  1993. return false;
  1994. }
  1995. APSInt &Int = Value.getInt();
  1996. unsigned OldBitWidth = Int.getBitWidth();
  1997. unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
  1998. if (NewBitWidth < OldBitWidth)
  1999. Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
  2000. return true;
  2001. }
  2002. static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
  2003. llvm::APInt &Res) {
  2004. APValue SVal;
  2005. if (!Evaluate(SVal, Info, E))
  2006. return false;
  2007. if (SVal.isInt()) {
  2008. Res = SVal.getInt();
  2009. return true;
  2010. }
  2011. if (SVal.isFloat()) {
  2012. Res = SVal.getFloat().bitcastToAPInt();
  2013. return true;
  2014. }
  2015. if (SVal.isVector()) {
  2016. QualType VecTy = E->getType();
  2017. unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
  2018. QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
  2019. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  2020. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  2021. Res = llvm::APInt::getNullValue(VecSize);
  2022. for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
  2023. APValue &Elt = SVal.getVectorElt(i);
  2024. llvm::APInt EltAsInt;
  2025. if (Elt.isInt()) {
  2026. EltAsInt = Elt.getInt();
  2027. } else if (Elt.isFloat()) {
  2028. EltAsInt = Elt.getFloat().bitcastToAPInt();
  2029. } else {
  2030. // Don't try to handle vectors of anything other than int or float
  2031. // (not sure if it's possible to hit this case).
  2032. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2033. return false;
  2034. }
  2035. unsigned BaseEltSize = EltAsInt.getBitWidth();
  2036. if (BigEndian)
  2037. Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
  2038. else
  2039. Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
  2040. }
  2041. return true;
  2042. }
  2043. // Give up if the input isn't an int, float, or vector. For example, we
  2044. // reject "(v4i16)(intptr_t)&a".
  2045. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2046. return false;
  2047. }
  2048. /// Perform the given integer operation, which is known to need at most BitWidth
  2049. /// bits, and check for overflow in the original type (if that type was not an
  2050. /// unsigned type).
  2051. template<typename Operation>
  2052. static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
  2053. const APSInt &LHS, const APSInt &RHS,
  2054. unsigned BitWidth, Operation Op,
  2055. APSInt &Result) {
  2056. if (LHS.isUnsigned()) {
  2057. Result = Op(LHS, RHS);
  2058. return true;
  2059. }
  2060. APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
  2061. Result = Value.trunc(LHS.getBitWidth());
  2062. if (Result.extend(BitWidth) != Value) {
  2063. if (Info.checkingForOverflow())
  2064. Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  2065. diag::warn_integer_constant_overflow)
  2066. << Result.toString(10) << E->getType();
  2067. else
  2068. return HandleOverflow(Info, E, Value, E->getType());
  2069. }
  2070. return true;
  2071. }
  2072. /// Perform the given binary integer operation.
  2073. static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
  2074. BinaryOperatorKind Opcode, APSInt RHS,
  2075. APSInt &Result) {
  2076. switch (Opcode) {
  2077. default:
  2078. Info.FFDiag(E);
  2079. return false;
  2080. case BO_Mul:
  2081. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
  2082. std::multiplies<APSInt>(), Result);
  2083. case BO_Add:
  2084. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2085. std::plus<APSInt>(), Result);
  2086. case BO_Sub:
  2087. return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
  2088. std::minus<APSInt>(), Result);
  2089. case BO_And: Result = LHS & RHS; return true;
  2090. case BO_Xor: Result = LHS ^ RHS; return true;
  2091. case BO_Or: Result = LHS | RHS; return true;
  2092. case BO_Div:
  2093. case BO_Rem:
  2094. if (RHS == 0) {
  2095. Info.FFDiag(E, diag::note_expr_divide_by_zero);
  2096. return false;
  2097. }
  2098. Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
  2099. // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
  2100. // this operation and gives the two's complement result.
  2101. if (RHS.isNegative() && RHS.isAllOnesValue() &&
  2102. LHS.isSigned() && LHS.isMinSignedValue())
  2103. return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
  2104. E->getType());
  2105. return true;
  2106. case BO_Shl: {
  2107. if (Info.getLangOpts().OpenCL)
  2108. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2109. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2110. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2111. RHS.isUnsigned());
  2112. else if (RHS.isSigned() && RHS.isNegative()) {
  2113. // During constant-folding, a negative shift is an opposite shift. Such
  2114. // a shift is not a constant expression.
  2115. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2116. RHS = -RHS;
  2117. goto shift_right;
  2118. }
  2119. shift_left:
  2120. // C++11 [expr.shift]p1: Shift width must be less than the bit width of
  2121. // the shifted type.
  2122. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2123. if (SA != RHS) {
  2124. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2125. << RHS << E->getType() << LHS.getBitWidth();
  2126. } else if (LHS.isSigned()) {
  2127. // C++11 [expr.shift]p2: A signed left shift must have a non-negative
  2128. // operand, and must not overflow the corresponding unsigned type.
  2129. if (LHS.isNegative())
  2130. Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
  2131. else if (LHS.countLeadingZeros() < SA)
  2132. Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
  2133. }
  2134. Result = LHS << SA;
  2135. return true;
  2136. }
  2137. case BO_Shr: {
  2138. if (Info.getLangOpts().OpenCL)
  2139. // OpenCL 6.3j: shift values are effectively % word size of LHS.
  2140. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
  2141. static_cast<uint64_t>(LHS.getBitWidth() - 1)),
  2142. RHS.isUnsigned());
  2143. else if (RHS.isSigned() && RHS.isNegative()) {
  2144. // During constant-folding, a negative shift is an opposite shift. Such a
  2145. // shift is not a constant expression.
  2146. Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
  2147. RHS = -RHS;
  2148. goto shift_left;
  2149. }
  2150. shift_right:
  2151. // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
  2152. // shifted type.
  2153. unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
  2154. if (SA != RHS)
  2155. Info.CCEDiag(E, diag::note_constexpr_large_shift)
  2156. << RHS << E->getType() << LHS.getBitWidth();
  2157. Result = LHS >> SA;
  2158. return true;
  2159. }
  2160. case BO_LT: Result = LHS < RHS; return true;
  2161. case BO_GT: Result = LHS > RHS; return true;
  2162. case BO_LE: Result = LHS <= RHS; return true;
  2163. case BO_GE: Result = LHS >= RHS; return true;
  2164. case BO_EQ: Result = LHS == RHS; return true;
  2165. case BO_NE: Result = LHS != RHS; return true;
  2166. case BO_Cmp:
  2167. llvm_unreachable("BO_Cmp should be handled elsewhere");
  2168. }
  2169. }
  2170. /// Perform the given binary floating-point operation, in-place, on LHS.
  2171. static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
  2172. APFloat &LHS, BinaryOperatorKind Opcode,
  2173. const APFloat &RHS) {
  2174. switch (Opcode) {
  2175. default:
  2176. Info.FFDiag(E);
  2177. return false;
  2178. case BO_Mul:
  2179. LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
  2180. break;
  2181. case BO_Add:
  2182. LHS.add(RHS, APFloat::rmNearestTiesToEven);
  2183. break;
  2184. case BO_Sub:
  2185. LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
  2186. break;
  2187. case BO_Div:
  2188. LHS.divide(RHS, APFloat::rmNearestTiesToEven);
  2189. break;
  2190. }
  2191. if (LHS.isInfinity() || LHS.isNaN()) {
  2192. Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
  2193. return Info.noteUndefinedBehavior();
  2194. }
  2195. return true;
  2196. }
  2197. /// Cast an lvalue referring to a base subobject to a derived class, by
  2198. /// truncating the lvalue's path to the given length.
  2199. static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2200. const RecordDecl *TruncatedType,
  2201. unsigned TruncatedElements) {
  2202. SubobjectDesignator &D = Result.Designator;
  2203. // Check we actually point to a derived class object.
  2204. if (TruncatedElements == D.Entries.size())
  2205. return true;
  2206. assert(TruncatedElements >= D.MostDerivedPathLength &&
  2207. "not casting to a derived class");
  2208. if (!Result.checkSubobject(Info, E, CSK_Derived))
  2209. return false;
  2210. // Truncate the path to the subobject, and remove any derived-to-base offsets.
  2211. const RecordDecl *RD = TruncatedType;
  2212. for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
  2213. if (RD->isInvalidDecl()) return false;
  2214. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  2215. const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
  2216. if (isVirtualBaseClass(D.Entries[I]))
  2217. Result.Offset -= Layout.getVBaseClassOffset(Base);
  2218. else
  2219. Result.Offset -= Layout.getBaseClassOffset(Base);
  2220. RD = Base;
  2221. }
  2222. D.Entries.resize(TruncatedElements);
  2223. return true;
  2224. }
  2225. static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2226. const CXXRecordDecl *Derived,
  2227. const CXXRecordDecl *Base,
  2228. const ASTRecordLayout *RL = nullptr) {
  2229. if (!RL) {
  2230. if (Derived->isInvalidDecl()) return false;
  2231. RL = &Info.Ctx.getASTRecordLayout(Derived);
  2232. }
  2233. Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
  2234. Obj.addDecl(Info, E, Base, /*Virtual*/ false);
  2235. return true;
  2236. }
  2237. static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
  2238. const CXXRecordDecl *DerivedDecl,
  2239. const CXXBaseSpecifier *Base) {
  2240. const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
  2241. if (!Base->isVirtual())
  2242. return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
  2243. SubobjectDesignator &D = Obj.Designator;
  2244. if (D.Invalid)
  2245. return false;
  2246. // Extract most-derived object and corresponding type.
  2247. DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
  2248. if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
  2249. return false;
  2250. // Find the virtual base class.
  2251. if (DerivedDecl->isInvalidDecl()) return false;
  2252. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
  2253. Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
  2254. Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
  2255. return true;
  2256. }
  2257. static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
  2258. QualType Type, LValue &Result) {
  2259. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  2260. PathE = E->path_end();
  2261. PathI != PathE; ++PathI) {
  2262. if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
  2263. *PathI))
  2264. return false;
  2265. Type = (*PathI)->getType();
  2266. }
  2267. return true;
  2268. }
  2269. /// Cast an lvalue referring to a derived class to a known base subobject.
  2270. static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
  2271. const CXXRecordDecl *DerivedRD,
  2272. const CXXRecordDecl *BaseRD) {
  2273. CXXBasePaths Paths(/*FindAmbiguities=*/false,
  2274. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  2275. if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
  2276. llvm_unreachable("Class must be derived from the passed in base class!");
  2277. for (CXXBasePathElement &Elem : Paths.front())
  2278. if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
  2279. return false;
  2280. return true;
  2281. }
  2282. /// Update LVal to refer to the given field, which must be a member of the type
  2283. /// currently described by LVal.
  2284. static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
  2285. const FieldDecl *FD,
  2286. const ASTRecordLayout *RL = nullptr) {
  2287. if (!RL) {
  2288. if (FD->getParent()->isInvalidDecl()) return false;
  2289. RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
  2290. }
  2291. unsigned I = FD->getFieldIndex();
  2292. LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
  2293. LVal.addDecl(Info, E, FD);
  2294. return true;
  2295. }
  2296. /// Update LVal to refer to the given indirect field.
  2297. static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
  2298. LValue &LVal,
  2299. const IndirectFieldDecl *IFD) {
  2300. for (const auto *C : IFD->chain())
  2301. if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
  2302. return false;
  2303. return true;
  2304. }
  2305. /// Get the size of the given type in char units.
  2306. static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
  2307. QualType Type, CharUnits &Size) {
  2308. // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
  2309. // extension.
  2310. if (Type->isVoidType() || Type->isFunctionType()) {
  2311. Size = CharUnits::One();
  2312. return true;
  2313. }
  2314. if (Type->isDependentType()) {
  2315. Info.FFDiag(Loc);
  2316. return false;
  2317. }
  2318. if (!Type->isConstantSizeType()) {
  2319. // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
  2320. // FIXME: Better diagnostic.
  2321. Info.FFDiag(Loc);
  2322. return false;
  2323. }
  2324. Size = Info.Ctx.getTypeSizeInChars(Type);
  2325. return true;
  2326. }
  2327. /// Update a pointer value to model pointer arithmetic.
  2328. /// \param Info - Information about the ongoing evaluation.
  2329. /// \param E - The expression being evaluated, for diagnostic purposes.
  2330. /// \param LVal - The pointer value to be updated.
  2331. /// \param EltTy - The pointee type represented by LVal.
  2332. /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
  2333. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2334. LValue &LVal, QualType EltTy,
  2335. APSInt Adjustment) {
  2336. CharUnits SizeOfPointee;
  2337. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
  2338. return false;
  2339. LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
  2340. return true;
  2341. }
  2342. static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
  2343. LValue &LVal, QualType EltTy,
  2344. int64_t Adjustment) {
  2345. return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
  2346. APSInt::get(Adjustment));
  2347. }
  2348. /// Update an lvalue to refer to a component of a complex number.
  2349. /// \param Info - Information about the ongoing evaluation.
  2350. /// \param LVal - The lvalue to be updated.
  2351. /// \param EltTy - The complex number's component type.
  2352. /// \param Imag - False for the real component, true for the imaginary.
  2353. static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
  2354. LValue &LVal, QualType EltTy,
  2355. bool Imag) {
  2356. if (Imag) {
  2357. CharUnits SizeOfComponent;
  2358. if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
  2359. return false;
  2360. LVal.Offset += SizeOfComponent;
  2361. }
  2362. LVal.addComplex(Info, E, EltTy, Imag);
  2363. return true;
  2364. }
  2365. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  2366. QualType Type, const LValue &LVal,
  2367. APValue &RVal);
  2368. /// Try to evaluate the initializer for a variable declaration.
  2369. ///
  2370. /// \param Info Information about the ongoing evaluation.
  2371. /// \param E An expression to be used when printing diagnostics.
  2372. /// \param VD The variable whose initializer should be obtained.
  2373. /// \param Frame The frame in which the variable was created. Must be null
  2374. /// if this variable is not local to the evaluation.
  2375. /// \param Result Filled in with a pointer to the value of the variable.
  2376. static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
  2377. const VarDecl *VD, CallStackFrame *Frame,
  2378. APValue *&Result, const LValue *LVal) {
  2379. // If this is a parameter to an active constexpr function call, perform
  2380. // argument substitution.
  2381. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
  2382. // Assume arguments of a potential constant expression are unknown
  2383. // constant expressions.
  2384. if (Info.checkingPotentialConstantExpression())
  2385. return false;
  2386. if (!Frame || !Frame->Arguments) {
  2387. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2388. return false;
  2389. }
  2390. Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
  2391. return true;
  2392. }
  2393. // If this is a local variable, dig out its value.
  2394. if (Frame) {
  2395. Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
  2396. : Frame->getCurrentTemporary(VD);
  2397. if (!Result) {
  2398. // Assume variables referenced within a lambda's call operator that were
  2399. // not declared within the call operator are captures and during checking
  2400. // of a potential constant expression, assume they are unknown constant
  2401. // expressions.
  2402. assert(isLambdaCallOperator(Frame->Callee) &&
  2403. (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
  2404. "missing value for local variable");
  2405. if (Info.checkingPotentialConstantExpression())
  2406. return false;
  2407. // FIXME: implement capture evaluation during constant expr evaluation.
  2408. Info.FFDiag(E->getBeginLoc(),
  2409. diag::note_unimplemented_constexpr_lambda_feature_ast)
  2410. << "captures not currently allowed";
  2411. return false;
  2412. }
  2413. return true;
  2414. }
  2415. // Dig out the initializer, and use the declaration which it's attached to.
  2416. const Expr *Init = VD->getAnyInitializer(VD);
  2417. if (!Init || Init->isValueDependent()) {
  2418. // If we're checking a potential constant expression, the variable could be
  2419. // initialized later.
  2420. if (!Info.checkingPotentialConstantExpression())
  2421. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2422. return false;
  2423. }
  2424. // If we're currently evaluating the initializer of this declaration, use that
  2425. // in-flight value.
  2426. if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
  2427. Result = Info.EvaluatingDeclValue;
  2428. return true;
  2429. }
  2430. // Never evaluate the initializer of a weak variable. We can't be sure that
  2431. // this is the definition which will be used.
  2432. if (VD->isWeak()) {
  2433. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2434. return false;
  2435. }
  2436. // Check that we can fold the initializer. In C++, we will have already done
  2437. // this in the cases where it matters for conformance.
  2438. SmallVector<PartialDiagnosticAt, 8> Notes;
  2439. if (!VD->evaluateValue(Notes)) {
  2440. Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
  2441. Notes.size() + 1) << VD;
  2442. Info.Note(VD->getLocation(), diag::note_declared_at);
  2443. Info.addNotes(Notes);
  2444. return false;
  2445. } else if (!VD->checkInitIsICE()) {
  2446. Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
  2447. Notes.size() + 1) << VD;
  2448. Info.Note(VD->getLocation(), diag::note_declared_at);
  2449. Info.addNotes(Notes);
  2450. }
  2451. Result = VD->getEvaluatedValue();
  2452. return true;
  2453. }
  2454. static bool IsConstNonVolatile(QualType T) {
  2455. Qualifiers Quals = T.getQualifiers();
  2456. return Quals.hasConst() && !Quals.hasVolatile();
  2457. }
  2458. /// Get the base index of the given base class within an APValue representing
  2459. /// the given derived class.
  2460. static unsigned getBaseIndex(const CXXRecordDecl *Derived,
  2461. const CXXRecordDecl *Base) {
  2462. Base = Base->getCanonicalDecl();
  2463. unsigned Index = 0;
  2464. for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
  2465. E = Derived->bases_end(); I != E; ++I, ++Index) {
  2466. if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
  2467. return Index;
  2468. }
  2469. llvm_unreachable("base class missing from derived class's bases list");
  2470. }
  2471. /// Extract the value of a character from a string literal.
  2472. static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
  2473. uint64_t Index) {
  2474. assert(!isa<SourceLocExpr>(Lit) &&
  2475. "SourceLocExpr should have already been converted to a StringLiteral");
  2476. // FIXME: Support MakeStringConstant
  2477. if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
  2478. std::string Str;
  2479. Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
  2480. assert(Index <= Str.size() && "Index too large");
  2481. return APSInt::getUnsigned(Str.c_str()[Index]);
  2482. }
  2483. if (auto PE = dyn_cast<PredefinedExpr>(Lit))
  2484. Lit = PE->getFunctionName();
  2485. const StringLiteral *S = cast<StringLiteral>(Lit);
  2486. const ConstantArrayType *CAT =
  2487. Info.Ctx.getAsConstantArrayType(S->getType());
  2488. assert(CAT && "string literal isn't an array");
  2489. QualType CharType = CAT->getElementType();
  2490. assert(CharType->isIntegerType() && "unexpected character type");
  2491. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2492. CharType->isUnsignedIntegerType());
  2493. if (Index < S->getLength())
  2494. Value = S->getCodeUnit(Index);
  2495. return Value;
  2496. }
  2497. // Expand a string literal into an array of characters.
  2498. //
  2499. // FIXME: This is inefficient; we should probably introduce something similar
  2500. // to the LLVM ConstantDataArray to make this cheaper.
  2501. static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
  2502. APValue &Result) {
  2503. const ConstantArrayType *CAT =
  2504. Info.Ctx.getAsConstantArrayType(S->getType());
  2505. assert(CAT && "string literal isn't an array");
  2506. QualType CharType = CAT->getElementType();
  2507. assert(CharType->isIntegerType() && "unexpected character type");
  2508. unsigned Elts = CAT->getSize().getZExtValue();
  2509. Result = APValue(APValue::UninitArray(),
  2510. std::min(S->getLength(), Elts), Elts);
  2511. APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
  2512. CharType->isUnsignedIntegerType());
  2513. if (Result.hasArrayFiller())
  2514. Result.getArrayFiller() = APValue(Value);
  2515. for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
  2516. Value = S->getCodeUnit(I);
  2517. Result.getArrayInitializedElt(I) = APValue(Value);
  2518. }
  2519. }
  2520. // Expand an array so that it has more than Index filled elements.
  2521. static void expandArray(APValue &Array, unsigned Index) {
  2522. unsigned Size = Array.getArraySize();
  2523. assert(Index < Size);
  2524. // Always at least double the number of elements for which we store a value.
  2525. unsigned OldElts = Array.getArrayInitializedElts();
  2526. unsigned NewElts = std::max(Index+1, OldElts * 2);
  2527. NewElts = std::min(Size, std::max(NewElts, 8u));
  2528. // Copy the data across.
  2529. APValue NewValue(APValue::UninitArray(), NewElts, Size);
  2530. for (unsigned I = 0; I != OldElts; ++I)
  2531. NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
  2532. for (unsigned I = OldElts; I != NewElts; ++I)
  2533. NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
  2534. if (NewValue.hasArrayFiller())
  2535. NewValue.getArrayFiller() = Array.getArrayFiller();
  2536. Array.swap(NewValue);
  2537. }
  2538. /// Determine whether a type would actually be read by an lvalue-to-rvalue
  2539. /// conversion. If it's of class type, we may assume that the copy operation
  2540. /// is trivial. Note that this is never true for a union type with fields
  2541. /// (because the copy always "reads" the active member) and always true for
  2542. /// a non-class type.
  2543. static bool isReadByLvalueToRvalueConversion(QualType T) {
  2544. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2545. if (!RD || (RD->isUnion() && !RD->field_empty()))
  2546. return true;
  2547. if (RD->isEmpty())
  2548. return false;
  2549. for (auto *Field : RD->fields())
  2550. if (isReadByLvalueToRvalueConversion(Field->getType()))
  2551. return true;
  2552. for (auto &BaseSpec : RD->bases())
  2553. if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
  2554. return true;
  2555. return false;
  2556. }
  2557. /// Diagnose an attempt to read from any unreadable field within the specified
  2558. /// type, which might be a class type.
  2559. static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
  2560. QualType T) {
  2561. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2562. if (!RD)
  2563. return false;
  2564. if (!RD->hasMutableFields())
  2565. return false;
  2566. for (auto *Field : RD->fields()) {
  2567. // If we're actually going to read this field in some way, then it can't
  2568. // be mutable. If we're in a union, then assigning to a mutable field
  2569. // (even an empty one) can change the active member, so that's not OK.
  2570. // FIXME: Add core issue number for the union case.
  2571. if (Field->isMutable() &&
  2572. (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
  2573. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
  2574. Info.Note(Field->getLocation(), diag::note_declared_at);
  2575. return true;
  2576. }
  2577. if (diagnoseUnreadableFields(Info, E, Field->getType()))
  2578. return true;
  2579. }
  2580. for (auto &BaseSpec : RD->bases())
  2581. if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
  2582. return true;
  2583. // All mutable fields were empty, and thus not actually read.
  2584. return false;
  2585. }
  2586. static bool lifetimeStartedInEvaluation(EvalInfo &Info,
  2587. APValue::LValueBase Base) {
  2588. // A temporary we created.
  2589. if (Base.getCallIndex())
  2590. return true;
  2591. auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  2592. if (!Evaluating)
  2593. return false;
  2594. // The variable whose initializer we're evaluating.
  2595. if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
  2596. if (declaresSameEntity(Evaluating, BaseD))
  2597. return true;
  2598. // A temporary lifetime-extended by the variable whose initializer we're
  2599. // evaluating.
  2600. if (auto *BaseE = Base.dyn_cast<const Expr *>())
  2601. if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
  2602. if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
  2603. return true;
  2604. return false;
  2605. }
  2606. namespace {
  2607. /// A handle to a complete object (an object that is not a subobject of
  2608. /// another object).
  2609. struct CompleteObject {
  2610. /// The identity of the object.
  2611. APValue::LValueBase Base;
  2612. /// The value of the complete object.
  2613. APValue *Value;
  2614. /// The type of the complete object.
  2615. QualType Type;
  2616. CompleteObject() : Value(nullptr) {}
  2617. CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
  2618. : Base(Base), Value(Value), Type(Type) {}
  2619. bool mayReadMutableMembers(EvalInfo &Info) const {
  2620. // In C++14 onwards, it is permitted to read a mutable member whose
  2621. // lifetime began within the evaluation.
  2622. // FIXME: Should we also allow this in C++11?
  2623. if (!Info.getLangOpts().CPlusPlus14)
  2624. return false;
  2625. return lifetimeStartedInEvaluation(Info, Base);
  2626. }
  2627. explicit operator bool() const { return !Type.isNull(); }
  2628. };
  2629. } // end anonymous namespace
  2630. static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
  2631. bool IsMutable = false) {
  2632. // C++ [basic.type.qualifier]p1:
  2633. // - A const object is an object of type const T or a non-mutable subobject
  2634. // of a const object.
  2635. if (ObjType.isConstQualified() && !IsMutable)
  2636. SubobjType.addConst();
  2637. // - A volatile object is an object of type const T or a subobject of a
  2638. // volatile object.
  2639. if (ObjType.isVolatileQualified())
  2640. SubobjType.addVolatile();
  2641. return SubobjType;
  2642. }
  2643. /// Find the designated sub-object of an rvalue.
  2644. template<typename SubobjectHandler>
  2645. typename SubobjectHandler::result_type
  2646. findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
  2647. const SubobjectDesignator &Sub, SubobjectHandler &handler) {
  2648. if (Sub.Invalid)
  2649. // A diagnostic will have already been produced.
  2650. return handler.failed();
  2651. if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
  2652. if (Info.getLangOpts().CPlusPlus11)
  2653. Info.FFDiag(E, Sub.isOnePastTheEnd()
  2654. ? diag::note_constexpr_access_past_end
  2655. : diag::note_constexpr_access_unsized_array)
  2656. << handler.AccessKind;
  2657. else
  2658. Info.FFDiag(E);
  2659. return handler.failed();
  2660. }
  2661. APValue *O = Obj.Value;
  2662. QualType ObjType = Obj.Type;
  2663. const FieldDecl *LastField = nullptr;
  2664. const FieldDecl *VolatileField = nullptr;
  2665. // Walk the designator's path to find the subobject.
  2666. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
  2667. // Reading an indeterminate value is undefined, but assigning over one is OK.
  2668. if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
  2669. if (!Info.checkingPotentialConstantExpression())
  2670. Info.FFDiag(E, diag::note_constexpr_access_uninit)
  2671. << handler.AccessKind << O->isIndeterminate();
  2672. return handler.failed();
  2673. }
  2674. // C++ [class.ctor]p5:
  2675. // const and volatile semantics are not applied on an object under
  2676. // construction.
  2677. if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
  2678. ObjType->isRecordType() &&
  2679. Info.isEvaluatingConstructor(
  2680. Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
  2681. Sub.Entries.begin() + I)) !=
  2682. ConstructionPhase::None) {
  2683. ObjType = Info.Ctx.getCanonicalType(ObjType);
  2684. ObjType.removeLocalConst();
  2685. ObjType.removeLocalVolatile();
  2686. }
  2687. // If this is our last pass, check that the final object type is OK.
  2688. if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
  2689. // Accesses to volatile objects are prohibited.
  2690. if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
  2691. if (Info.getLangOpts().CPlusPlus) {
  2692. int DiagKind;
  2693. SourceLocation Loc;
  2694. const NamedDecl *Decl = nullptr;
  2695. if (VolatileField) {
  2696. DiagKind = 2;
  2697. Loc = VolatileField->getLocation();
  2698. Decl = VolatileField;
  2699. } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
  2700. DiagKind = 1;
  2701. Loc = VD->getLocation();
  2702. Decl = VD;
  2703. } else {
  2704. DiagKind = 0;
  2705. if (auto *E = Obj.Base.dyn_cast<const Expr *>())
  2706. Loc = E->getExprLoc();
  2707. }
  2708. Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
  2709. << handler.AccessKind << DiagKind << Decl;
  2710. Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
  2711. } else {
  2712. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  2713. }
  2714. return handler.failed();
  2715. }
  2716. // If we are reading an object of class type, there may still be more
  2717. // things we need to check: if there are any mutable subobjects, we
  2718. // cannot perform this read. (This only happens when performing a trivial
  2719. // copy or assignment.)
  2720. if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
  2721. !Obj.mayReadMutableMembers(Info) &&
  2722. diagnoseUnreadableFields(Info, E, ObjType))
  2723. return handler.failed();
  2724. }
  2725. if (I == N) {
  2726. if (!handler.found(*O, ObjType))
  2727. return false;
  2728. // If we modified a bit-field, truncate it to the right width.
  2729. if (isModification(handler.AccessKind) &&
  2730. LastField && LastField->isBitField() &&
  2731. !truncateBitfieldValue(Info, E, *O, LastField))
  2732. return false;
  2733. return true;
  2734. }
  2735. LastField = nullptr;
  2736. if (ObjType->isArrayType()) {
  2737. // Next subobject is an array element.
  2738. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
  2739. assert(CAT && "vla in literal type?");
  2740. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2741. if (CAT->getSize().ule(Index)) {
  2742. // Note, it should not be possible to form a pointer with a valid
  2743. // designator which points more than one past the end of the array.
  2744. if (Info.getLangOpts().CPlusPlus11)
  2745. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2746. << handler.AccessKind;
  2747. else
  2748. Info.FFDiag(E);
  2749. return handler.failed();
  2750. }
  2751. ObjType = CAT->getElementType();
  2752. if (O->getArrayInitializedElts() > Index)
  2753. O = &O->getArrayInitializedElt(Index);
  2754. else if (handler.AccessKind != AK_Read) {
  2755. expandArray(*O, Index);
  2756. O = &O->getArrayInitializedElt(Index);
  2757. } else
  2758. O = &O->getArrayFiller();
  2759. } else if (ObjType->isAnyComplexType()) {
  2760. // Next subobject is a complex number.
  2761. uint64_t Index = Sub.Entries[I].getAsArrayIndex();
  2762. if (Index > 1) {
  2763. if (Info.getLangOpts().CPlusPlus11)
  2764. Info.FFDiag(E, diag::note_constexpr_access_past_end)
  2765. << handler.AccessKind;
  2766. else
  2767. Info.FFDiag(E);
  2768. return handler.failed();
  2769. }
  2770. ObjType = getSubobjectType(
  2771. ObjType, ObjType->castAs<ComplexType>()->getElementType());
  2772. assert(I == N - 1 && "extracting subobject of scalar?");
  2773. if (O->isComplexInt()) {
  2774. return handler.found(Index ? O->getComplexIntImag()
  2775. : O->getComplexIntReal(), ObjType);
  2776. } else {
  2777. assert(O->isComplexFloat());
  2778. return handler.found(Index ? O->getComplexFloatImag()
  2779. : O->getComplexFloatReal(), ObjType);
  2780. }
  2781. } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
  2782. if (Field->isMutable() && handler.AccessKind == AK_Read &&
  2783. !Obj.mayReadMutableMembers(Info)) {
  2784. Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
  2785. << Field;
  2786. Info.Note(Field->getLocation(), diag::note_declared_at);
  2787. return handler.failed();
  2788. }
  2789. // Next subobject is a class, struct or union field.
  2790. RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
  2791. if (RD->isUnion()) {
  2792. const FieldDecl *UnionField = O->getUnionField();
  2793. if (!UnionField ||
  2794. UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
  2795. Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
  2796. << handler.AccessKind << Field << !UnionField << UnionField;
  2797. return handler.failed();
  2798. }
  2799. O = &O->getUnionValue();
  2800. } else
  2801. O = &O->getStructField(Field->getFieldIndex());
  2802. ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
  2803. LastField = Field;
  2804. if (Field->getType().isVolatileQualified())
  2805. VolatileField = Field;
  2806. } else {
  2807. // Next subobject is a base class.
  2808. const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
  2809. const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
  2810. O = &O->getStructBase(getBaseIndex(Derived, Base));
  2811. ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
  2812. }
  2813. }
  2814. }
  2815. namespace {
  2816. struct ExtractSubobjectHandler {
  2817. EvalInfo &Info;
  2818. APValue &Result;
  2819. static const AccessKinds AccessKind = AK_Read;
  2820. typedef bool result_type;
  2821. bool failed() { return false; }
  2822. bool found(APValue &Subobj, QualType SubobjType) {
  2823. Result = Subobj;
  2824. return true;
  2825. }
  2826. bool found(APSInt &Value, QualType SubobjType) {
  2827. Result = APValue(Value);
  2828. return true;
  2829. }
  2830. bool found(APFloat &Value, QualType SubobjType) {
  2831. Result = APValue(Value);
  2832. return true;
  2833. }
  2834. };
  2835. } // end anonymous namespace
  2836. const AccessKinds ExtractSubobjectHandler::AccessKind;
  2837. /// Extract the designated sub-object of an rvalue.
  2838. static bool extractSubobject(EvalInfo &Info, const Expr *E,
  2839. const CompleteObject &Obj,
  2840. const SubobjectDesignator &Sub,
  2841. APValue &Result) {
  2842. ExtractSubobjectHandler Handler = { Info, Result };
  2843. return findSubobject(Info, E, Obj, Sub, Handler);
  2844. }
  2845. namespace {
  2846. struct ModifySubobjectHandler {
  2847. EvalInfo &Info;
  2848. APValue &NewVal;
  2849. const Expr *E;
  2850. typedef bool result_type;
  2851. static const AccessKinds AccessKind = AK_Assign;
  2852. bool checkConst(QualType QT) {
  2853. // Assigning to a const object has undefined behavior.
  2854. if (QT.isConstQualified()) {
  2855. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  2856. return false;
  2857. }
  2858. return true;
  2859. }
  2860. bool failed() { return false; }
  2861. bool found(APValue &Subobj, QualType SubobjType) {
  2862. if (!checkConst(SubobjType))
  2863. return false;
  2864. // We've been given ownership of NewVal, so just swap it in.
  2865. Subobj.swap(NewVal);
  2866. return true;
  2867. }
  2868. bool found(APSInt &Value, QualType SubobjType) {
  2869. if (!checkConst(SubobjType))
  2870. return false;
  2871. if (!NewVal.isInt()) {
  2872. // Maybe trying to write a cast pointer value into a complex?
  2873. Info.FFDiag(E);
  2874. return false;
  2875. }
  2876. Value = NewVal.getInt();
  2877. return true;
  2878. }
  2879. bool found(APFloat &Value, QualType SubobjType) {
  2880. if (!checkConst(SubobjType))
  2881. return false;
  2882. Value = NewVal.getFloat();
  2883. return true;
  2884. }
  2885. };
  2886. } // end anonymous namespace
  2887. const AccessKinds ModifySubobjectHandler::AccessKind;
  2888. /// Update the designated sub-object of an rvalue to the given value.
  2889. static bool modifySubobject(EvalInfo &Info, const Expr *E,
  2890. const CompleteObject &Obj,
  2891. const SubobjectDesignator &Sub,
  2892. APValue &NewVal) {
  2893. ModifySubobjectHandler Handler = { Info, NewVal, E };
  2894. return findSubobject(Info, E, Obj, Sub, Handler);
  2895. }
  2896. /// Find the position where two subobject designators diverge, or equivalently
  2897. /// the length of the common initial subsequence.
  2898. static unsigned FindDesignatorMismatch(QualType ObjType,
  2899. const SubobjectDesignator &A,
  2900. const SubobjectDesignator &B,
  2901. bool &WasArrayIndex) {
  2902. unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
  2903. for (/**/; I != N; ++I) {
  2904. if (!ObjType.isNull() &&
  2905. (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
  2906. // Next subobject is an array element.
  2907. if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
  2908. WasArrayIndex = true;
  2909. return I;
  2910. }
  2911. if (ObjType->isAnyComplexType())
  2912. ObjType = ObjType->castAs<ComplexType>()->getElementType();
  2913. else
  2914. ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
  2915. } else {
  2916. if (A.Entries[I].getAsBaseOrMember() !=
  2917. B.Entries[I].getAsBaseOrMember()) {
  2918. WasArrayIndex = false;
  2919. return I;
  2920. }
  2921. if (const FieldDecl *FD = getAsField(A.Entries[I]))
  2922. // Next subobject is a field.
  2923. ObjType = FD->getType();
  2924. else
  2925. // Next subobject is a base class.
  2926. ObjType = QualType();
  2927. }
  2928. }
  2929. WasArrayIndex = false;
  2930. return I;
  2931. }
  2932. /// Determine whether the given subobject designators refer to elements of the
  2933. /// same array object.
  2934. static bool AreElementsOfSameArray(QualType ObjType,
  2935. const SubobjectDesignator &A,
  2936. const SubobjectDesignator &B) {
  2937. if (A.Entries.size() != B.Entries.size())
  2938. return false;
  2939. bool IsArray = A.MostDerivedIsArrayElement;
  2940. if (IsArray && A.MostDerivedPathLength != A.Entries.size())
  2941. // A is a subobject of the array element.
  2942. return false;
  2943. // If A (and B) designates an array element, the last entry will be the array
  2944. // index. That doesn't have to match. Otherwise, we're in the 'implicit array
  2945. // of length 1' case, and the entire path must match.
  2946. bool WasArrayIndex;
  2947. unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
  2948. return CommonLength >= A.Entries.size() - IsArray;
  2949. }
  2950. /// Find the complete object to which an LValue refers.
  2951. static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
  2952. AccessKinds AK, const LValue &LVal,
  2953. QualType LValType) {
  2954. if (LVal.InvalidBase) {
  2955. Info.FFDiag(E);
  2956. return CompleteObject();
  2957. }
  2958. if (!LVal.Base) {
  2959. Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
  2960. return CompleteObject();
  2961. }
  2962. CallStackFrame *Frame = nullptr;
  2963. unsigned Depth = 0;
  2964. if (LVal.getLValueCallIndex()) {
  2965. std::tie(Frame, Depth) =
  2966. Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
  2967. if (!Frame) {
  2968. Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
  2969. << AK << LVal.Base.is<const ValueDecl*>();
  2970. NoteLValueLocation(Info, LVal.Base);
  2971. return CompleteObject();
  2972. }
  2973. }
  2974. bool IsAccess = isFormalAccess(AK);
  2975. // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
  2976. // is not a constant expression (even if the object is non-volatile). We also
  2977. // apply this rule to C++98, in order to conform to the expected 'volatile'
  2978. // semantics.
  2979. if (IsAccess && LValType.isVolatileQualified()) {
  2980. if (Info.getLangOpts().CPlusPlus)
  2981. Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
  2982. << AK << LValType;
  2983. else
  2984. Info.FFDiag(E);
  2985. return CompleteObject();
  2986. }
  2987. // Compute value storage location and type of base object.
  2988. APValue *BaseVal = nullptr;
  2989. QualType BaseType = getType(LVal.Base);
  2990. if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
  2991. // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
  2992. // In C++11, constexpr, non-volatile variables initialized with constant
  2993. // expressions are constant expressions too. Inside constexpr functions,
  2994. // parameters are constant expressions even if they're non-const.
  2995. // In C++1y, objects local to a constant expression (those with a Frame) are
  2996. // both readable and writable inside constant expressions.
  2997. // In C, such things can also be folded, although they are not ICEs.
  2998. const VarDecl *VD = dyn_cast<VarDecl>(D);
  2999. if (VD) {
  3000. if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
  3001. VD = VDef;
  3002. }
  3003. if (!VD || VD->isInvalidDecl()) {
  3004. Info.FFDiag(E);
  3005. return CompleteObject();
  3006. }
  3007. // Unless we're looking at a local variable or argument in a constexpr call,
  3008. // the variable we're reading must be const.
  3009. if (!Frame) {
  3010. if (Info.getLangOpts().CPlusPlus14 &&
  3011. declaresSameEntity(
  3012. VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
  3013. // OK, we can read and modify an object if we're in the process of
  3014. // evaluating its initializer, because its lifetime began in this
  3015. // evaluation.
  3016. } else if (isModification(AK)) {
  3017. // All the remaining cases do not permit modification of the object.
  3018. Info.FFDiag(E, diag::note_constexpr_modify_global);
  3019. return CompleteObject();
  3020. } else if (VD->isConstexpr()) {
  3021. // OK, we can read this variable.
  3022. } else if (BaseType->isIntegralOrEnumerationType()) {
  3023. // In OpenCL if a variable is in constant address space it is a const
  3024. // value.
  3025. if (!(BaseType.isConstQualified() ||
  3026. (Info.getLangOpts().OpenCL &&
  3027. BaseType.getAddressSpace() == LangAS::opencl_constant))) {
  3028. if (!IsAccess)
  3029. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3030. if (Info.getLangOpts().CPlusPlus) {
  3031. Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
  3032. Info.Note(VD->getLocation(), diag::note_declared_at);
  3033. } else {
  3034. Info.FFDiag(E);
  3035. }
  3036. return CompleteObject();
  3037. }
  3038. } else if (!IsAccess) {
  3039. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3040. } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
  3041. // We support folding of const floating-point types, in order to make
  3042. // static const data members of such types (supported as an extension)
  3043. // more useful.
  3044. if (Info.getLangOpts().CPlusPlus11) {
  3045. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3046. Info.Note(VD->getLocation(), diag::note_declared_at);
  3047. } else {
  3048. Info.CCEDiag(E);
  3049. }
  3050. } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
  3051. Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
  3052. // Keep evaluating to see what we can do.
  3053. } else {
  3054. // FIXME: Allow folding of values of any literal type in all languages.
  3055. if (Info.checkingPotentialConstantExpression() &&
  3056. VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
  3057. // The definition of this variable could be constexpr. We can't
  3058. // access it right now, but may be able to in future.
  3059. } else if (Info.getLangOpts().CPlusPlus11) {
  3060. Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
  3061. Info.Note(VD->getLocation(), diag::note_declared_at);
  3062. } else {
  3063. Info.FFDiag(E);
  3064. }
  3065. return CompleteObject();
  3066. }
  3067. }
  3068. if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
  3069. return CompleteObject();
  3070. } else {
  3071. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3072. if (!Frame) {
  3073. if (const MaterializeTemporaryExpr *MTE =
  3074. dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
  3075. assert(MTE->getStorageDuration() == SD_Static &&
  3076. "should have a frame for a non-global materialized temporary");
  3077. // Per C++1y [expr.const]p2:
  3078. // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
  3079. // - a [...] glvalue of integral or enumeration type that refers to
  3080. // a non-volatile const object [...]
  3081. // [...]
  3082. // - a [...] glvalue of literal type that refers to a non-volatile
  3083. // object whose lifetime began within the evaluation of e.
  3084. //
  3085. // C++11 misses the 'began within the evaluation of e' check and
  3086. // instead allows all temporaries, including things like:
  3087. // int &&r = 1;
  3088. // int x = ++r;
  3089. // constexpr int k = r;
  3090. // Therefore we use the C++14 rules in C++11 too.
  3091. const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
  3092. const ValueDecl *ED = MTE->getExtendingDecl();
  3093. if (!(BaseType.isConstQualified() &&
  3094. BaseType->isIntegralOrEnumerationType()) &&
  3095. !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
  3096. if (!IsAccess)
  3097. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3098. Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
  3099. Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
  3100. return CompleteObject();
  3101. }
  3102. BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
  3103. assert(BaseVal && "got reference to unevaluated temporary");
  3104. } else {
  3105. if (!IsAccess)
  3106. return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
  3107. APValue Val;
  3108. LVal.moveInto(Val);
  3109. Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
  3110. << AK
  3111. << Val.getAsString(Info.Ctx,
  3112. Info.Ctx.getLValueReferenceType(LValType));
  3113. NoteLValueLocation(Info, LVal.Base);
  3114. return CompleteObject();
  3115. }
  3116. } else {
  3117. BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
  3118. assert(BaseVal && "missing value for temporary");
  3119. }
  3120. }
  3121. // In C++14, we can't safely access any mutable state when we might be
  3122. // evaluating after an unmodeled side effect.
  3123. //
  3124. // FIXME: Not all local state is mutable. Allow local constant subobjects
  3125. // to be read here (but take care with 'mutable' fields).
  3126. if ((Frame && Info.getLangOpts().CPlusPlus14 &&
  3127. Info.EvalStatus.HasSideEffects) ||
  3128. (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
  3129. return CompleteObject();
  3130. return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
  3131. }
  3132. /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
  3133. /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
  3134. /// glvalue referred to by an entity of reference type.
  3135. ///
  3136. /// \param Info - Information about the ongoing evaluation.
  3137. /// \param Conv - The expression for which we are performing the conversion.
  3138. /// Used for diagnostics.
  3139. /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
  3140. /// case of a non-class type).
  3141. /// \param LVal - The glvalue on which we are attempting to perform this action.
  3142. /// \param RVal - The produced value will be placed here.
  3143. static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
  3144. QualType Type,
  3145. const LValue &LVal, APValue &RVal) {
  3146. if (LVal.Designator.Invalid)
  3147. return false;
  3148. // Check for special cases where there is no existing APValue to look at.
  3149. const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
  3150. if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
  3151. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
  3152. // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
  3153. // initializer until now for such expressions. Such an expression can't be
  3154. // an ICE in C, so this only matters for fold.
  3155. if (Type.isVolatileQualified()) {
  3156. Info.FFDiag(Conv);
  3157. return false;
  3158. }
  3159. APValue Lit;
  3160. if (!Evaluate(Lit, Info, CLE->getInitializer()))
  3161. return false;
  3162. CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
  3163. return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
  3164. } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
  3165. // Special-case character extraction so we don't have to construct an
  3166. // APValue for the whole string.
  3167. assert(LVal.Designator.Entries.size() <= 1 &&
  3168. "Can only read characters from string literals");
  3169. if (LVal.Designator.Entries.empty()) {
  3170. // Fail for now for LValue to RValue conversion of an array.
  3171. // (This shouldn't show up in C/C++, but it could be triggered by a
  3172. // weird EvaluateAsRValue call from a tool.)
  3173. Info.FFDiag(Conv);
  3174. return false;
  3175. }
  3176. if (LVal.Designator.isOnePastTheEnd()) {
  3177. if (Info.getLangOpts().CPlusPlus11)
  3178. Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
  3179. else
  3180. Info.FFDiag(Conv);
  3181. return false;
  3182. }
  3183. uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
  3184. RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
  3185. return true;
  3186. }
  3187. }
  3188. CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
  3189. return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
  3190. }
  3191. /// Perform an assignment of Val to LVal. Takes ownership of Val.
  3192. static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3193. QualType LValType, APValue &Val) {
  3194. if (LVal.Designator.Invalid)
  3195. return false;
  3196. if (!Info.getLangOpts().CPlusPlus14) {
  3197. Info.FFDiag(E);
  3198. return false;
  3199. }
  3200. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3201. return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
  3202. }
  3203. namespace {
  3204. struct CompoundAssignSubobjectHandler {
  3205. EvalInfo &Info;
  3206. const Expr *E;
  3207. QualType PromotedLHSType;
  3208. BinaryOperatorKind Opcode;
  3209. const APValue &RHS;
  3210. static const AccessKinds AccessKind = AK_Assign;
  3211. typedef bool result_type;
  3212. bool checkConst(QualType QT) {
  3213. // Assigning to a const object has undefined behavior.
  3214. if (QT.isConstQualified()) {
  3215. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3216. return false;
  3217. }
  3218. return true;
  3219. }
  3220. bool failed() { return false; }
  3221. bool found(APValue &Subobj, QualType SubobjType) {
  3222. switch (Subobj.getKind()) {
  3223. case APValue::Int:
  3224. return found(Subobj.getInt(), SubobjType);
  3225. case APValue::Float:
  3226. return found(Subobj.getFloat(), SubobjType);
  3227. case APValue::ComplexInt:
  3228. case APValue::ComplexFloat:
  3229. // FIXME: Implement complex compound assignment.
  3230. Info.FFDiag(E);
  3231. return false;
  3232. case APValue::LValue:
  3233. return foundPointer(Subobj, SubobjType);
  3234. default:
  3235. // FIXME: can this happen?
  3236. Info.FFDiag(E);
  3237. return false;
  3238. }
  3239. }
  3240. bool found(APSInt &Value, QualType SubobjType) {
  3241. if (!checkConst(SubobjType))
  3242. return false;
  3243. if (!SubobjType->isIntegerType()) {
  3244. // We don't support compound assignment on integer-cast-to-pointer
  3245. // values.
  3246. Info.FFDiag(E);
  3247. return false;
  3248. }
  3249. if (RHS.isInt()) {
  3250. APSInt LHS =
  3251. HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
  3252. if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
  3253. return false;
  3254. Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
  3255. return true;
  3256. } else if (RHS.isFloat()) {
  3257. APFloat FValue(0.0);
  3258. return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
  3259. FValue) &&
  3260. handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
  3261. HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
  3262. Value);
  3263. }
  3264. Info.FFDiag(E);
  3265. return false;
  3266. }
  3267. bool found(APFloat &Value, QualType SubobjType) {
  3268. return checkConst(SubobjType) &&
  3269. HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
  3270. Value) &&
  3271. handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
  3272. HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
  3273. }
  3274. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3275. if (!checkConst(SubobjType))
  3276. return false;
  3277. QualType PointeeType;
  3278. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3279. PointeeType = PT->getPointeeType();
  3280. if (PointeeType.isNull() || !RHS.isInt() ||
  3281. (Opcode != BO_Add && Opcode != BO_Sub)) {
  3282. Info.FFDiag(E);
  3283. return false;
  3284. }
  3285. APSInt Offset = RHS.getInt();
  3286. if (Opcode == BO_Sub)
  3287. negateAsSigned(Offset);
  3288. LValue LVal;
  3289. LVal.setFrom(Info.Ctx, Subobj);
  3290. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
  3291. return false;
  3292. LVal.moveInto(Subobj);
  3293. return true;
  3294. }
  3295. };
  3296. } // end anonymous namespace
  3297. const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
  3298. /// Perform a compound assignment of LVal <op>= RVal.
  3299. static bool handleCompoundAssignment(
  3300. EvalInfo &Info, const Expr *E,
  3301. const LValue &LVal, QualType LValType, QualType PromotedLValType,
  3302. BinaryOperatorKind Opcode, const APValue &RVal) {
  3303. if (LVal.Designator.Invalid)
  3304. return false;
  3305. if (!Info.getLangOpts().CPlusPlus14) {
  3306. Info.FFDiag(E);
  3307. return false;
  3308. }
  3309. CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
  3310. CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
  3311. RVal };
  3312. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3313. }
  3314. namespace {
  3315. struct IncDecSubobjectHandler {
  3316. EvalInfo &Info;
  3317. const UnaryOperator *E;
  3318. AccessKinds AccessKind;
  3319. APValue *Old;
  3320. typedef bool result_type;
  3321. bool checkConst(QualType QT) {
  3322. // Assigning to a const object has undefined behavior.
  3323. if (QT.isConstQualified()) {
  3324. Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
  3325. return false;
  3326. }
  3327. return true;
  3328. }
  3329. bool failed() { return false; }
  3330. bool found(APValue &Subobj, QualType SubobjType) {
  3331. // Stash the old value. Also clear Old, so we don't clobber it later
  3332. // if we're post-incrementing a complex.
  3333. if (Old) {
  3334. *Old = Subobj;
  3335. Old = nullptr;
  3336. }
  3337. switch (Subobj.getKind()) {
  3338. case APValue::Int:
  3339. return found(Subobj.getInt(), SubobjType);
  3340. case APValue::Float:
  3341. return found(Subobj.getFloat(), SubobjType);
  3342. case APValue::ComplexInt:
  3343. return found(Subobj.getComplexIntReal(),
  3344. SubobjType->castAs<ComplexType>()->getElementType()
  3345. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3346. case APValue::ComplexFloat:
  3347. return found(Subobj.getComplexFloatReal(),
  3348. SubobjType->castAs<ComplexType>()->getElementType()
  3349. .withCVRQualifiers(SubobjType.getCVRQualifiers()));
  3350. case APValue::LValue:
  3351. return foundPointer(Subobj, SubobjType);
  3352. default:
  3353. // FIXME: can this happen?
  3354. Info.FFDiag(E);
  3355. return false;
  3356. }
  3357. }
  3358. bool found(APSInt &Value, QualType SubobjType) {
  3359. if (!checkConst(SubobjType))
  3360. return false;
  3361. if (!SubobjType->isIntegerType()) {
  3362. // We don't support increment / decrement on integer-cast-to-pointer
  3363. // values.
  3364. Info.FFDiag(E);
  3365. return false;
  3366. }
  3367. if (Old) *Old = APValue(Value);
  3368. // bool arithmetic promotes to int, and the conversion back to bool
  3369. // doesn't reduce mod 2^n, so special-case it.
  3370. if (SubobjType->isBooleanType()) {
  3371. if (AccessKind == AK_Increment)
  3372. Value = 1;
  3373. else
  3374. Value = !Value;
  3375. return true;
  3376. }
  3377. bool WasNegative = Value.isNegative();
  3378. if (AccessKind == AK_Increment) {
  3379. ++Value;
  3380. if (!WasNegative && Value.isNegative() && E->canOverflow()) {
  3381. APSInt ActualValue(Value, /*IsUnsigned*/true);
  3382. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3383. }
  3384. } else {
  3385. --Value;
  3386. if (WasNegative && !Value.isNegative() && E->canOverflow()) {
  3387. unsigned BitWidth = Value.getBitWidth();
  3388. APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
  3389. ActualValue.setBit(BitWidth);
  3390. return HandleOverflow(Info, E, ActualValue, SubobjType);
  3391. }
  3392. }
  3393. return true;
  3394. }
  3395. bool found(APFloat &Value, QualType SubobjType) {
  3396. if (!checkConst(SubobjType))
  3397. return false;
  3398. if (Old) *Old = APValue(Value);
  3399. APFloat One(Value.getSemantics(), 1);
  3400. if (AccessKind == AK_Increment)
  3401. Value.add(One, APFloat::rmNearestTiesToEven);
  3402. else
  3403. Value.subtract(One, APFloat::rmNearestTiesToEven);
  3404. return true;
  3405. }
  3406. bool foundPointer(APValue &Subobj, QualType SubobjType) {
  3407. if (!checkConst(SubobjType))
  3408. return false;
  3409. QualType PointeeType;
  3410. if (const PointerType *PT = SubobjType->getAs<PointerType>())
  3411. PointeeType = PT->getPointeeType();
  3412. else {
  3413. Info.FFDiag(E);
  3414. return false;
  3415. }
  3416. LValue LVal;
  3417. LVal.setFrom(Info.Ctx, Subobj);
  3418. if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
  3419. AccessKind == AK_Increment ? 1 : -1))
  3420. return false;
  3421. LVal.moveInto(Subobj);
  3422. return true;
  3423. }
  3424. };
  3425. } // end anonymous namespace
  3426. /// Perform an increment or decrement on LVal.
  3427. static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
  3428. QualType LValType, bool IsIncrement, APValue *Old) {
  3429. if (LVal.Designator.Invalid)
  3430. return false;
  3431. if (!Info.getLangOpts().CPlusPlus14) {
  3432. Info.FFDiag(E);
  3433. return false;
  3434. }
  3435. AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
  3436. CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
  3437. IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
  3438. return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
  3439. }
  3440. /// Build an lvalue for the object argument of a member function call.
  3441. static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
  3442. LValue &This) {
  3443. if (Object->getType()->isPointerType())
  3444. return EvaluatePointer(Object, This, Info);
  3445. if (Object->isGLValue())
  3446. return EvaluateLValue(Object, This, Info);
  3447. if (Object->getType()->isLiteralType(Info.Ctx))
  3448. return EvaluateTemporary(Object, This, Info);
  3449. Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
  3450. return false;
  3451. }
  3452. /// HandleMemberPointerAccess - Evaluate a member access operation and build an
  3453. /// lvalue referring to the result.
  3454. ///
  3455. /// \param Info - Information about the ongoing evaluation.
  3456. /// \param LV - An lvalue referring to the base of the member pointer.
  3457. /// \param RHS - The member pointer expression.
  3458. /// \param IncludeMember - Specifies whether the member itself is included in
  3459. /// the resulting LValue subobject designator. This is not possible when
  3460. /// creating a bound member function.
  3461. /// \return The field or method declaration to which the member pointer refers,
  3462. /// or 0 if evaluation fails.
  3463. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3464. QualType LVType,
  3465. LValue &LV,
  3466. const Expr *RHS,
  3467. bool IncludeMember = true) {
  3468. MemberPtr MemPtr;
  3469. if (!EvaluateMemberPointer(RHS, MemPtr, Info))
  3470. return nullptr;
  3471. // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
  3472. // member value, the behavior is undefined.
  3473. if (!MemPtr.getDecl()) {
  3474. // FIXME: Specific diagnostic.
  3475. Info.FFDiag(RHS);
  3476. return nullptr;
  3477. }
  3478. if (MemPtr.isDerivedMember()) {
  3479. // This is a member of some derived class. Truncate LV appropriately.
  3480. // The end of the derived-to-base path for the base object must match the
  3481. // derived-to-base path for the member pointer.
  3482. if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
  3483. LV.Designator.Entries.size()) {
  3484. Info.FFDiag(RHS);
  3485. return nullptr;
  3486. }
  3487. unsigned PathLengthToMember =
  3488. LV.Designator.Entries.size() - MemPtr.Path.size();
  3489. for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
  3490. const CXXRecordDecl *LVDecl = getAsBaseClass(
  3491. LV.Designator.Entries[PathLengthToMember + I]);
  3492. const CXXRecordDecl *MPDecl = MemPtr.Path[I];
  3493. if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
  3494. Info.FFDiag(RHS);
  3495. return nullptr;
  3496. }
  3497. }
  3498. // Truncate the lvalue to the appropriate derived class.
  3499. if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
  3500. PathLengthToMember))
  3501. return nullptr;
  3502. } else if (!MemPtr.Path.empty()) {
  3503. // Extend the LValue path with the member pointer's path.
  3504. LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
  3505. MemPtr.Path.size() + IncludeMember);
  3506. // Walk down to the appropriate base class.
  3507. if (const PointerType *PT = LVType->getAs<PointerType>())
  3508. LVType = PT->getPointeeType();
  3509. const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
  3510. assert(RD && "member pointer access on non-class-type expression");
  3511. // The first class in the path is that of the lvalue.
  3512. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
  3513. const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
  3514. if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
  3515. return nullptr;
  3516. RD = Base;
  3517. }
  3518. // Finally cast to the class containing the member.
  3519. if (!HandleLValueDirectBase(Info, RHS, LV, RD,
  3520. MemPtr.getContainingRecord()))
  3521. return nullptr;
  3522. }
  3523. // Add the member. Note that we cannot build bound member functions here.
  3524. if (IncludeMember) {
  3525. if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
  3526. if (!HandleLValueMember(Info, RHS, LV, FD))
  3527. return nullptr;
  3528. } else if (const IndirectFieldDecl *IFD =
  3529. dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
  3530. if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
  3531. return nullptr;
  3532. } else {
  3533. llvm_unreachable("can't construct reference to bound member function");
  3534. }
  3535. }
  3536. return MemPtr.getDecl();
  3537. }
  3538. static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
  3539. const BinaryOperator *BO,
  3540. LValue &LV,
  3541. bool IncludeMember = true) {
  3542. assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
  3543. if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
  3544. if (Info.noteFailure()) {
  3545. MemberPtr MemPtr;
  3546. EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
  3547. }
  3548. return nullptr;
  3549. }
  3550. return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
  3551. BO->getRHS(), IncludeMember);
  3552. }
  3553. /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
  3554. /// the provided lvalue, which currently refers to the base object.
  3555. static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
  3556. LValue &Result) {
  3557. SubobjectDesignator &D = Result.Designator;
  3558. if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
  3559. return false;
  3560. QualType TargetQT = E->getType();
  3561. if (const PointerType *PT = TargetQT->getAs<PointerType>())
  3562. TargetQT = PT->getPointeeType();
  3563. // Check this cast lands within the final derived-to-base subobject path.
  3564. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
  3565. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3566. << D.MostDerivedType << TargetQT;
  3567. return false;
  3568. }
  3569. // Check the type of the final cast. We don't need to check the path,
  3570. // since a cast can only be formed if the path is unique.
  3571. unsigned NewEntriesSize = D.Entries.size() - E->path_size();
  3572. const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
  3573. const CXXRecordDecl *FinalType;
  3574. if (NewEntriesSize == D.MostDerivedPathLength)
  3575. FinalType = D.MostDerivedType->getAsCXXRecordDecl();
  3576. else
  3577. FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
  3578. if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
  3579. Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
  3580. << D.MostDerivedType << TargetQT;
  3581. return false;
  3582. }
  3583. // Truncate the lvalue to the appropriate derived class.
  3584. return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
  3585. }
  3586. namespace {
  3587. enum EvalStmtResult {
  3588. /// Evaluation failed.
  3589. ESR_Failed,
  3590. /// Hit a 'return' statement.
  3591. ESR_Returned,
  3592. /// Evaluation succeeded.
  3593. ESR_Succeeded,
  3594. /// Hit a 'continue' statement.
  3595. ESR_Continue,
  3596. /// Hit a 'break' statement.
  3597. ESR_Break,
  3598. /// Still scanning for 'case' or 'default' statement.
  3599. ESR_CaseNotFound
  3600. };
  3601. }
  3602. static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
  3603. // We don't need to evaluate the initializer for a static local.
  3604. if (!VD->hasLocalStorage())
  3605. return true;
  3606. LValue Result;
  3607. APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
  3608. const Expr *InitE = VD->getInit();
  3609. if (!InitE) {
  3610. Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
  3611. << false << VD->getType();
  3612. Val = APValue();
  3613. return false;
  3614. }
  3615. if (InitE->isValueDependent())
  3616. return false;
  3617. if (!EvaluateInPlace(Val, Info, Result, InitE)) {
  3618. // Wipe out any partially-computed value, to allow tracking that this
  3619. // evaluation failed.
  3620. Val = APValue();
  3621. return false;
  3622. }
  3623. return true;
  3624. }
  3625. static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
  3626. bool OK = true;
  3627. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3628. OK &= EvaluateVarDecl(Info, VD);
  3629. if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
  3630. for (auto *BD : DD->bindings())
  3631. if (auto *VD = BD->getHoldingVar())
  3632. OK &= EvaluateDecl(Info, VD);
  3633. return OK;
  3634. }
  3635. /// Evaluate a condition (either a variable declaration or an expression).
  3636. static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
  3637. const Expr *Cond, bool &Result) {
  3638. FullExpressionRAII Scope(Info);
  3639. if (CondDecl && !EvaluateDecl(Info, CondDecl))
  3640. return false;
  3641. return EvaluateAsBooleanCondition(Cond, Result, Info);
  3642. }
  3643. namespace {
  3644. /// A location where the result (returned value) of evaluating a
  3645. /// statement should be stored.
  3646. struct StmtResult {
  3647. /// The APValue that should be filled in with the returned value.
  3648. APValue &Value;
  3649. /// The location containing the result, if any (used to support RVO).
  3650. const LValue *Slot;
  3651. };
  3652. struct TempVersionRAII {
  3653. CallStackFrame &Frame;
  3654. TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
  3655. Frame.pushTempVersion();
  3656. }
  3657. ~TempVersionRAII() {
  3658. Frame.popTempVersion();
  3659. }
  3660. };
  3661. }
  3662. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3663. const Stmt *S,
  3664. const SwitchCase *SC = nullptr);
  3665. /// Evaluate the body of a loop, and translate the result as appropriate.
  3666. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
  3667. const Stmt *Body,
  3668. const SwitchCase *Case = nullptr) {
  3669. BlockScopeRAII Scope(Info);
  3670. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
  3671. case ESR_Break:
  3672. return ESR_Succeeded;
  3673. case ESR_Succeeded:
  3674. case ESR_Continue:
  3675. return ESR_Continue;
  3676. case ESR_Failed:
  3677. case ESR_Returned:
  3678. case ESR_CaseNotFound:
  3679. return ESR;
  3680. }
  3681. llvm_unreachable("Invalid EvalStmtResult!");
  3682. }
  3683. /// Evaluate a switch statement.
  3684. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
  3685. const SwitchStmt *SS) {
  3686. BlockScopeRAII Scope(Info);
  3687. // Evaluate the switch condition.
  3688. APSInt Value;
  3689. {
  3690. FullExpressionRAII Scope(Info);
  3691. if (const Stmt *Init = SS->getInit()) {
  3692. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3693. if (ESR != ESR_Succeeded)
  3694. return ESR;
  3695. }
  3696. if (SS->getConditionVariable() &&
  3697. !EvaluateDecl(Info, SS->getConditionVariable()))
  3698. return ESR_Failed;
  3699. if (!EvaluateInteger(SS->getCond(), Value, Info))
  3700. return ESR_Failed;
  3701. }
  3702. // Find the switch case corresponding to the value of the condition.
  3703. // FIXME: Cache this lookup.
  3704. const SwitchCase *Found = nullptr;
  3705. for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
  3706. SC = SC->getNextSwitchCase()) {
  3707. if (isa<DefaultStmt>(SC)) {
  3708. Found = SC;
  3709. continue;
  3710. }
  3711. const CaseStmt *CS = cast<CaseStmt>(SC);
  3712. APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
  3713. APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
  3714. : LHS;
  3715. if (LHS <= Value && Value <= RHS) {
  3716. Found = SC;
  3717. break;
  3718. }
  3719. }
  3720. if (!Found)
  3721. return ESR_Succeeded;
  3722. // Search the switch body for the switch case and evaluate it from there.
  3723. switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
  3724. case ESR_Break:
  3725. return ESR_Succeeded;
  3726. case ESR_Succeeded:
  3727. case ESR_Continue:
  3728. case ESR_Failed:
  3729. case ESR_Returned:
  3730. return ESR;
  3731. case ESR_CaseNotFound:
  3732. // This can only happen if the switch case is nested within a statement
  3733. // expression. We have no intention of supporting that.
  3734. Info.FFDiag(Found->getBeginLoc(),
  3735. diag::note_constexpr_stmt_expr_unsupported);
  3736. return ESR_Failed;
  3737. }
  3738. llvm_unreachable("Invalid EvalStmtResult!");
  3739. }
  3740. // Evaluate a statement.
  3741. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
  3742. const Stmt *S, const SwitchCase *Case) {
  3743. if (!Info.nextStep(S))
  3744. return ESR_Failed;
  3745. // If we're hunting down a 'case' or 'default' label, recurse through
  3746. // substatements until we hit the label.
  3747. if (Case) {
  3748. // FIXME: We don't start the lifetime of objects whose initialization we
  3749. // jump over. However, such objects must be of class type with a trivial
  3750. // default constructor that initialize all subobjects, so must be empty,
  3751. // so this almost never matters.
  3752. switch (S->getStmtClass()) {
  3753. case Stmt::CompoundStmtClass:
  3754. // FIXME: Precompute which substatement of a compound statement we
  3755. // would jump to, and go straight there rather than performing a
  3756. // linear scan each time.
  3757. case Stmt::LabelStmtClass:
  3758. case Stmt::AttributedStmtClass:
  3759. case Stmt::DoStmtClass:
  3760. break;
  3761. case Stmt::CaseStmtClass:
  3762. case Stmt::DefaultStmtClass:
  3763. if (Case == S)
  3764. Case = nullptr;
  3765. break;
  3766. case Stmt::IfStmtClass: {
  3767. // FIXME: Precompute which side of an 'if' we would jump to, and go
  3768. // straight there rather than scanning both sides.
  3769. const IfStmt *IS = cast<IfStmt>(S);
  3770. // Wrap the evaluation in a block scope, in case it's a DeclStmt
  3771. // preceded by our switch label.
  3772. BlockScopeRAII Scope(Info);
  3773. EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
  3774. if (ESR != ESR_CaseNotFound || !IS->getElse())
  3775. return ESR;
  3776. return EvaluateStmt(Result, Info, IS->getElse(), Case);
  3777. }
  3778. case Stmt::WhileStmtClass: {
  3779. EvalStmtResult ESR =
  3780. EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
  3781. if (ESR != ESR_Continue)
  3782. return ESR;
  3783. break;
  3784. }
  3785. case Stmt::ForStmtClass: {
  3786. const ForStmt *FS = cast<ForStmt>(S);
  3787. EvalStmtResult ESR =
  3788. EvaluateLoopBody(Result, Info, FS->getBody(), Case);
  3789. if (ESR != ESR_Continue)
  3790. return ESR;
  3791. if (FS->getInc()) {
  3792. FullExpressionRAII IncScope(Info);
  3793. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3794. return ESR_Failed;
  3795. }
  3796. break;
  3797. }
  3798. case Stmt::DeclStmtClass:
  3799. // FIXME: If the variable has initialization that can't be jumped over,
  3800. // bail out of any immediately-surrounding compound-statement too.
  3801. default:
  3802. return ESR_CaseNotFound;
  3803. }
  3804. }
  3805. switch (S->getStmtClass()) {
  3806. default:
  3807. if (const Expr *E = dyn_cast<Expr>(S)) {
  3808. // Don't bother evaluating beyond an expression-statement which couldn't
  3809. // be evaluated.
  3810. FullExpressionRAII Scope(Info);
  3811. if (!EvaluateIgnoredValue(Info, E))
  3812. return ESR_Failed;
  3813. return ESR_Succeeded;
  3814. }
  3815. Info.FFDiag(S->getBeginLoc());
  3816. return ESR_Failed;
  3817. case Stmt::NullStmtClass:
  3818. return ESR_Succeeded;
  3819. case Stmt::DeclStmtClass: {
  3820. const DeclStmt *DS = cast<DeclStmt>(S);
  3821. for (const auto *DclIt : DS->decls()) {
  3822. // Each declaration initialization is its own full-expression.
  3823. // FIXME: This isn't quite right; if we're performing aggregate
  3824. // initialization, each braced subexpression is its own full-expression.
  3825. FullExpressionRAII Scope(Info);
  3826. if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
  3827. return ESR_Failed;
  3828. }
  3829. return ESR_Succeeded;
  3830. }
  3831. case Stmt::ReturnStmtClass: {
  3832. const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
  3833. FullExpressionRAII Scope(Info);
  3834. if (RetExpr &&
  3835. !(Result.Slot
  3836. ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
  3837. : Evaluate(Result.Value, Info, RetExpr)))
  3838. return ESR_Failed;
  3839. return ESR_Returned;
  3840. }
  3841. case Stmt::CompoundStmtClass: {
  3842. BlockScopeRAII Scope(Info);
  3843. const CompoundStmt *CS = cast<CompoundStmt>(S);
  3844. for (const auto *BI : CS->body()) {
  3845. EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
  3846. if (ESR == ESR_Succeeded)
  3847. Case = nullptr;
  3848. else if (ESR != ESR_CaseNotFound)
  3849. return ESR;
  3850. }
  3851. return Case ? ESR_CaseNotFound : ESR_Succeeded;
  3852. }
  3853. case Stmt::IfStmtClass: {
  3854. const IfStmt *IS = cast<IfStmt>(S);
  3855. // Evaluate the condition, as either a var decl or as an expression.
  3856. BlockScopeRAII Scope(Info);
  3857. if (const Stmt *Init = IS->getInit()) {
  3858. EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
  3859. if (ESR != ESR_Succeeded)
  3860. return ESR;
  3861. }
  3862. bool Cond;
  3863. if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
  3864. return ESR_Failed;
  3865. if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
  3866. EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
  3867. if (ESR != ESR_Succeeded)
  3868. return ESR;
  3869. }
  3870. return ESR_Succeeded;
  3871. }
  3872. case Stmt::WhileStmtClass: {
  3873. const WhileStmt *WS = cast<WhileStmt>(S);
  3874. while (true) {
  3875. BlockScopeRAII Scope(Info);
  3876. bool Continue;
  3877. if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
  3878. Continue))
  3879. return ESR_Failed;
  3880. if (!Continue)
  3881. break;
  3882. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
  3883. if (ESR != ESR_Continue)
  3884. return ESR;
  3885. }
  3886. return ESR_Succeeded;
  3887. }
  3888. case Stmt::DoStmtClass: {
  3889. const DoStmt *DS = cast<DoStmt>(S);
  3890. bool Continue;
  3891. do {
  3892. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
  3893. if (ESR != ESR_Continue)
  3894. return ESR;
  3895. Case = nullptr;
  3896. FullExpressionRAII CondScope(Info);
  3897. if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
  3898. return ESR_Failed;
  3899. } while (Continue);
  3900. return ESR_Succeeded;
  3901. }
  3902. case Stmt::ForStmtClass: {
  3903. const ForStmt *FS = cast<ForStmt>(S);
  3904. BlockScopeRAII Scope(Info);
  3905. if (FS->getInit()) {
  3906. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3907. if (ESR != ESR_Succeeded)
  3908. return ESR;
  3909. }
  3910. while (true) {
  3911. BlockScopeRAII Scope(Info);
  3912. bool Continue = true;
  3913. if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
  3914. FS->getCond(), Continue))
  3915. return ESR_Failed;
  3916. if (!Continue)
  3917. break;
  3918. EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3919. if (ESR != ESR_Continue)
  3920. return ESR;
  3921. if (FS->getInc()) {
  3922. FullExpressionRAII IncScope(Info);
  3923. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3924. return ESR_Failed;
  3925. }
  3926. }
  3927. return ESR_Succeeded;
  3928. }
  3929. case Stmt::CXXForRangeStmtClass: {
  3930. const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
  3931. BlockScopeRAII Scope(Info);
  3932. // Evaluate the init-statement if present.
  3933. if (FS->getInit()) {
  3934. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
  3935. if (ESR != ESR_Succeeded)
  3936. return ESR;
  3937. }
  3938. // Initialize the __range variable.
  3939. EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
  3940. if (ESR != ESR_Succeeded)
  3941. return ESR;
  3942. // Create the __begin and __end iterators.
  3943. ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
  3944. if (ESR != ESR_Succeeded)
  3945. return ESR;
  3946. ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
  3947. if (ESR != ESR_Succeeded)
  3948. return ESR;
  3949. while (true) {
  3950. // Condition: __begin != __end.
  3951. {
  3952. bool Continue = true;
  3953. FullExpressionRAII CondExpr(Info);
  3954. if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
  3955. return ESR_Failed;
  3956. if (!Continue)
  3957. break;
  3958. }
  3959. // User's variable declaration, initialized by *__begin.
  3960. BlockScopeRAII InnerScope(Info);
  3961. ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
  3962. if (ESR != ESR_Succeeded)
  3963. return ESR;
  3964. // Loop body.
  3965. ESR = EvaluateLoopBody(Result, Info, FS->getBody());
  3966. if (ESR != ESR_Continue)
  3967. return ESR;
  3968. // Increment: ++__begin
  3969. if (!EvaluateIgnoredValue(Info, FS->getInc()))
  3970. return ESR_Failed;
  3971. }
  3972. return ESR_Succeeded;
  3973. }
  3974. case Stmt::SwitchStmtClass:
  3975. return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
  3976. case Stmt::ContinueStmtClass:
  3977. return ESR_Continue;
  3978. case Stmt::BreakStmtClass:
  3979. return ESR_Break;
  3980. case Stmt::LabelStmtClass:
  3981. return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
  3982. case Stmt::AttributedStmtClass:
  3983. // As a general principle, C++11 attributes can be ignored without
  3984. // any semantic impact.
  3985. return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
  3986. Case);
  3987. case Stmt::CaseStmtClass:
  3988. case Stmt::DefaultStmtClass:
  3989. return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
  3990. case Stmt::CXXTryStmtClass:
  3991. // Evaluate try blocks by evaluating all sub statements.
  3992. return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
  3993. }
  3994. }
  3995. /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
  3996. /// default constructor. If so, we'll fold it whether or not it's marked as
  3997. /// constexpr. If it is marked as constexpr, we will never implicitly define it,
  3998. /// so we need special handling.
  3999. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
  4000. const CXXConstructorDecl *CD,
  4001. bool IsValueInitialization) {
  4002. if (!CD->isTrivial() || !CD->isDefaultConstructor())
  4003. return false;
  4004. // Value-initialization does not call a trivial default constructor, so such a
  4005. // call is a core constant expression whether or not the constructor is
  4006. // constexpr.
  4007. if (!CD->isConstexpr() && !IsValueInitialization) {
  4008. if (Info.getLangOpts().CPlusPlus11) {
  4009. // FIXME: If DiagDecl is an implicitly-declared special member function,
  4010. // we should be much more explicit about why it's not constexpr.
  4011. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
  4012. << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
  4013. Info.Note(CD->getLocation(), diag::note_declared_at);
  4014. } else {
  4015. Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
  4016. }
  4017. }
  4018. return true;
  4019. }
  4020. /// CheckConstexprFunction - Check that a function can be called in a constant
  4021. /// expression.
  4022. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
  4023. const FunctionDecl *Declaration,
  4024. const FunctionDecl *Definition,
  4025. const Stmt *Body) {
  4026. // Potential constant expressions can contain calls to declared, but not yet
  4027. // defined, constexpr functions.
  4028. if (Info.checkingPotentialConstantExpression() && !Definition &&
  4029. Declaration->isConstexpr())
  4030. return false;
  4031. // Bail out if the function declaration itself is invalid. We will
  4032. // have produced a relevant diagnostic while parsing it, so just
  4033. // note the problematic sub-expression.
  4034. if (Declaration->isInvalidDecl()) {
  4035. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4036. return false;
  4037. }
  4038. // DR1872: An instantiated virtual constexpr function can't be called in a
  4039. // constant expression (prior to C++20). We can still constant-fold such a
  4040. // call.
  4041. if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
  4042. cast<CXXMethodDecl>(Declaration)->isVirtual())
  4043. Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
  4044. if (Definition && Definition->isInvalidDecl()) {
  4045. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4046. return false;
  4047. }
  4048. // Can we evaluate this function call?
  4049. if (Definition && Definition->isConstexpr() && Body)
  4050. return true;
  4051. if (Info.getLangOpts().CPlusPlus11) {
  4052. const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
  4053. // If this function is not constexpr because it is an inherited
  4054. // non-constexpr constructor, diagnose that directly.
  4055. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
  4056. if (CD && CD->isInheritingConstructor()) {
  4057. auto *Inherited = CD->getInheritedConstructor().getConstructor();
  4058. if (!Inherited->isConstexpr())
  4059. DiagDecl = CD = Inherited;
  4060. }
  4061. // FIXME: If DiagDecl is an implicitly-declared special member function
  4062. // or an inheriting constructor, we should be much more explicit about why
  4063. // it's not constexpr.
  4064. if (CD && CD->isInheritingConstructor())
  4065. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
  4066. << CD->getInheritedConstructor().getConstructor()->getParent();
  4067. else
  4068. Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
  4069. << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
  4070. Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
  4071. } else {
  4072. Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
  4073. }
  4074. return false;
  4075. }
  4076. namespace {
  4077. struct CheckDynamicTypeHandler {
  4078. AccessKinds AccessKind;
  4079. typedef bool result_type;
  4080. bool failed() { return false; }
  4081. bool found(APValue &Subobj, QualType SubobjType) { return true; }
  4082. bool found(APSInt &Value, QualType SubobjType) { return true; }
  4083. bool found(APFloat &Value, QualType SubobjType) { return true; }
  4084. };
  4085. } // end anonymous namespace
  4086. /// Check that we can access the notional vptr of an object / determine its
  4087. /// dynamic type.
  4088. static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
  4089. AccessKinds AK, bool Polymorphic) {
  4090. if (This.Designator.Invalid)
  4091. return false;
  4092. CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
  4093. if (!Obj)
  4094. return false;
  4095. if (!Obj.Value) {
  4096. // The object is not usable in constant expressions, so we can't inspect
  4097. // its value to see if it's in-lifetime or what the active union members
  4098. // are. We can still check for a one-past-the-end lvalue.
  4099. if (This.Designator.isOnePastTheEnd() ||
  4100. This.Designator.isMostDerivedAnUnsizedArray()) {
  4101. Info.FFDiag(E, This.Designator.isOnePastTheEnd()
  4102. ? diag::note_constexpr_access_past_end
  4103. : diag::note_constexpr_access_unsized_array)
  4104. << AK;
  4105. return false;
  4106. } else if (Polymorphic) {
  4107. // Conservatively refuse to perform a polymorphic operation if we would
  4108. // not be able to read a notional 'vptr' value.
  4109. APValue Val;
  4110. This.moveInto(Val);
  4111. QualType StarThisType =
  4112. Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
  4113. Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
  4114. << AK << Val.getAsString(Info.Ctx, StarThisType);
  4115. return false;
  4116. }
  4117. return true;
  4118. }
  4119. CheckDynamicTypeHandler Handler{AK};
  4120. return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
  4121. }
  4122. /// Check that the pointee of the 'this' pointer in a member function call is
  4123. /// either within its lifetime or in its period of construction or destruction.
  4124. static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
  4125. const LValue &This) {
  4126. return checkDynamicType(Info, E, This, AK_MemberCall, false);
  4127. }
  4128. struct DynamicType {
  4129. /// The dynamic class type of the object.
  4130. const CXXRecordDecl *Type;
  4131. /// The corresponding path length in the lvalue.
  4132. unsigned PathLength;
  4133. };
  4134. static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
  4135. unsigned PathLength) {
  4136. assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
  4137. Designator.Entries.size() && "invalid path length");
  4138. return (PathLength == Designator.MostDerivedPathLength)
  4139. ? Designator.MostDerivedType->getAsCXXRecordDecl()
  4140. : getAsBaseClass(Designator.Entries[PathLength - 1]);
  4141. }
  4142. /// Determine the dynamic type of an object.
  4143. static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
  4144. LValue &This, AccessKinds AK) {
  4145. // If we don't have an lvalue denoting an object of class type, there is no
  4146. // meaningful dynamic type. (We consider objects of non-class type to have no
  4147. // dynamic type.)
  4148. if (!checkDynamicType(Info, E, This, AK, true))
  4149. return None;
  4150. // Refuse to compute a dynamic type in the presence of virtual bases. This
  4151. // shouldn't happen other than in constant-folding situations, since literal
  4152. // types can't have virtual bases.
  4153. //
  4154. // Note that consumers of DynamicType assume that the type has no virtual
  4155. // bases, and will need modifications if this restriction is relaxed.
  4156. const CXXRecordDecl *Class =
  4157. This.Designator.MostDerivedType->getAsCXXRecordDecl();
  4158. if (!Class || Class->getNumVBases()) {
  4159. Info.FFDiag(E);
  4160. return None;
  4161. }
  4162. // FIXME: For very deep class hierarchies, it might be beneficial to use a
  4163. // binary search here instead. But the overwhelmingly common case is that
  4164. // we're not in the middle of a constructor, so it probably doesn't matter
  4165. // in practice.
  4166. ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
  4167. for (unsigned PathLength = This.Designator.MostDerivedPathLength;
  4168. PathLength <= Path.size(); ++PathLength) {
  4169. switch (Info.isEvaluatingConstructor(This.getLValueBase(),
  4170. Path.slice(0, PathLength))) {
  4171. case ConstructionPhase::Bases:
  4172. // We're constructing a base class. This is not the dynamic type.
  4173. break;
  4174. case ConstructionPhase::None:
  4175. case ConstructionPhase::AfterBases:
  4176. // We've finished constructing the base classes, so this is the dynamic
  4177. // type.
  4178. return DynamicType{getBaseClassType(This.Designator, PathLength),
  4179. PathLength};
  4180. }
  4181. }
  4182. // CWG issue 1517: we're constructing a base class of the object described by
  4183. // 'This', so that object has not yet begun its period of construction and
  4184. // any polymorphic operation on it results in undefined behavior.
  4185. Info.FFDiag(E);
  4186. return None;
  4187. }
  4188. /// Perform virtual dispatch.
  4189. static const CXXMethodDecl *HandleVirtualDispatch(
  4190. EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
  4191. llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
  4192. Optional<DynamicType> DynType =
  4193. ComputeDynamicType(Info, E, This, AK_MemberCall);
  4194. if (!DynType)
  4195. return nullptr;
  4196. // Find the final overrider. It must be declared in one of the classes on the
  4197. // path from the dynamic type to the static type.
  4198. // FIXME: If we ever allow literal types to have virtual base classes, that
  4199. // won't be true.
  4200. const CXXMethodDecl *Callee = Found;
  4201. unsigned PathLength = DynType->PathLength;
  4202. for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
  4203. const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
  4204. const CXXMethodDecl *Overrider =
  4205. Found->getCorrespondingMethodDeclaredInClass(Class, false);
  4206. if (Overrider) {
  4207. Callee = Overrider;
  4208. break;
  4209. }
  4210. }
  4211. // C++2a [class.abstract]p6:
  4212. // the effect of making a virtual call to a pure virtual function [...] is
  4213. // undefined
  4214. if (Callee->isPure()) {
  4215. Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
  4216. Info.Note(Callee->getLocation(), diag::note_declared_at);
  4217. return nullptr;
  4218. }
  4219. // If necessary, walk the rest of the path to determine the sequence of
  4220. // covariant adjustment steps to apply.
  4221. if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
  4222. Found->getReturnType())) {
  4223. CovariantAdjustmentPath.push_back(Callee->getReturnType());
  4224. for (unsigned CovariantPathLength = PathLength + 1;
  4225. CovariantPathLength != This.Designator.Entries.size();
  4226. ++CovariantPathLength) {
  4227. const CXXRecordDecl *NextClass =
  4228. getBaseClassType(This.Designator, CovariantPathLength);
  4229. const CXXMethodDecl *Next =
  4230. Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
  4231. if (Next && !Info.Ctx.hasSameUnqualifiedType(
  4232. Next->getReturnType(), CovariantAdjustmentPath.back()))
  4233. CovariantAdjustmentPath.push_back(Next->getReturnType());
  4234. }
  4235. if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
  4236. CovariantAdjustmentPath.back()))
  4237. CovariantAdjustmentPath.push_back(Found->getReturnType());
  4238. }
  4239. // Perform 'this' adjustment.
  4240. if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
  4241. return nullptr;
  4242. return Callee;
  4243. }
  4244. /// Perform the adjustment from a value returned by a virtual function to
  4245. /// a value of the statically expected type, which may be a pointer or
  4246. /// reference to a base class of the returned type.
  4247. static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
  4248. APValue &Result,
  4249. ArrayRef<QualType> Path) {
  4250. assert(Result.isLValue() &&
  4251. "unexpected kind of APValue for covariant return");
  4252. if (Result.isNullPointer())
  4253. return true;
  4254. LValue LVal;
  4255. LVal.setFrom(Info.Ctx, Result);
  4256. const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
  4257. for (unsigned I = 1; I != Path.size(); ++I) {
  4258. const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
  4259. assert(OldClass && NewClass && "unexpected kind of covariant return");
  4260. if (OldClass != NewClass &&
  4261. !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
  4262. return false;
  4263. OldClass = NewClass;
  4264. }
  4265. LVal.moveInto(Result);
  4266. return true;
  4267. }
  4268. /// Determine whether \p Base, which is known to be a direct base class of
  4269. /// \p Derived, is a public base class.
  4270. static bool isBaseClassPublic(const CXXRecordDecl *Derived,
  4271. const CXXRecordDecl *Base) {
  4272. for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
  4273. auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
  4274. if (BaseClass && declaresSameEntity(BaseClass, Base))
  4275. return BaseSpec.getAccessSpecifier() == AS_public;
  4276. }
  4277. llvm_unreachable("Base is not a direct base of Derived");
  4278. }
  4279. /// Apply the given dynamic cast operation on the provided lvalue.
  4280. ///
  4281. /// This implements the hard case of dynamic_cast, requiring a "runtime check"
  4282. /// to find a suitable target subobject.
  4283. static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
  4284. LValue &Ptr) {
  4285. // We can't do anything with a non-symbolic pointer value.
  4286. SubobjectDesignator &D = Ptr.Designator;
  4287. if (D.Invalid)
  4288. return false;
  4289. // C++ [expr.dynamic.cast]p6:
  4290. // If v is a null pointer value, the result is a null pointer value.
  4291. if (Ptr.isNullPointer() && !E->isGLValue())
  4292. return true;
  4293. // For all the other cases, we need the pointer to point to an object within
  4294. // its lifetime / period of construction / destruction, and we need to know
  4295. // its dynamic type.
  4296. Optional<DynamicType> DynType =
  4297. ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
  4298. if (!DynType)
  4299. return false;
  4300. // C++ [expr.dynamic.cast]p7:
  4301. // If T is "pointer to cv void", then the result is a pointer to the most
  4302. // derived object
  4303. if (E->getType()->isVoidPointerType())
  4304. return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
  4305. const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
  4306. assert(C && "dynamic_cast target is not void pointer nor class");
  4307. CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
  4308. auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
  4309. // C++ [expr.dynamic.cast]p9:
  4310. if (!E->isGLValue()) {
  4311. // The value of a failed cast to pointer type is the null pointer value
  4312. // of the required result type.
  4313. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  4314. Ptr.setNull(E->getType(), TargetVal);
  4315. return true;
  4316. }
  4317. // A failed cast to reference type throws [...] std::bad_cast.
  4318. unsigned DiagKind;
  4319. if (!Paths && (declaresSameEntity(DynType->Type, C) ||
  4320. DynType->Type->isDerivedFrom(C)))
  4321. DiagKind = 0;
  4322. else if (!Paths || Paths->begin() == Paths->end())
  4323. DiagKind = 1;
  4324. else if (Paths->isAmbiguous(CQT))
  4325. DiagKind = 2;
  4326. else {
  4327. assert(Paths->front().Access != AS_public && "why did the cast fail?");
  4328. DiagKind = 3;
  4329. }
  4330. Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
  4331. << DiagKind << Ptr.Designator.getType(Info.Ctx)
  4332. << Info.Ctx.getRecordType(DynType->Type)
  4333. << E->getType().getUnqualifiedType();
  4334. return false;
  4335. };
  4336. // Runtime check, phase 1:
  4337. // Walk from the base subobject towards the derived object looking for the
  4338. // target type.
  4339. for (int PathLength = Ptr.Designator.Entries.size();
  4340. PathLength >= (int)DynType->PathLength; --PathLength) {
  4341. const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
  4342. if (declaresSameEntity(Class, C))
  4343. return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
  4344. // We can only walk across public inheritance edges.
  4345. if (PathLength > (int)DynType->PathLength &&
  4346. !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
  4347. Class))
  4348. return RuntimeCheckFailed(nullptr);
  4349. }
  4350. // Runtime check, phase 2:
  4351. // Search the dynamic type for an unambiguous public base of type C.
  4352. CXXBasePaths Paths(/*FindAmbiguities=*/true,
  4353. /*RecordPaths=*/true, /*DetectVirtual=*/false);
  4354. if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
  4355. Paths.front().Access == AS_public) {
  4356. // Downcast to the dynamic type...
  4357. if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
  4358. return false;
  4359. // ... then upcast to the chosen base class subobject.
  4360. for (CXXBasePathElement &Elem : Paths.front())
  4361. if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
  4362. return false;
  4363. return true;
  4364. }
  4365. // Otherwise, the runtime check fails.
  4366. return RuntimeCheckFailed(&Paths);
  4367. }
  4368. namespace {
  4369. struct StartLifetimeOfUnionMemberHandler {
  4370. const FieldDecl *Field;
  4371. static const AccessKinds AccessKind = AK_Assign;
  4372. APValue getDefaultInitValue(QualType SubobjType) {
  4373. if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
  4374. if (RD->isUnion())
  4375. return APValue((const FieldDecl*)nullptr);
  4376. APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
  4377. std::distance(RD->field_begin(), RD->field_end()));
  4378. unsigned Index = 0;
  4379. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  4380. End = RD->bases_end(); I != End; ++I, ++Index)
  4381. Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
  4382. for (const auto *I : RD->fields()) {
  4383. if (I->isUnnamedBitfield())
  4384. continue;
  4385. Struct.getStructField(I->getFieldIndex()) =
  4386. getDefaultInitValue(I->getType());
  4387. }
  4388. return Struct;
  4389. }
  4390. if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
  4391. SubobjType->getAsArrayTypeUnsafe())) {
  4392. APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
  4393. if (Array.hasArrayFiller())
  4394. Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
  4395. return Array;
  4396. }
  4397. return APValue::IndeterminateValue();
  4398. }
  4399. typedef bool result_type;
  4400. bool failed() { return false; }
  4401. bool found(APValue &Subobj, QualType SubobjType) {
  4402. // We are supposed to perform no initialization but begin the lifetime of
  4403. // the object. We interpret that as meaning to do what default
  4404. // initialization of the object would do if all constructors involved were
  4405. // trivial:
  4406. // * All base, non-variant member, and array element subobjects' lifetimes
  4407. // begin
  4408. // * No variant members' lifetimes begin
  4409. // * All scalar subobjects whose lifetimes begin have indeterminate values
  4410. assert(SubobjType->isUnionType());
  4411. if (!declaresSameEntity(Subobj.getUnionField(), Field))
  4412. Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
  4413. return true;
  4414. }
  4415. bool found(APSInt &Value, QualType SubobjType) {
  4416. llvm_unreachable("wrong value kind for union object");
  4417. }
  4418. bool found(APFloat &Value, QualType SubobjType) {
  4419. llvm_unreachable("wrong value kind for union object");
  4420. }
  4421. };
  4422. } // end anonymous namespace
  4423. const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
  4424. /// Handle a builtin simple-assignment or a call to a trivial assignment
  4425. /// operator whose left-hand side might involve a union member access. If it
  4426. /// does, implicitly start the lifetime of any accessed union elements per
  4427. /// C++20 [class.union]5.
  4428. static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
  4429. const LValue &LHS) {
  4430. if (LHS.InvalidBase || LHS.Designator.Invalid)
  4431. return false;
  4432. llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
  4433. // C++ [class.union]p5:
  4434. // define the set S(E) of subexpressions of E as follows:
  4435. unsigned PathLength = LHS.Designator.Entries.size();
  4436. for (const Expr *E = LHSExpr; E != nullptr;) {
  4437. // -- If E is of the form A.B, S(E) contains the elements of S(A)...
  4438. if (auto *ME = dyn_cast<MemberExpr>(E)) {
  4439. auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  4440. if (!FD)
  4441. break;
  4442. // ... and also contains A.B if B names a union member
  4443. if (FD->getParent()->isUnion())
  4444. UnionPathLengths.push_back({PathLength - 1, FD});
  4445. E = ME->getBase();
  4446. --PathLength;
  4447. assert(declaresSameEntity(FD,
  4448. LHS.Designator.Entries[PathLength]
  4449. .getAsBaseOrMember().getPointer()));
  4450. // -- If E is of the form A[B] and is interpreted as a built-in array
  4451. // subscripting operator, S(E) is [S(the array operand, if any)].
  4452. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
  4453. // Step over an ArrayToPointerDecay implicit cast.
  4454. auto *Base = ASE->getBase()->IgnoreImplicit();
  4455. if (!Base->getType()->isArrayType())
  4456. break;
  4457. E = Base;
  4458. --PathLength;
  4459. } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  4460. // Step over a derived-to-base conversion.
  4461. E = ICE->getSubExpr();
  4462. if (ICE->getCastKind() == CK_NoOp)
  4463. continue;
  4464. if (ICE->getCastKind() != CK_DerivedToBase &&
  4465. ICE->getCastKind() != CK_UncheckedDerivedToBase)
  4466. break;
  4467. // Walk path backwards as we walk up from the base to the derived class.
  4468. for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
  4469. --PathLength;
  4470. (void)Elt;
  4471. assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
  4472. LHS.Designator.Entries[PathLength]
  4473. .getAsBaseOrMember().getPointer()));
  4474. }
  4475. // -- Otherwise, S(E) is empty.
  4476. } else {
  4477. break;
  4478. }
  4479. }
  4480. // Common case: no unions' lifetimes are started.
  4481. if (UnionPathLengths.empty())
  4482. return true;
  4483. // if modification of X [would access an inactive union member], an object
  4484. // of the type of X is implicitly created
  4485. CompleteObject Obj =
  4486. findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
  4487. if (!Obj)
  4488. return false;
  4489. for (std::pair<unsigned, const FieldDecl *> LengthAndField :
  4490. llvm::reverse(UnionPathLengths)) {
  4491. // Form a designator for the union object.
  4492. SubobjectDesignator D = LHS.Designator;
  4493. D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
  4494. StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
  4495. if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
  4496. return false;
  4497. }
  4498. return true;
  4499. }
  4500. /// Determine if a class has any fields that might need to be copied by a
  4501. /// trivial copy or move operation.
  4502. static bool hasFields(const CXXRecordDecl *RD) {
  4503. if (!RD || RD->isEmpty())
  4504. return false;
  4505. for (auto *FD : RD->fields()) {
  4506. if (FD->isUnnamedBitfield())
  4507. continue;
  4508. return true;
  4509. }
  4510. for (auto &Base : RD->bases())
  4511. if (hasFields(Base.getType()->getAsCXXRecordDecl()))
  4512. return true;
  4513. return false;
  4514. }
  4515. namespace {
  4516. typedef SmallVector<APValue, 8> ArgVector;
  4517. }
  4518. /// EvaluateArgs - Evaluate the arguments to a function call.
  4519. static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
  4520. EvalInfo &Info) {
  4521. bool Success = true;
  4522. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  4523. I != E; ++I) {
  4524. if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
  4525. // If we're checking for a potential constant expression, evaluate all
  4526. // initializers even if some of them fail.
  4527. if (!Info.noteFailure())
  4528. return false;
  4529. Success = false;
  4530. }
  4531. }
  4532. return Success;
  4533. }
  4534. /// Evaluate a function call.
  4535. static bool HandleFunctionCall(SourceLocation CallLoc,
  4536. const FunctionDecl *Callee, const LValue *This,
  4537. ArrayRef<const Expr*> Args, const Stmt *Body,
  4538. EvalInfo &Info, APValue &Result,
  4539. const LValue *ResultSlot) {
  4540. ArgVector ArgValues(Args.size());
  4541. if (!EvaluateArgs(Args, ArgValues, Info))
  4542. return false;
  4543. if (!Info.CheckCallLimit(CallLoc))
  4544. return false;
  4545. CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
  4546. // For a trivial copy or move assignment, perform an APValue copy. This is
  4547. // essential for unions, where the operations performed by the assignment
  4548. // operator cannot be represented as statements.
  4549. //
  4550. // Skip this for non-union classes with no fields; in that case, the defaulted
  4551. // copy/move does not actually read the object.
  4552. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
  4553. if (MD && MD->isDefaulted() &&
  4554. (MD->getParent()->isUnion() ||
  4555. (MD->isTrivial() && hasFields(MD->getParent())))) {
  4556. assert(This &&
  4557. (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
  4558. LValue RHS;
  4559. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4560. APValue RHSValue;
  4561. if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
  4562. RHS, RHSValue))
  4563. return false;
  4564. if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
  4565. !HandleUnionActiveMemberChange(Info, Args[0], *This))
  4566. return false;
  4567. if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
  4568. RHSValue))
  4569. return false;
  4570. This->moveInto(Result);
  4571. return true;
  4572. } else if (MD && isLambdaCallOperator(MD)) {
  4573. // We're in a lambda; determine the lambda capture field maps unless we're
  4574. // just constexpr checking a lambda's call operator. constexpr checking is
  4575. // done before the captures have been added to the closure object (unless
  4576. // we're inferring constexpr-ness), so we don't have access to them in this
  4577. // case. But since we don't need the captures to constexpr check, we can
  4578. // just ignore them.
  4579. if (!Info.checkingPotentialConstantExpression())
  4580. MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
  4581. Frame.LambdaThisCaptureField);
  4582. }
  4583. StmtResult Ret = {Result, ResultSlot};
  4584. EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
  4585. if (ESR == ESR_Succeeded) {
  4586. if (Callee->getReturnType()->isVoidType())
  4587. return true;
  4588. Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
  4589. }
  4590. return ESR == ESR_Returned;
  4591. }
  4592. /// Evaluate a constructor call.
  4593. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4594. APValue *ArgValues,
  4595. const CXXConstructorDecl *Definition,
  4596. EvalInfo &Info, APValue &Result) {
  4597. SourceLocation CallLoc = E->getExprLoc();
  4598. if (!Info.CheckCallLimit(CallLoc))
  4599. return false;
  4600. const CXXRecordDecl *RD = Definition->getParent();
  4601. if (RD->getNumVBases()) {
  4602. Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
  4603. return false;
  4604. }
  4605. EvalInfo::EvaluatingConstructorRAII EvalObj(
  4606. Info,
  4607. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  4608. RD->getNumBases());
  4609. CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
  4610. // FIXME: Creating an APValue just to hold a nonexistent return value is
  4611. // wasteful.
  4612. APValue RetVal;
  4613. StmtResult Ret = {RetVal, nullptr};
  4614. // If it's a delegating constructor, delegate.
  4615. if (Definition->isDelegatingConstructor()) {
  4616. CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
  4617. {
  4618. FullExpressionRAII InitScope(Info);
  4619. if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
  4620. return false;
  4621. }
  4622. return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4623. }
  4624. // For a trivial copy or move constructor, perform an APValue copy. This is
  4625. // essential for unions (or classes with anonymous union members), where the
  4626. // operations performed by the constructor cannot be represented by
  4627. // ctor-initializers.
  4628. //
  4629. // Skip this for empty non-union classes; we should not perform an
  4630. // lvalue-to-rvalue conversion on them because their copy constructor does not
  4631. // actually read them.
  4632. if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
  4633. (Definition->getParent()->isUnion() ||
  4634. (Definition->isTrivial() && hasFields(Definition->getParent())))) {
  4635. LValue RHS;
  4636. RHS.setFrom(Info.Ctx, ArgValues[0]);
  4637. return handleLValueToRValueConversion(
  4638. Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
  4639. RHS, Result);
  4640. }
  4641. // Reserve space for the struct members.
  4642. if (!RD->isUnion() && !Result.hasValue())
  4643. Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  4644. std::distance(RD->field_begin(), RD->field_end()));
  4645. if (RD->isInvalidDecl()) return false;
  4646. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  4647. // A scope for temporaries lifetime-extended by reference members.
  4648. BlockScopeRAII LifetimeExtendedScope(Info);
  4649. bool Success = true;
  4650. unsigned BasesSeen = 0;
  4651. #ifndef NDEBUG
  4652. CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
  4653. #endif
  4654. for (const auto *I : Definition->inits()) {
  4655. LValue Subobject = This;
  4656. LValue SubobjectParent = This;
  4657. APValue *Value = &Result;
  4658. // Determine the subobject to initialize.
  4659. FieldDecl *FD = nullptr;
  4660. if (I->isBaseInitializer()) {
  4661. QualType BaseType(I->getBaseClass(), 0);
  4662. #ifndef NDEBUG
  4663. // Non-virtual base classes are initialized in the order in the class
  4664. // definition. We have already checked for virtual base classes.
  4665. assert(!BaseIt->isVirtual() && "virtual base for literal type");
  4666. assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
  4667. "base class initializers not in expected order");
  4668. ++BaseIt;
  4669. #endif
  4670. if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
  4671. BaseType->getAsCXXRecordDecl(), &Layout))
  4672. return false;
  4673. Value = &Result.getStructBase(BasesSeen++);
  4674. } else if ((FD = I->getMember())) {
  4675. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
  4676. return false;
  4677. if (RD->isUnion()) {
  4678. Result = APValue(FD);
  4679. Value = &Result.getUnionValue();
  4680. } else {
  4681. Value = &Result.getStructField(FD->getFieldIndex());
  4682. }
  4683. } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
  4684. // Walk the indirect field decl's chain to find the object to initialize,
  4685. // and make sure we've initialized every step along it.
  4686. auto IndirectFieldChain = IFD->chain();
  4687. for (auto *C : IndirectFieldChain) {
  4688. FD = cast<FieldDecl>(C);
  4689. CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
  4690. // Switch the union field if it differs. This happens if we had
  4691. // preceding zero-initialization, and we're now initializing a union
  4692. // subobject other than the first.
  4693. // FIXME: In this case, the values of the other subobjects are
  4694. // specified, since zero-initialization sets all padding bits to zero.
  4695. if (!Value->hasValue() ||
  4696. (Value->isUnion() && Value->getUnionField() != FD)) {
  4697. if (CD->isUnion())
  4698. *Value = APValue(FD);
  4699. else
  4700. *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
  4701. std::distance(CD->field_begin(), CD->field_end()));
  4702. }
  4703. // Store Subobject as its parent before updating it for the last element
  4704. // in the chain.
  4705. if (C == IndirectFieldChain.back())
  4706. SubobjectParent = Subobject;
  4707. if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
  4708. return false;
  4709. if (CD->isUnion())
  4710. Value = &Value->getUnionValue();
  4711. else
  4712. Value = &Value->getStructField(FD->getFieldIndex());
  4713. }
  4714. } else {
  4715. llvm_unreachable("unknown base initializer kind");
  4716. }
  4717. // Need to override This for implicit field initializers as in this case
  4718. // This refers to innermost anonymous struct/union containing initializer,
  4719. // not to currently constructed class.
  4720. const Expr *Init = I->getInit();
  4721. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
  4722. isa<CXXDefaultInitExpr>(Init));
  4723. FullExpressionRAII InitScope(Info);
  4724. if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
  4725. (FD && FD->isBitField() &&
  4726. !truncateBitfieldValue(Info, Init, *Value, FD))) {
  4727. // If we're checking for a potential constant expression, evaluate all
  4728. // initializers even if some of them fail.
  4729. if (!Info.noteFailure())
  4730. return false;
  4731. Success = false;
  4732. }
  4733. // This is the point at which the dynamic type of the object becomes this
  4734. // class type.
  4735. if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
  4736. EvalObj.finishedConstructingBases();
  4737. }
  4738. return Success &&
  4739. EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
  4740. }
  4741. static bool HandleConstructorCall(const Expr *E, const LValue &This,
  4742. ArrayRef<const Expr*> Args,
  4743. const CXXConstructorDecl *Definition,
  4744. EvalInfo &Info, APValue &Result) {
  4745. ArgVector ArgValues(Args.size());
  4746. if (!EvaluateArgs(Args, ArgValues, Info))
  4747. return false;
  4748. return HandleConstructorCall(E, This, ArgValues.data(), Definition,
  4749. Info, Result);
  4750. }
  4751. //===----------------------------------------------------------------------===//
  4752. // Generic Evaluation
  4753. //===----------------------------------------------------------------------===//
  4754. namespace {
  4755. template <class Derived>
  4756. class ExprEvaluatorBase
  4757. : public ConstStmtVisitor<Derived, bool> {
  4758. private:
  4759. Derived &getDerived() { return static_cast<Derived&>(*this); }
  4760. bool DerivedSuccess(const APValue &V, const Expr *E) {
  4761. return getDerived().Success(V, E);
  4762. }
  4763. bool DerivedZeroInitialization(const Expr *E) {
  4764. return getDerived().ZeroInitialization(E);
  4765. }
  4766. // Check whether a conditional operator with a non-constant condition is a
  4767. // potential constant expression. If neither arm is a potential constant
  4768. // expression, then the conditional operator is not either.
  4769. template<typename ConditionalOperator>
  4770. void CheckPotentialConstantConditional(const ConditionalOperator *E) {
  4771. assert(Info.checkingPotentialConstantExpression());
  4772. // Speculatively evaluate both arms.
  4773. SmallVector<PartialDiagnosticAt, 8> Diag;
  4774. {
  4775. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4776. StmtVisitorTy::Visit(E->getFalseExpr());
  4777. if (Diag.empty())
  4778. return;
  4779. }
  4780. {
  4781. SpeculativeEvaluationRAII Speculate(Info, &Diag);
  4782. Diag.clear();
  4783. StmtVisitorTy::Visit(E->getTrueExpr());
  4784. if (Diag.empty())
  4785. return;
  4786. }
  4787. Error(E, diag::note_constexpr_conditional_never_const);
  4788. }
  4789. template<typename ConditionalOperator>
  4790. bool HandleConditionalOperator(const ConditionalOperator *E) {
  4791. bool BoolResult;
  4792. if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
  4793. if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
  4794. CheckPotentialConstantConditional(E);
  4795. return false;
  4796. }
  4797. if (Info.noteFailure()) {
  4798. StmtVisitorTy::Visit(E->getTrueExpr());
  4799. StmtVisitorTy::Visit(E->getFalseExpr());
  4800. }
  4801. return false;
  4802. }
  4803. Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
  4804. return StmtVisitorTy::Visit(EvalExpr);
  4805. }
  4806. protected:
  4807. EvalInfo &Info;
  4808. typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
  4809. typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
  4810. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  4811. return Info.CCEDiag(E, D);
  4812. }
  4813. bool ZeroInitialization(const Expr *E) { return Error(E); }
  4814. public:
  4815. ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
  4816. EvalInfo &getEvalInfo() { return Info; }
  4817. /// Report an evaluation error. This should only be called when an error is
  4818. /// first discovered. When propagating an error, just return false.
  4819. bool Error(const Expr *E, diag::kind D) {
  4820. Info.FFDiag(E, D);
  4821. return false;
  4822. }
  4823. bool Error(const Expr *E) {
  4824. return Error(E, diag::note_invalid_subexpr_in_const_expr);
  4825. }
  4826. bool VisitStmt(const Stmt *) {
  4827. llvm_unreachable("Expression evaluator should not be called on stmts");
  4828. }
  4829. bool VisitExpr(const Expr *E) {
  4830. return Error(E);
  4831. }
  4832. bool VisitConstantExpr(const ConstantExpr *E)
  4833. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4834. bool VisitParenExpr(const ParenExpr *E)
  4835. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4836. bool VisitUnaryExtension(const UnaryOperator *E)
  4837. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4838. bool VisitUnaryPlus(const UnaryOperator *E)
  4839. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4840. bool VisitChooseExpr(const ChooseExpr *E)
  4841. { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
  4842. bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
  4843. { return StmtVisitorTy::Visit(E->getResultExpr()); }
  4844. bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
  4845. { return StmtVisitorTy::Visit(E->getReplacement()); }
  4846. bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
  4847. TempVersionRAII RAII(*Info.CurrentCall);
  4848. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  4849. return StmtVisitorTy::Visit(E->getExpr());
  4850. }
  4851. bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
  4852. TempVersionRAII RAII(*Info.CurrentCall);
  4853. // The initializer may not have been parsed yet, or might be erroneous.
  4854. if (!E->getExpr())
  4855. return Error(E);
  4856. SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
  4857. return StmtVisitorTy::Visit(E->getExpr());
  4858. }
  4859. // We cannot create any objects for which cleanups are required, so there is
  4860. // nothing to do here; all cleanups must come from unevaluated subexpressions.
  4861. bool VisitExprWithCleanups(const ExprWithCleanups *E)
  4862. { return StmtVisitorTy::Visit(E->getSubExpr()); }
  4863. bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
  4864. CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
  4865. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4866. }
  4867. bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
  4868. if (!Info.Ctx.getLangOpts().CPlusPlus2a)
  4869. CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
  4870. return static_cast<Derived*>(this)->VisitCastExpr(E);
  4871. }
  4872. bool VisitBinaryOperator(const BinaryOperator *E) {
  4873. switch (E->getOpcode()) {
  4874. default:
  4875. return Error(E);
  4876. case BO_Comma:
  4877. VisitIgnoredValue(E->getLHS());
  4878. return StmtVisitorTy::Visit(E->getRHS());
  4879. case BO_PtrMemD:
  4880. case BO_PtrMemI: {
  4881. LValue Obj;
  4882. if (!HandleMemberPointerAccess(Info, E, Obj))
  4883. return false;
  4884. APValue Result;
  4885. if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
  4886. return false;
  4887. return DerivedSuccess(Result, E);
  4888. }
  4889. }
  4890. }
  4891. bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
  4892. // Evaluate and cache the common expression. We treat it as a temporary,
  4893. // even though it's not quite the same thing.
  4894. if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
  4895. Info, E->getCommon()))
  4896. return false;
  4897. return HandleConditionalOperator(E);
  4898. }
  4899. bool VisitConditionalOperator(const ConditionalOperator *E) {
  4900. bool IsBcpCall = false;
  4901. // If the condition (ignoring parens) is a __builtin_constant_p call,
  4902. // the result is a constant expression if it can be folded without
  4903. // side-effects. This is an important GNU extension. See GCC PR38377
  4904. // for discussion.
  4905. if (const CallExpr *CallCE =
  4906. dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
  4907. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  4908. IsBcpCall = true;
  4909. // Always assume __builtin_constant_p(...) ? ... : ... is a potential
  4910. // constant expression; we can't check whether it's potentially foldable.
  4911. if (Info.checkingPotentialConstantExpression() && IsBcpCall)
  4912. return false;
  4913. FoldConstant Fold(Info, IsBcpCall);
  4914. if (!HandleConditionalOperator(E)) {
  4915. Fold.keepDiagnostics();
  4916. return false;
  4917. }
  4918. return true;
  4919. }
  4920. bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  4921. if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
  4922. return DerivedSuccess(*Value, E);
  4923. const Expr *Source = E->getSourceExpr();
  4924. if (!Source)
  4925. return Error(E);
  4926. if (Source == E) { // sanity checking.
  4927. assert(0 && "OpaqueValueExpr recursively refers to itself");
  4928. return Error(E);
  4929. }
  4930. return StmtVisitorTy::Visit(Source);
  4931. }
  4932. bool VisitCallExpr(const CallExpr *E) {
  4933. APValue Result;
  4934. if (!handleCallExpr(E, Result, nullptr))
  4935. return false;
  4936. return DerivedSuccess(Result, E);
  4937. }
  4938. bool handleCallExpr(const CallExpr *E, APValue &Result,
  4939. const LValue *ResultSlot) {
  4940. const Expr *Callee = E->getCallee()->IgnoreParens();
  4941. QualType CalleeType = Callee->getType();
  4942. const FunctionDecl *FD = nullptr;
  4943. LValue *This = nullptr, ThisVal;
  4944. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  4945. bool HasQualifier = false;
  4946. // Extract function decl and 'this' pointer from the callee.
  4947. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
  4948. const CXXMethodDecl *Member = nullptr;
  4949. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
  4950. // Explicit bound member calls, such as x.f() or p->g();
  4951. if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
  4952. return false;
  4953. Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  4954. if (!Member)
  4955. return Error(Callee);
  4956. This = &ThisVal;
  4957. HasQualifier = ME->hasQualifier();
  4958. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
  4959. // Indirect bound member calls ('.*' or '->*').
  4960. Member = dyn_cast_or_null<CXXMethodDecl>(
  4961. HandleMemberPointerAccess(Info, BE, ThisVal, false));
  4962. if (!Member)
  4963. return Error(Callee);
  4964. This = &ThisVal;
  4965. } else
  4966. return Error(Callee);
  4967. FD = Member;
  4968. } else if (CalleeType->isFunctionPointerType()) {
  4969. LValue Call;
  4970. if (!EvaluatePointer(Callee, Call, Info))
  4971. return false;
  4972. if (!Call.getLValueOffset().isZero())
  4973. return Error(Callee);
  4974. FD = dyn_cast_or_null<FunctionDecl>(
  4975. Call.getLValueBase().dyn_cast<const ValueDecl*>());
  4976. if (!FD)
  4977. return Error(Callee);
  4978. // Don't call function pointers which have been cast to some other type.
  4979. // Per DR (no number yet), the caller and callee can differ in noexcept.
  4980. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
  4981. CalleeType->getPointeeType(), FD->getType())) {
  4982. return Error(E);
  4983. }
  4984. // Overloaded operator calls to member functions are represented as normal
  4985. // calls with '*this' as the first argument.
  4986. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  4987. if (MD && !MD->isStatic()) {
  4988. // FIXME: When selecting an implicit conversion for an overloaded
  4989. // operator delete, we sometimes try to evaluate calls to conversion
  4990. // operators without a 'this' parameter!
  4991. if (Args.empty())
  4992. return Error(E);
  4993. if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
  4994. return false;
  4995. This = &ThisVal;
  4996. Args = Args.slice(1);
  4997. } else if (MD && MD->isLambdaStaticInvoker()) {
  4998. // Map the static invoker for the lambda back to the call operator.
  4999. // Conveniently, we don't have to slice out the 'this' argument (as is
  5000. // being done for the non-static case), since a static member function
  5001. // doesn't have an implicit argument passed in.
  5002. const CXXRecordDecl *ClosureClass = MD->getParent();
  5003. assert(
  5004. ClosureClass->captures_begin() == ClosureClass->captures_end() &&
  5005. "Number of captures must be zero for conversion to function-ptr");
  5006. const CXXMethodDecl *LambdaCallOp =
  5007. ClosureClass->getLambdaCallOperator();
  5008. // Set 'FD', the function that will be called below, to the call
  5009. // operator. If the closure object represents a generic lambda, find
  5010. // the corresponding specialization of the call operator.
  5011. if (ClosureClass->isGenericLambda()) {
  5012. assert(MD->isFunctionTemplateSpecialization() &&
  5013. "A generic lambda's static-invoker function must be a "
  5014. "template specialization");
  5015. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  5016. FunctionTemplateDecl *CallOpTemplate =
  5017. LambdaCallOp->getDescribedFunctionTemplate();
  5018. void *InsertPos = nullptr;
  5019. FunctionDecl *CorrespondingCallOpSpecialization =
  5020. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  5021. assert(CorrespondingCallOpSpecialization &&
  5022. "We must always have a function call operator specialization "
  5023. "that corresponds to our static invoker specialization");
  5024. FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  5025. } else
  5026. FD = LambdaCallOp;
  5027. }
  5028. } else
  5029. return Error(E);
  5030. SmallVector<QualType, 4> CovariantAdjustmentPath;
  5031. if (This) {
  5032. auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
  5033. if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
  5034. // Perform virtual dispatch, if necessary.
  5035. FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
  5036. CovariantAdjustmentPath);
  5037. if (!FD)
  5038. return false;
  5039. } else {
  5040. // Check that the 'this' pointer points to an object of the right type.
  5041. if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
  5042. return false;
  5043. }
  5044. }
  5045. const FunctionDecl *Definition = nullptr;
  5046. Stmt *Body = FD->getBody(Definition);
  5047. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
  5048. !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
  5049. Result, ResultSlot))
  5050. return false;
  5051. if (!CovariantAdjustmentPath.empty() &&
  5052. !HandleCovariantReturnAdjustment(Info, E, Result,
  5053. CovariantAdjustmentPath))
  5054. return false;
  5055. return true;
  5056. }
  5057. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5058. return StmtVisitorTy::Visit(E->getInitializer());
  5059. }
  5060. bool VisitInitListExpr(const InitListExpr *E) {
  5061. if (E->getNumInits() == 0)
  5062. return DerivedZeroInitialization(E);
  5063. if (E->getNumInits() == 1)
  5064. return StmtVisitorTy::Visit(E->getInit(0));
  5065. return Error(E);
  5066. }
  5067. bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
  5068. return DerivedZeroInitialization(E);
  5069. }
  5070. bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
  5071. return DerivedZeroInitialization(E);
  5072. }
  5073. bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
  5074. return DerivedZeroInitialization(E);
  5075. }
  5076. /// A member expression where the object is a prvalue is itself a prvalue.
  5077. bool VisitMemberExpr(const MemberExpr *E) {
  5078. assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
  5079. "missing temporary materialization conversion");
  5080. assert(!E->isArrow() && "missing call to bound member function?");
  5081. APValue Val;
  5082. if (!Evaluate(Val, Info, E->getBase()))
  5083. return false;
  5084. QualType BaseTy = E->getBase()->getType();
  5085. const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  5086. if (!FD) return Error(E);
  5087. assert(!FD->getType()->isReferenceType() && "prvalue reference?");
  5088. assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5089. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5090. // Note: there is no lvalue base here. But this case should only ever
  5091. // happen in C or in C++98, where we cannot be evaluating a constexpr
  5092. // constructor, which is the only case the base matters.
  5093. CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
  5094. SubobjectDesignator Designator(BaseTy);
  5095. Designator.addDeclUnchecked(FD);
  5096. APValue Result;
  5097. return extractSubobject(Info, E, Obj, Designator, Result) &&
  5098. DerivedSuccess(Result, E);
  5099. }
  5100. bool VisitCastExpr(const CastExpr *E) {
  5101. switch (E->getCastKind()) {
  5102. default:
  5103. break;
  5104. case CK_AtomicToNonAtomic: {
  5105. APValue AtomicVal;
  5106. // This does not need to be done in place even for class/array types:
  5107. // atomic-to-non-atomic conversion implies copying the object
  5108. // representation.
  5109. if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
  5110. return false;
  5111. return DerivedSuccess(AtomicVal, E);
  5112. }
  5113. case CK_NoOp:
  5114. case CK_UserDefinedConversion:
  5115. return StmtVisitorTy::Visit(E->getSubExpr());
  5116. case CK_LValueToRValue: {
  5117. LValue LVal;
  5118. if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
  5119. return false;
  5120. APValue RVal;
  5121. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5122. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5123. LVal, RVal))
  5124. return false;
  5125. return DerivedSuccess(RVal, E);
  5126. }
  5127. }
  5128. return Error(E);
  5129. }
  5130. bool VisitUnaryPostInc(const UnaryOperator *UO) {
  5131. return VisitUnaryPostIncDec(UO);
  5132. }
  5133. bool VisitUnaryPostDec(const UnaryOperator *UO) {
  5134. return VisitUnaryPostIncDec(UO);
  5135. }
  5136. bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
  5137. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5138. return Error(UO);
  5139. LValue LVal;
  5140. if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
  5141. return false;
  5142. APValue RVal;
  5143. if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
  5144. UO->isIncrementOp(), &RVal))
  5145. return false;
  5146. return DerivedSuccess(RVal, UO);
  5147. }
  5148. bool VisitStmtExpr(const StmtExpr *E) {
  5149. // We will have checked the full-expressions inside the statement expression
  5150. // when they were completed, and don't need to check them again now.
  5151. if (Info.checkingForOverflow())
  5152. return Error(E);
  5153. BlockScopeRAII Scope(Info);
  5154. const CompoundStmt *CS = E->getSubStmt();
  5155. if (CS->body_empty())
  5156. return true;
  5157. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  5158. BE = CS->body_end();
  5159. /**/; ++BI) {
  5160. if (BI + 1 == BE) {
  5161. const Expr *FinalExpr = dyn_cast<Expr>(*BI);
  5162. if (!FinalExpr) {
  5163. Info.FFDiag((*BI)->getBeginLoc(),
  5164. diag::note_constexpr_stmt_expr_unsupported);
  5165. return false;
  5166. }
  5167. return this->Visit(FinalExpr);
  5168. }
  5169. APValue ReturnValue;
  5170. StmtResult Result = { ReturnValue, nullptr };
  5171. EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
  5172. if (ESR != ESR_Succeeded) {
  5173. // FIXME: If the statement-expression terminated due to 'return',
  5174. // 'break', or 'continue', it would be nice to propagate that to
  5175. // the outer statement evaluation rather than bailing out.
  5176. if (ESR != ESR_Failed)
  5177. Info.FFDiag((*BI)->getBeginLoc(),
  5178. diag::note_constexpr_stmt_expr_unsupported);
  5179. return false;
  5180. }
  5181. }
  5182. llvm_unreachable("Return from function from the loop above.");
  5183. }
  5184. /// Visit a value which is evaluated, but whose value is ignored.
  5185. void VisitIgnoredValue(const Expr *E) {
  5186. EvaluateIgnoredValue(Info, E);
  5187. }
  5188. /// Potentially visit a MemberExpr's base expression.
  5189. void VisitIgnoredBaseExpression(const Expr *E) {
  5190. // While MSVC doesn't evaluate the base expression, it does diagnose the
  5191. // presence of side-effecting behavior.
  5192. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
  5193. return;
  5194. VisitIgnoredValue(E);
  5195. }
  5196. };
  5197. } // namespace
  5198. //===----------------------------------------------------------------------===//
  5199. // Common base class for lvalue and temporary evaluation.
  5200. //===----------------------------------------------------------------------===//
  5201. namespace {
  5202. template<class Derived>
  5203. class LValueExprEvaluatorBase
  5204. : public ExprEvaluatorBase<Derived> {
  5205. protected:
  5206. LValue &Result;
  5207. bool InvalidBaseOK;
  5208. typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
  5209. typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
  5210. bool Success(APValue::LValueBase B) {
  5211. Result.set(B);
  5212. return true;
  5213. }
  5214. bool evaluatePointer(const Expr *E, LValue &Result) {
  5215. return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
  5216. }
  5217. public:
  5218. LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
  5219. : ExprEvaluatorBaseTy(Info), Result(Result),
  5220. InvalidBaseOK(InvalidBaseOK) {}
  5221. bool Success(const APValue &V, const Expr *E) {
  5222. Result.setFrom(this->Info.Ctx, V);
  5223. return true;
  5224. }
  5225. bool VisitMemberExpr(const MemberExpr *E) {
  5226. // Handle non-static data members.
  5227. QualType BaseTy;
  5228. bool EvalOK;
  5229. if (E->isArrow()) {
  5230. EvalOK = evaluatePointer(E->getBase(), Result);
  5231. BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
  5232. } else if (E->getBase()->isRValue()) {
  5233. assert(E->getBase()->getType()->isRecordType());
  5234. EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
  5235. BaseTy = E->getBase()->getType();
  5236. } else {
  5237. EvalOK = this->Visit(E->getBase());
  5238. BaseTy = E->getBase()->getType();
  5239. }
  5240. if (!EvalOK) {
  5241. if (!InvalidBaseOK)
  5242. return false;
  5243. Result.setInvalid(E);
  5244. return true;
  5245. }
  5246. const ValueDecl *MD = E->getMemberDecl();
  5247. if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  5248. assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
  5249. FD->getParent()->getCanonicalDecl() && "record / field mismatch");
  5250. (void)BaseTy;
  5251. if (!HandleLValueMember(this->Info, E, Result, FD))
  5252. return false;
  5253. } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
  5254. if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
  5255. return false;
  5256. } else
  5257. return this->Error(E);
  5258. if (MD->getType()->isReferenceType()) {
  5259. APValue RefValue;
  5260. if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
  5261. RefValue))
  5262. return false;
  5263. return Success(RefValue, E);
  5264. }
  5265. return true;
  5266. }
  5267. bool VisitBinaryOperator(const BinaryOperator *E) {
  5268. switch (E->getOpcode()) {
  5269. default:
  5270. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5271. case BO_PtrMemD:
  5272. case BO_PtrMemI:
  5273. return HandleMemberPointerAccess(this->Info, E, Result);
  5274. }
  5275. }
  5276. bool VisitCastExpr(const CastExpr *E) {
  5277. switch (E->getCastKind()) {
  5278. default:
  5279. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5280. case CK_DerivedToBase:
  5281. case CK_UncheckedDerivedToBase:
  5282. if (!this->Visit(E->getSubExpr()))
  5283. return false;
  5284. // Now figure out the necessary offset to add to the base LV to get from
  5285. // the derived class to the base class.
  5286. return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
  5287. Result);
  5288. }
  5289. }
  5290. };
  5291. }
  5292. //===----------------------------------------------------------------------===//
  5293. // LValue Evaluation
  5294. //
  5295. // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
  5296. // function designators (in C), decl references to void objects (in C), and
  5297. // temporaries (if building with -Wno-address-of-temporary).
  5298. //
  5299. // LValue evaluation produces values comprising a base expression of one of the
  5300. // following types:
  5301. // - Declarations
  5302. // * VarDecl
  5303. // * FunctionDecl
  5304. // - Literals
  5305. // * CompoundLiteralExpr in C (and in global scope in C++)
  5306. // * StringLiteral
  5307. // * PredefinedExpr
  5308. // * ObjCStringLiteralExpr
  5309. // * ObjCEncodeExpr
  5310. // * AddrLabelExpr
  5311. // * BlockExpr
  5312. // * CallExpr for a MakeStringConstant builtin
  5313. // - typeid(T) expressions, as TypeInfoLValues
  5314. // - Locals and temporaries
  5315. // * MaterializeTemporaryExpr
  5316. // * Any Expr, with a CallIndex indicating the function in which the temporary
  5317. // was evaluated, for cases where the MaterializeTemporaryExpr is missing
  5318. // from the AST (FIXME).
  5319. // * A MaterializeTemporaryExpr that has static storage duration, with no
  5320. // CallIndex, for a lifetime-extended temporary.
  5321. // plus an offset in bytes.
  5322. //===----------------------------------------------------------------------===//
  5323. namespace {
  5324. class LValueExprEvaluator
  5325. : public LValueExprEvaluatorBase<LValueExprEvaluator> {
  5326. public:
  5327. LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
  5328. LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
  5329. bool VisitVarDecl(const Expr *E, const VarDecl *VD);
  5330. bool VisitUnaryPreIncDec(const UnaryOperator *UO);
  5331. bool VisitDeclRefExpr(const DeclRefExpr *E);
  5332. bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
  5333. bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  5334. bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  5335. bool VisitMemberExpr(const MemberExpr *E);
  5336. bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
  5337. bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
  5338. bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  5339. bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  5340. bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
  5341. bool VisitUnaryDeref(const UnaryOperator *E);
  5342. bool VisitUnaryReal(const UnaryOperator *E);
  5343. bool VisitUnaryImag(const UnaryOperator *E);
  5344. bool VisitUnaryPreInc(const UnaryOperator *UO) {
  5345. return VisitUnaryPreIncDec(UO);
  5346. }
  5347. bool VisitUnaryPreDec(const UnaryOperator *UO) {
  5348. return VisitUnaryPreIncDec(UO);
  5349. }
  5350. bool VisitBinAssign(const BinaryOperator *BO);
  5351. bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  5352. bool VisitCastExpr(const CastExpr *E) {
  5353. switch (E->getCastKind()) {
  5354. default:
  5355. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  5356. case CK_LValueBitCast:
  5357. this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5358. if (!Visit(E->getSubExpr()))
  5359. return false;
  5360. Result.Designator.setInvalid();
  5361. return true;
  5362. case CK_BaseToDerived:
  5363. if (!Visit(E->getSubExpr()))
  5364. return false;
  5365. return HandleBaseToDerivedCast(Info, E, Result);
  5366. case CK_Dynamic:
  5367. if (!Visit(E->getSubExpr()))
  5368. return false;
  5369. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  5370. }
  5371. }
  5372. };
  5373. } // end anonymous namespace
  5374. /// Evaluate an expression as an lvalue. This can be legitimately called on
  5375. /// expressions which are not glvalues, in three cases:
  5376. /// * function designators in C, and
  5377. /// * "extern void" objects
  5378. /// * @selector() expressions in Objective-C
  5379. static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
  5380. bool InvalidBaseOK) {
  5381. assert(E->isGLValue() || E->getType()->isFunctionType() ||
  5382. E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
  5383. return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5384. }
  5385. bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
  5386. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  5387. return Success(FD);
  5388. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  5389. return VisitVarDecl(E, VD);
  5390. if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
  5391. return Visit(BD->getBinding());
  5392. return Error(E);
  5393. }
  5394. bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
  5395. // If we are within a lambda's call operator, check whether the 'VD' referred
  5396. // to within 'E' actually represents a lambda-capture that maps to a
  5397. // data-member/field within the closure object, and if so, evaluate to the
  5398. // field or what the field refers to.
  5399. if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
  5400. isa<DeclRefExpr>(E) &&
  5401. cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
  5402. // We don't always have a complete capture-map when checking or inferring if
  5403. // the function call operator meets the requirements of a constexpr function
  5404. // - but we don't need to evaluate the captures to determine constexprness
  5405. // (dcl.constexpr C++17).
  5406. if (Info.checkingPotentialConstantExpression())
  5407. return false;
  5408. if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
  5409. // Start with 'Result' referring to the complete closure object...
  5410. Result = *Info.CurrentCall->This;
  5411. // ... then update it to refer to the field of the closure object
  5412. // that represents the capture.
  5413. if (!HandleLValueMember(Info, E, Result, FD))
  5414. return false;
  5415. // And if the field is of reference type, update 'Result' to refer to what
  5416. // the field refers to.
  5417. if (FD->getType()->isReferenceType()) {
  5418. APValue RVal;
  5419. if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
  5420. RVal))
  5421. return false;
  5422. Result.setFrom(Info.Ctx, RVal);
  5423. }
  5424. return true;
  5425. }
  5426. }
  5427. CallStackFrame *Frame = nullptr;
  5428. if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
  5429. // Only if a local variable was declared in the function currently being
  5430. // evaluated, do we expect to be able to find its value in the current
  5431. // frame. (Otherwise it was likely declared in an enclosing context and
  5432. // could either have a valid evaluatable value (for e.g. a constexpr
  5433. // variable) or be ill-formed (and trigger an appropriate evaluation
  5434. // diagnostic)).
  5435. if (Info.CurrentCall->Callee &&
  5436. Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
  5437. Frame = Info.CurrentCall;
  5438. }
  5439. }
  5440. if (!VD->getType()->isReferenceType()) {
  5441. if (Frame) {
  5442. Result.set({VD, Frame->Index,
  5443. Info.CurrentCall->getCurrentTemporaryVersion(VD)});
  5444. return true;
  5445. }
  5446. return Success(VD);
  5447. }
  5448. APValue *V;
  5449. if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
  5450. return false;
  5451. if (!V->hasValue()) {
  5452. // FIXME: Is it possible for V to be indeterminate here? If so, we should
  5453. // adjust the diagnostic to say that.
  5454. if (!Info.checkingPotentialConstantExpression())
  5455. Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
  5456. return false;
  5457. }
  5458. return Success(*V, E);
  5459. }
  5460. bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
  5461. const MaterializeTemporaryExpr *E) {
  5462. // Walk through the expression to find the materialized temporary itself.
  5463. SmallVector<const Expr *, 2> CommaLHSs;
  5464. SmallVector<SubobjectAdjustment, 2> Adjustments;
  5465. const Expr *Inner = E->GetTemporaryExpr()->
  5466. skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  5467. // If we passed any comma operators, evaluate their LHSs.
  5468. for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
  5469. if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
  5470. return false;
  5471. // A materialized temporary with static storage duration can appear within the
  5472. // result of a constant expression evaluation, so we need to preserve its
  5473. // value for use outside this evaluation.
  5474. APValue *Value;
  5475. if (E->getStorageDuration() == SD_Static) {
  5476. Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
  5477. *Value = APValue();
  5478. Result.set(E);
  5479. } else {
  5480. Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
  5481. *Info.CurrentCall);
  5482. }
  5483. QualType Type = Inner->getType();
  5484. // Materialize the temporary itself.
  5485. if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
  5486. (E->getStorageDuration() == SD_Static &&
  5487. !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
  5488. *Value = APValue();
  5489. return false;
  5490. }
  5491. // Adjust our lvalue to refer to the desired subobject.
  5492. for (unsigned I = Adjustments.size(); I != 0; /**/) {
  5493. --I;
  5494. switch (Adjustments[I].Kind) {
  5495. case SubobjectAdjustment::DerivedToBaseAdjustment:
  5496. if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
  5497. Type, Result))
  5498. return false;
  5499. Type = Adjustments[I].DerivedToBase.BasePath->getType();
  5500. break;
  5501. case SubobjectAdjustment::FieldAdjustment:
  5502. if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
  5503. return false;
  5504. Type = Adjustments[I].Field->getType();
  5505. break;
  5506. case SubobjectAdjustment::MemberPointerAdjustment:
  5507. if (!HandleMemberPointerAccess(this->Info, Type, Result,
  5508. Adjustments[I].Ptr.RHS))
  5509. return false;
  5510. Type = Adjustments[I].Ptr.MPT->getPointeeType();
  5511. break;
  5512. }
  5513. }
  5514. return true;
  5515. }
  5516. bool
  5517. LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  5518. assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
  5519. "lvalue compound literal in c++?");
  5520. // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
  5521. // only see this when folding in C, so there's no standard to follow here.
  5522. return Success(E);
  5523. }
  5524. bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  5525. TypeInfoLValue TypeInfo;
  5526. if (!E->isPotentiallyEvaluated()) {
  5527. if (E->isTypeOperand())
  5528. TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
  5529. else
  5530. TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
  5531. } else {
  5532. if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
  5533. Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
  5534. << E->getExprOperand()->getType()
  5535. << E->getExprOperand()->getSourceRange();
  5536. }
  5537. if (!Visit(E->getExprOperand()))
  5538. return false;
  5539. Optional<DynamicType> DynType =
  5540. ComputeDynamicType(Info, E, Result, AK_TypeId);
  5541. if (!DynType)
  5542. return false;
  5543. TypeInfo =
  5544. TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
  5545. }
  5546. return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
  5547. }
  5548. bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  5549. return Success(E);
  5550. }
  5551. bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
  5552. // Handle static data members.
  5553. if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
  5554. VisitIgnoredBaseExpression(E->getBase());
  5555. return VisitVarDecl(E, VD);
  5556. }
  5557. // Handle static member functions.
  5558. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
  5559. if (MD->isStatic()) {
  5560. VisitIgnoredBaseExpression(E->getBase());
  5561. return Success(MD);
  5562. }
  5563. }
  5564. // Handle non-static data members.
  5565. return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
  5566. }
  5567. bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
  5568. // FIXME: Deal with vectors as array subscript bases.
  5569. if (E->getBase()->getType()->isVectorType())
  5570. return Error(E);
  5571. bool Success = true;
  5572. if (!evaluatePointer(E->getBase(), Result)) {
  5573. if (!Info.noteFailure())
  5574. return false;
  5575. Success = false;
  5576. }
  5577. APSInt Index;
  5578. if (!EvaluateInteger(E->getIdx(), Index, Info))
  5579. return false;
  5580. return Success &&
  5581. HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
  5582. }
  5583. bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
  5584. return evaluatePointer(E->getSubExpr(), Result);
  5585. }
  5586. bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  5587. if (!Visit(E->getSubExpr()))
  5588. return false;
  5589. // __real is a no-op on scalar lvalues.
  5590. if (E->getSubExpr()->getType()->isAnyComplexType())
  5591. HandleLValueComplexElement(Info, E, Result, E->getType(), false);
  5592. return true;
  5593. }
  5594. bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  5595. assert(E->getSubExpr()->getType()->isAnyComplexType() &&
  5596. "lvalue __imag__ on scalar?");
  5597. if (!Visit(E->getSubExpr()))
  5598. return false;
  5599. HandleLValueComplexElement(Info, E, Result, E->getType(), true);
  5600. return true;
  5601. }
  5602. bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
  5603. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5604. return Error(UO);
  5605. if (!this->Visit(UO->getSubExpr()))
  5606. return false;
  5607. return handleIncDec(
  5608. this->Info, UO, Result, UO->getSubExpr()->getType(),
  5609. UO->isIncrementOp(), nullptr);
  5610. }
  5611. bool LValueExprEvaluator::VisitCompoundAssignOperator(
  5612. const CompoundAssignOperator *CAO) {
  5613. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5614. return Error(CAO);
  5615. APValue RHS;
  5616. // The overall lvalue result is the result of evaluating the LHS.
  5617. if (!this->Visit(CAO->getLHS())) {
  5618. if (Info.noteFailure())
  5619. Evaluate(RHS, this->Info, CAO->getRHS());
  5620. return false;
  5621. }
  5622. if (!Evaluate(RHS, this->Info, CAO->getRHS()))
  5623. return false;
  5624. return handleCompoundAssignment(
  5625. this->Info, CAO,
  5626. Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
  5627. CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
  5628. }
  5629. bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
  5630. if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
  5631. return Error(E);
  5632. APValue NewVal;
  5633. if (!this->Visit(E->getLHS())) {
  5634. if (Info.noteFailure())
  5635. Evaluate(NewVal, this->Info, E->getRHS());
  5636. return false;
  5637. }
  5638. if (!Evaluate(NewVal, this->Info, E->getRHS()))
  5639. return false;
  5640. if (Info.getLangOpts().CPlusPlus2a &&
  5641. !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
  5642. return false;
  5643. return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
  5644. NewVal);
  5645. }
  5646. //===----------------------------------------------------------------------===//
  5647. // Pointer Evaluation
  5648. //===----------------------------------------------------------------------===//
  5649. /// Attempts to compute the number of bytes available at the pointer
  5650. /// returned by a function with the alloc_size attribute. Returns true if we
  5651. /// were successful. Places an unsigned number into `Result`.
  5652. ///
  5653. /// This expects the given CallExpr to be a call to a function with an
  5654. /// alloc_size attribute.
  5655. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5656. const CallExpr *Call,
  5657. llvm::APInt &Result) {
  5658. const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
  5659. assert(AllocSize && AllocSize->getElemSizeParam().isValid());
  5660. unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
  5661. unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
  5662. if (Call->getNumArgs() <= SizeArgNo)
  5663. return false;
  5664. auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
  5665. Expr::EvalResult ExprResult;
  5666. if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
  5667. return false;
  5668. Into = ExprResult.Val.getInt();
  5669. if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
  5670. return false;
  5671. Into = Into.zextOrSelf(BitsInSizeT);
  5672. return true;
  5673. };
  5674. APSInt SizeOfElem;
  5675. if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
  5676. return false;
  5677. if (!AllocSize->getNumElemsParam().isValid()) {
  5678. Result = std::move(SizeOfElem);
  5679. return true;
  5680. }
  5681. APSInt NumberOfElems;
  5682. unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
  5683. if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
  5684. return false;
  5685. bool Overflow;
  5686. llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
  5687. if (Overflow)
  5688. return false;
  5689. Result = std::move(BytesAvailable);
  5690. return true;
  5691. }
  5692. /// Convenience function. LVal's base must be a call to an alloc_size
  5693. /// function.
  5694. static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
  5695. const LValue &LVal,
  5696. llvm::APInt &Result) {
  5697. assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  5698. "Can't get the size of a non alloc_size function");
  5699. const auto *Base = LVal.getLValueBase().get<const Expr *>();
  5700. const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
  5701. return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
  5702. }
  5703. /// Attempts to evaluate the given LValueBase as the result of a call to
  5704. /// a function with the alloc_size attribute. If it was possible to do so, this
  5705. /// function will return true, make Result's Base point to said function call,
  5706. /// and mark Result's Base as invalid.
  5707. static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
  5708. LValue &Result) {
  5709. if (Base.isNull())
  5710. return false;
  5711. // Because we do no form of static analysis, we only support const variables.
  5712. //
  5713. // Additionally, we can't support parameters, nor can we support static
  5714. // variables (in the latter case, use-before-assign isn't UB; in the former,
  5715. // we have no clue what they'll be assigned to).
  5716. const auto *VD =
  5717. dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
  5718. if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
  5719. return false;
  5720. const Expr *Init = VD->getAnyInitializer();
  5721. if (!Init)
  5722. return false;
  5723. const Expr *E = Init->IgnoreParens();
  5724. if (!tryUnwrapAllocSizeCall(E))
  5725. return false;
  5726. // Store E instead of E unwrapped so that the type of the LValue's base is
  5727. // what the user wanted.
  5728. Result.setInvalid(E);
  5729. QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
  5730. Result.addUnsizedArray(Info, E, Pointee);
  5731. return true;
  5732. }
  5733. namespace {
  5734. class PointerExprEvaluator
  5735. : public ExprEvaluatorBase<PointerExprEvaluator> {
  5736. LValue &Result;
  5737. bool InvalidBaseOK;
  5738. bool Success(const Expr *E) {
  5739. Result.set(E);
  5740. return true;
  5741. }
  5742. bool evaluateLValue(const Expr *E, LValue &Result) {
  5743. return EvaluateLValue(E, Result, Info, InvalidBaseOK);
  5744. }
  5745. bool evaluatePointer(const Expr *E, LValue &Result) {
  5746. return EvaluatePointer(E, Result, Info, InvalidBaseOK);
  5747. }
  5748. bool visitNonBuiltinCallExpr(const CallExpr *E);
  5749. public:
  5750. PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
  5751. : ExprEvaluatorBaseTy(info), Result(Result),
  5752. InvalidBaseOK(InvalidBaseOK) {}
  5753. bool Success(const APValue &V, const Expr *E) {
  5754. Result.setFrom(Info.Ctx, V);
  5755. return true;
  5756. }
  5757. bool ZeroInitialization(const Expr *E) {
  5758. auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
  5759. Result.setNull(E->getType(), TargetVal);
  5760. return true;
  5761. }
  5762. bool VisitBinaryOperator(const BinaryOperator *E);
  5763. bool VisitCastExpr(const CastExpr* E);
  5764. bool VisitUnaryAddrOf(const UnaryOperator *E);
  5765. bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
  5766. { return Success(E); }
  5767. bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  5768. if (E->isExpressibleAsConstantInitializer())
  5769. return Success(E);
  5770. if (Info.noteFailure())
  5771. EvaluateIgnoredValue(Info, E->getSubExpr());
  5772. return Error(E);
  5773. }
  5774. bool VisitAddrLabelExpr(const AddrLabelExpr *E)
  5775. { return Success(E); }
  5776. bool VisitCallExpr(const CallExpr *E);
  5777. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  5778. bool VisitBlockExpr(const BlockExpr *E) {
  5779. if (!E->getBlockDecl()->hasCaptures())
  5780. return Success(E);
  5781. return Error(E);
  5782. }
  5783. bool VisitCXXThisExpr(const CXXThisExpr *E) {
  5784. // Can't look at 'this' when checking a potential constant expression.
  5785. if (Info.checkingPotentialConstantExpression())
  5786. return false;
  5787. if (!Info.CurrentCall->This) {
  5788. if (Info.getLangOpts().CPlusPlus11)
  5789. Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
  5790. else
  5791. Info.FFDiag(E);
  5792. return false;
  5793. }
  5794. Result = *Info.CurrentCall->This;
  5795. // If we are inside a lambda's call operator, the 'this' expression refers
  5796. // to the enclosing '*this' object (either by value or reference) which is
  5797. // either copied into the closure object's field that represents the '*this'
  5798. // or refers to '*this'.
  5799. if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
  5800. // Update 'Result' to refer to the data member/field of the closure object
  5801. // that represents the '*this' capture.
  5802. if (!HandleLValueMember(Info, E, Result,
  5803. Info.CurrentCall->LambdaThisCaptureField))
  5804. return false;
  5805. // If we captured '*this' by reference, replace the field with its referent.
  5806. if (Info.CurrentCall->LambdaThisCaptureField->getType()
  5807. ->isPointerType()) {
  5808. APValue RVal;
  5809. if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
  5810. RVal))
  5811. return false;
  5812. Result.setFrom(Info.Ctx, RVal);
  5813. }
  5814. }
  5815. return true;
  5816. }
  5817. bool VisitSourceLocExpr(const SourceLocExpr *E) {
  5818. assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
  5819. APValue LValResult = E->EvaluateInContext(
  5820. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  5821. Result.setFrom(Info.Ctx, LValResult);
  5822. return true;
  5823. }
  5824. // FIXME: Missing: @protocol, @selector
  5825. };
  5826. } // end anonymous namespace
  5827. static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
  5828. bool InvalidBaseOK) {
  5829. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  5830. return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
  5831. }
  5832. bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  5833. if (E->getOpcode() != BO_Add &&
  5834. E->getOpcode() != BO_Sub)
  5835. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  5836. const Expr *PExp = E->getLHS();
  5837. const Expr *IExp = E->getRHS();
  5838. if (IExp->getType()->isPointerType())
  5839. std::swap(PExp, IExp);
  5840. bool EvalPtrOK = evaluatePointer(PExp, Result);
  5841. if (!EvalPtrOK && !Info.noteFailure())
  5842. return false;
  5843. llvm::APSInt Offset;
  5844. if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
  5845. return false;
  5846. if (E->getOpcode() == BO_Sub)
  5847. negateAsSigned(Offset);
  5848. QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
  5849. return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
  5850. }
  5851. bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  5852. return evaluateLValue(E->getSubExpr(), Result);
  5853. }
  5854. bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  5855. const Expr *SubExpr = E->getSubExpr();
  5856. switch (E->getCastKind()) {
  5857. default:
  5858. break;
  5859. case CK_BitCast:
  5860. case CK_CPointerToObjCPointerCast:
  5861. case CK_BlockPointerToObjCPointerCast:
  5862. case CK_AnyPointerToBlockPointerCast:
  5863. case CK_AddressSpaceConversion:
  5864. if (!Visit(SubExpr))
  5865. return false;
  5866. // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
  5867. // permitted in constant expressions in C++11. Bitcasts from cv void* are
  5868. // also static_casts, but we disallow them as a resolution to DR1312.
  5869. if (!E->getType()->isVoidPointerType()) {
  5870. Result.Designator.setInvalid();
  5871. if (SubExpr->getType()->isVoidPointerType())
  5872. CCEDiag(E, diag::note_constexpr_invalid_cast)
  5873. << 3 << SubExpr->getType();
  5874. else
  5875. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5876. }
  5877. if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
  5878. ZeroInitialization(E);
  5879. return true;
  5880. case CK_DerivedToBase:
  5881. case CK_UncheckedDerivedToBase:
  5882. if (!evaluatePointer(E->getSubExpr(), Result))
  5883. return false;
  5884. if (!Result.Base && Result.Offset.isZero())
  5885. return true;
  5886. // Now figure out the necessary offset to add to the base LV to get from
  5887. // the derived class to the base class.
  5888. return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
  5889. castAs<PointerType>()->getPointeeType(),
  5890. Result);
  5891. case CK_BaseToDerived:
  5892. if (!Visit(E->getSubExpr()))
  5893. return false;
  5894. if (!Result.Base && Result.Offset.isZero())
  5895. return true;
  5896. return HandleBaseToDerivedCast(Info, E, Result);
  5897. case CK_Dynamic:
  5898. if (!Visit(E->getSubExpr()))
  5899. return false;
  5900. return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
  5901. case CK_NullToPointer:
  5902. VisitIgnoredValue(E->getSubExpr());
  5903. return ZeroInitialization(E);
  5904. case CK_IntegralToPointer: {
  5905. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  5906. APValue Value;
  5907. if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
  5908. break;
  5909. if (Value.isInt()) {
  5910. unsigned Size = Info.Ctx.getTypeSize(E->getType());
  5911. uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
  5912. Result.Base = (Expr*)nullptr;
  5913. Result.InvalidBase = false;
  5914. Result.Offset = CharUnits::fromQuantity(N);
  5915. Result.Designator.setInvalid();
  5916. Result.IsNullPtr = false;
  5917. return true;
  5918. } else {
  5919. // Cast is of an lvalue, no need to change value.
  5920. Result.setFrom(Info.Ctx, Value);
  5921. return true;
  5922. }
  5923. }
  5924. case CK_ArrayToPointerDecay: {
  5925. if (SubExpr->isGLValue()) {
  5926. if (!evaluateLValue(SubExpr, Result))
  5927. return false;
  5928. } else {
  5929. APValue &Value = createTemporary(SubExpr, false, Result,
  5930. *Info.CurrentCall);
  5931. if (!EvaluateInPlace(Value, Info, Result, SubExpr))
  5932. return false;
  5933. }
  5934. // The result is a pointer to the first element of the array.
  5935. auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
  5936. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5937. Result.addArray(Info, E, CAT);
  5938. else
  5939. Result.addUnsizedArray(Info, E, AT->getElementType());
  5940. return true;
  5941. }
  5942. case CK_FunctionToPointerDecay:
  5943. return evaluateLValue(SubExpr, Result);
  5944. case CK_LValueToRValue: {
  5945. LValue LVal;
  5946. if (!evaluateLValue(E->getSubExpr(), LVal))
  5947. return false;
  5948. APValue RVal;
  5949. // Note, we use the subexpression's type in order to retain cv-qualifiers.
  5950. if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
  5951. LVal, RVal))
  5952. return InvalidBaseOK &&
  5953. evaluateLValueAsAllocSize(Info, LVal.Base, Result);
  5954. return Success(RVal, E);
  5955. }
  5956. }
  5957. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  5958. }
  5959. static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
  5960. UnaryExprOrTypeTrait ExprKind) {
  5961. // C++ [expr.alignof]p3:
  5962. // When alignof is applied to a reference type, the result is the
  5963. // alignment of the referenced type.
  5964. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  5965. T = Ref->getPointeeType();
  5966. if (T.getQualifiers().hasUnaligned())
  5967. return CharUnits::One();
  5968. const bool AlignOfReturnsPreferred =
  5969. Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
  5970. // __alignof is defined to return the preferred alignment.
  5971. // Before 8, clang returned the preferred alignment for alignof and _Alignof
  5972. // as well.
  5973. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
  5974. return Info.Ctx.toCharUnitsFromBits(
  5975. Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
  5976. // alignof and _Alignof are defined to return the ABI alignment.
  5977. else if (ExprKind == UETT_AlignOf)
  5978. return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
  5979. else
  5980. llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
  5981. }
  5982. static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
  5983. UnaryExprOrTypeTrait ExprKind) {
  5984. E = E->IgnoreParens();
  5985. // The kinds of expressions that we have special-case logic here for
  5986. // should be kept up to date with the special checks for those
  5987. // expressions in Sema.
  5988. // alignof decl is always accepted, even if it doesn't make sense: we default
  5989. // to 1 in those cases.
  5990. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5991. return Info.Ctx.getDeclAlign(DRE->getDecl(),
  5992. /*RefAsPointee*/true);
  5993. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  5994. return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
  5995. /*RefAsPointee*/true);
  5996. return GetAlignOfType(Info, E->getType(), ExprKind);
  5997. }
  5998. // To be clear: this happily visits unsupported builtins. Better name welcomed.
  5999. bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
  6000. if (ExprEvaluatorBaseTy::VisitCallExpr(E))
  6001. return true;
  6002. if (!(InvalidBaseOK && getAllocSizeAttr(E)))
  6003. return false;
  6004. Result.setInvalid(E);
  6005. QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
  6006. Result.addUnsizedArray(Info, E, PointeeTy);
  6007. return true;
  6008. }
  6009. bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
  6010. if (IsStringLiteralCall(E))
  6011. return Success(E);
  6012. if (unsigned BuiltinOp = E->getBuiltinCallee())
  6013. return VisitBuiltinCallExpr(E, BuiltinOp);
  6014. return visitNonBuiltinCallExpr(E);
  6015. }
  6016. bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  6017. unsigned BuiltinOp) {
  6018. switch (BuiltinOp) {
  6019. case Builtin::BI__builtin_addressof:
  6020. return evaluateLValue(E->getArg(0), Result);
  6021. case Builtin::BI__builtin_assume_aligned: {
  6022. // We need to be very careful here because: if the pointer does not have the
  6023. // asserted alignment, then the behavior is undefined, and undefined
  6024. // behavior is non-constant.
  6025. if (!evaluatePointer(E->getArg(0), Result))
  6026. return false;
  6027. LValue OffsetResult(Result);
  6028. APSInt Alignment;
  6029. if (!EvaluateInteger(E->getArg(1), Alignment, Info))
  6030. return false;
  6031. CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
  6032. if (E->getNumArgs() > 2) {
  6033. APSInt Offset;
  6034. if (!EvaluateInteger(E->getArg(2), Offset, Info))
  6035. return false;
  6036. int64_t AdditionalOffset = -Offset.getZExtValue();
  6037. OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
  6038. }
  6039. // If there is a base object, then it must have the correct alignment.
  6040. if (OffsetResult.Base) {
  6041. CharUnits BaseAlignment;
  6042. if (const ValueDecl *VD =
  6043. OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
  6044. BaseAlignment = Info.Ctx.getDeclAlign(VD);
  6045. } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
  6046. BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
  6047. } else {
  6048. BaseAlignment = GetAlignOfType(
  6049. Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
  6050. }
  6051. if (BaseAlignment < Align) {
  6052. Result.Designator.setInvalid();
  6053. // FIXME: Add support to Diagnostic for long / long long.
  6054. CCEDiag(E->getArg(0),
  6055. diag::note_constexpr_baa_insufficient_alignment) << 0
  6056. << (unsigned)BaseAlignment.getQuantity()
  6057. << (unsigned)Align.getQuantity();
  6058. return false;
  6059. }
  6060. }
  6061. // The offset must also have the correct alignment.
  6062. if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
  6063. Result.Designator.setInvalid();
  6064. (OffsetResult.Base
  6065. ? CCEDiag(E->getArg(0),
  6066. diag::note_constexpr_baa_insufficient_alignment) << 1
  6067. : CCEDiag(E->getArg(0),
  6068. diag::note_constexpr_baa_value_insufficient_alignment))
  6069. << (int)OffsetResult.Offset.getQuantity()
  6070. << (unsigned)Align.getQuantity();
  6071. return false;
  6072. }
  6073. return true;
  6074. }
  6075. case Builtin::BI__builtin_launder:
  6076. return evaluatePointer(E->getArg(0), Result);
  6077. case Builtin::BIstrchr:
  6078. case Builtin::BIwcschr:
  6079. case Builtin::BImemchr:
  6080. case Builtin::BIwmemchr:
  6081. if (Info.getLangOpts().CPlusPlus11)
  6082. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6083. << /*isConstexpr*/0 << /*isConstructor*/0
  6084. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6085. else
  6086. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6087. LLVM_FALLTHROUGH;
  6088. case Builtin::BI__builtin_strchr:
  6089. case Builtin::BI__builtin_wcschr:
  6090. case Builtin::BI__builtin_memchr:
  6091. case Builtin::BI__builtin_char_memchr:
  6092. case Builtin::BI__builtin_wmemchr: {
  6093. if (!Visit(E->getArg(0)))
  6094. return false;
  6095. APSInt Desired;
  6096. if (!EvaluateInteger(E->getArg(1), Desired, Info))
  6097. return false;
  6098. uint64_t MaxLength = uint64_t(-1);
  6099. if (BuiltinOp != Builtin::BIstrchr &&
  6100. BuiltinOp != Builtin::BIwcschr &&
  6101. BuiltinOp != Builtin::BI__builtin_strchr &&
  6102. BuiltinOp != Builtin::BI__builtin_wcschr) {
  6103. APSInt N;
  6104. if (!EvaluateInteger(E->getArg(2), N, Info))
  6105. return false;
  6106. MaxLength = N.getExtValue();
  6107. }
  6108. // We cannot find the value if there are no candidates to match against.
  6109. if (MaxLength == 0u)
  6110. return ZeroInitialization(E);
  6111. if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  6112. Result.Designator.Invalid)
  6113. return false;
  6114. QualType CharTy = Result.Designator.getType(Info.Ctx);
  6115. bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
  6116. BuiltinOp == Builtin::BI__builtin_memchr;
  6117. assert(IsRawByte ||
  6118. Info.Ctx.hasSameUnqualifiedType(
  6119. CharTy, E->getArg(0)->getType()->getPointeeType()));
  6120. // Pointers to const void may point to objects of incomplete type.
  6121. if (IsRawByte && CharTy->isIncompleteType()) {
  6122. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
  6123. return false;
  6124. }
  6125. // Give up on byte-oriented matching against multibyte elements.
  6126. // FIXME: We can compare the bytes in the correct order.
  6127. if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
  6128. return false;
  6129. // Figure out what value we're actually looking for (after converting to
  6130. // the corresponding unsigned type if necessary).
  6131. uint64_t DesiredVal;
  6132. bool StopAtNull = false;
  6133. switch (BuiltinOp) {
  6134. case Builtin::BIstrchr:
  6135. case Builtin::BI__builtin_strchr:
  6136. // strchr compares directly to the passed integer, and therefore
  6137. // always fails if given an int that is not a char.
  6138. if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
  6139. E->getArg(1)->getType(),
  6140. Desired),
  6141. Desired))
  6142. return ZeroInitialization(E);
  6143. StopAtNull = true;
  6144. LLVM_FALLTHROUGH;
  6145. case Builtin::BImemchr:
  6146. case Builtin::BI__builtin_memchr:
  6147. case Builtin::BI__builtin_char_memchr:
  6148. // memchr compares by converting both sides to unsigned char. That's also
  6149. // correct for strchr if we get this far (to cope with plain char being
  6150. // unsigned in the strchr case).
  6151. DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
  6152. break;
  6153. case Builtin::BIwcschr:
  6154. case Builtin::BI__builtin_wcschr:
  6155. StopAtNull = true;
  6156. LLVM_FALLTHROUGH;
  6157. case Builtin::BIwmemchr:
  6158. case Builtin::BI__builtin_wmemchr:
  6159. // wcschr and wmemchr are given a wchar_t to look for. Just use it.
  6160. DesiredVal = Desired.getZExtValue();
  6161. break;
  6162. }
  6163. for (; MaxLength; --MaxLength) {
  6164. APValue Char;
  6165. if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
  6166. !Char.isInt())
  6167. return false;
  6168. if (Char.getInt().getZExtValue() == DesiredVal)
  6169. return true;
  6170. if (StopAtNull && !Char.getInt())
  6171. break;
  6172. if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
  6173. return false;
  6174. }
  6175. // Not found: return nullptr.
  6176. return ZeroInitialization(E);
  6177. }
  6178. case Builtin::BImemcpy:
  6179. case Builtin::BImemmove:
  6180. case Builtin::BIwmemcpy:
  6181. case Builtin::BIwmemmove:
  6182. if (Info.getLangOpts().CPlusPlus11)
  6183. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  6184. << /*isConstexpr*/0 << /*isConstructor*/0
  6185. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  6186. else
  6187. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  6188. LLVM_FALLTHROUGH;
  6189. case Builtin::BI__builtin_memcpy:
  6190. case Builtin::BI__builtin_memmove:
  6191. case Builtin::BI__builtin_wmemcpy:
  6192. case Builtin::BI__builtin_wmemmove: {
  6193. bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
  6194. BuiltinOp == Builtin::BIwmemmove ||
  6195. BuiltinOp == Builtin::BI__builtin_wmemcpy ||
  6196. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6197. bool Move = BuiltinOp == Builtin::BImemmove ||
  6198. BuiltinOp == Builtin::BIwmemmove ||
  6199. BuiltinOp == Builtin::BI__builtin_memmove ||
  6200. BuiltinOp == Builtin::BI__builtin_wmemmove;
  6201. // The result of mem* is the first argument.
  6202. if (!Visit(E->getArg(0)))
  6203. return false;
  6204. LValue Dest = Result;
  6205. LValue Src;
  6206. if (!EvaluatePointer(E->getArg(1), Src, Info))
  6207. return false;
  6208. APSInt N;
  6209. if (!EvaluateInteger(E->getArg(2), N, Info))
  6210. return false;
  6211. assert(!N.isSigned() && "memcpy and friends take an unsigned size");
  6212. // If the size is zero, we treat this as always being a valid no-op.
  6213. // (Even if one of the src and dest pointers is null.)
  6214. if (!N)
  6215. return true;
  6216. // Otherwise, if either of the operands is null, we can't proceed. Don't
  6217. // try to determine the type of the copied objects, because there aren't
  6218. // any.
  6219. if (!Src.Base || !Dest.Base) {
  6220. APValue Val;
  6221. (!Src.Base ? Src : Dest).moveInto(Val);
  6222. Info.FFDiag(E, diag::note_constexpr_memcpy_null)
  6223. << Move << WChar << !!Src.Base
  6224. << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
  6225. return false;
  6226. }
  6227. if (Src.Designator.Invalid || Dest.Designator.Invalid)
  6228. return false;
  6229. // We require that Src and Dest are both pointers to arrays of
  6230. // trivially-copyable type. (For the wide version, the designator will be
  6231. // invalid if the designated object is not a wchar_t.)
  6232. QualType T = Dest.Designator.getType(Info.Ctx);
  6233. QualType SrcT = Src.Designator.getType(Info.Ctx);
  6234. if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
  6235. Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
  6236. return false;
  6237. }
  6238. if (T->isIncompleteType()) {
  6239. Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
  6240. return false;
  6241. }
  6242. if (!T.isTriviallyCopyableType(Info.Ctx)) {
  6243. Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
  6244. return false;
  6245. }
  6246. // Figure out how many T's we're copying.
  6247. uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
  6248. if (!WChar) {
  6249. uint64_t Remainder;
  6250. llvm::APInt OrigN = N;
  6251. llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
  6252. if (Remainder) {
  6253. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6254. << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
  6255. << (unsigned)TSize;
  6256. return false;
  6257. }
  6258. }
  6259. // Check that the copying will remain within the arrays, just so that we
  6260. // can give a more meaningful diagnostic. This implicitly also checks that
  6261. // N fits into 64 bits.
  6262. uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
  6263. uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
  6264. if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
  6265. Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
  6266. << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
  6267. << N.toString(10, /*Signed*/false);
  6268. return false;
  6269. }
  6270. uint64_t NElems = N.getZExtValue();
  6271. uint64_t NBytes = NElems * TSize;
  6272. // Check for overlap.
  6273. int Direction = 1;
  6274. if (HasSameBase(Src, Dest)) {
  6275. uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
  6276. uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
  6277. if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
  6278. // Dest is inside the source region.
  6279. if (!Move) {
  6280. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6281. return false;
  6282. }
  6283. // For memmove and friends, copy backwards.
  6284. if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
  6285. !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
  6286. return false;
  6287. Direction = -1;
  6288. } else if (!Move && SrcOffset >= DestOffset &&
  6289. SrcOffset - DestOffset < NBytes) {
  6290. // Src is inside the destination region for memcpy: invalid.
  6291. Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
  6292. return false;
  6293. }
  6294. }
  6295. while (true) {
  6296. APValue Val;
  6297. if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
  6298. !handleAssignment(Info, E, Dest, T, Val))
  6299. return false;
  6300. // Do not iterate past the last element; if we're copying backwards, that
  6301. // might take us off the start of the array.
  6302. if (--NElems == 0)
  6303. return true;
  6304. if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
  6305. !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
  6306. return false;
  6307. }
  6308. }
  6309. default:
  6310. return visitNonBuiltinCallExpr(E);
  6311. }
  6312. }
  6313. //===----------------------------------------------------------------------===//
  6314. // Member Pointer Evaluation
  6315. //===----------------------------------------------------------------------===//
  6316. namespace {
  6317. class MemberPointerExprEvaluator
  6318. : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
  6319. MemberPtr &Result;
  6320. bool Success(const ValueDecl *D) {
  6321. Result = MemberPtr(D);
  6322. return true;
  6323. }
  6324. public:
  6325. MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
  6326. : ExprEvaluatorBaseTy(Info), Result(Result) {}
  6327. bool Success(const APValue &V, const Expr *E) {
  6328. Result.setFrom(V);
  6329. return true;
  6330. }
  6331. bool ZeroInitialization(const Expr *E) {
  6332. return Success((const ValueDecl*)nullptr);
  6333. }
  6334. bool VisitCastExpr(const CastExpr *E);
  6335. bool VisitUnaryAddrOf(const UnaryOperator *E);
  6336. };
  6337. } // end anonymous namespace
  6338. static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
  6339. EvalInfo &Info) {
  6340. assert(E->isRValue() && E->getType()->isMemberPointerType());
  6341. return MemberPointerExprEvaluator(Info, Result).Visit(E);
  6342. }
  6343. bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6344. switch (E->getCastKind()) {
  6345. default:
  6346. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6347. case CK_NullToMemberPointer:
  6348. VisitIgnoredValue(E->getSubExpr());
  6349. return ZeroInitialization(E);
  6350. case CK_BaseToDerivedMemberPointer: {
  6351. if (!Visit(E->getSubExpr()))
  6352. return false;
  6353. if (E->path_empty())
  6354. return true;
  6355. // Base-to-derived member pointer casts store the path in derived-to-base
  6356. // order, so iterate backwards. The CXXBaseSpecifier also provides us with
  6357. // the wrong end of the derived->base arc, so stagger the path by one class.
  6358. typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
  6359. for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
  6360. PathI != PathE; ++PathI) {
  6361. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6362. const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
  6363. if (!Result.castToDerived(Derived))
  6364. return Error(E);
  6365. }
  6366. const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
  6367. if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
  6368. return Error(E);
  6369. return true;
  6370. }
  6371. case CK_DerivedToBaseMemberPointer:
  6372. if (!Visit(E->getSubExpr()))
  6373. return false;
  6374. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6375. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6376. assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
  6377. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6378. if (!Result.castToBase(Base))
  6379. return Error(E);
  6380. }
  6381. return true;
  6382. }
  6383. }
  6384. bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
  6385. // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
  6386. // member can be formed.
  6387. return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
  6388. }
  6389. //===----------------------------------------------------------------------===//
  6390. // Record Evaluation
  6391. //===----------------------------------------------------------------------===//
  6392. namespace {
  6393. class RecordExprEvaluator
  6394. : public ExprEvaluatorBase<RecordExprEvaluator> {
  6395. const LValue &This;
  6396. APValue &Result;
  6397. public:
  6398. RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
  6399. : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
  6400. bool Success(const APValue &V, const Expr *E) {
  6401. Result = V;
  6402. return true;
  6403. }
  6404. bool ZeroInitialization(const Expr *E) {
  6405. return ZeroInitialization(E, E->getType());
  6406. }
  6407. bool ZeroInitialization(const Expr *E, QualType T);
  6408. bool VisitCallExpr(const CallExpr *E) {
  6409. return handleCallExpr(E, Result, &This);
  6410. }
  6411. bool VisitCastExpr(const CastExpr *E);
  6412. bool VisitInitListExpr(const InitListExpr *E);
  6413. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6414. return VisitCXXConstructExpr(E, E->getType());
  6415. }
  6416. bool VisitLambdaExpr(const LambdaExpr *E);
  6417. bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  6418. bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
  6419. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
  6420. bool VisitBinCmp(const BinaryOperator *E);
  6421. };
  6422. }
  6423. /// Perform zero-initialization on an object of non-union class type.
  6424. /// C++11 [dcl.init]p5:
  6425. /// To zero-initialize an object or reference of type T means:
  6426. /// [...]
  6427. /// -- if T is a (possibly cv-qualified) non-union class type,
  6428. /// each non-static data member and each base-class subobject is
  6429. /// zero-initialized
  6430. static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
  6431. const RecordDecl *RD,
  6432. const LValue &This, APValue &Result) {
  6433. assert(!RD->isUnion() && "Expected non-union class type");
  6434. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  6435. Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
  6436. std::distance(RD->field_begin(), RD->field_end()));
  6437. if (RD->isInvalidDecl()) return false;
  6438. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6439. if (CD) {
  6440. unsigned Index = 0;
  6441. for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
  6442. End = CD->bases_end(); I != End; ++I, ++Index) {
  6443. const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
  6444. LValue Subobject = This;
  6445. if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
  6446. return false;
  6447. if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
  6448. Result.getStructBase(Index)))
  6449. return false;
  6450. }
  6451. }
  6452. for (const auto *I : RD->fields()) {
  6453. // -- if T is a reference type, no initialization is performed.
  6454. if (I->getType()->isReferenceType())
  6455. continue;
  6456. LValue Subobject = This;
  6457. if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
  6458. return false;
  6459. ImplicitValueInitExpr VIE(I->getType());
  6460. if (!EvaluateInPlace(
  6461. Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
  6462. return false;
  6463. }
  6464. return true;
  6465. }
  6466. bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
  6467. const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
  6468. if (RD->isInvalidDecl()) return false;
  6469. if (RD->isUnion()) {
  6470. // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
  6471. // object's first non-static named data member is zero-initialized
  6472. RecordDecl::field_iterator I = RD->field_begin();
  6473. if (I == RD->field_end()) {
  6474. Result = APValue((const FieldDecl*)nullptr);
  6475. return true;
  6476. }
  6477. LValue Subobject = This;
  6478. if (!HandleLValueMember(Info, E, Subobject, *I))
  6479. return false;
  6480. Result = APValue(*I);
  6481. ImplicitValueInitExpr VIE(I->getType());
  6482. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
  6483. }
  6484. if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
  6485. Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
  6486. return false;
  6487. }
  6488. return HandleClassZeroInitialization(Info, E, RD, This, Result);
  6489. }
  6490. bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6491. switch (E->getCastKind()) {
  6492. default:
  6493. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6494. case CK_ConstructorConversion:
  6495. return Visit(E->getSubExpr());
  6496. case CK_DerivedToBase:
  6497. case CK_UncheckedDerivedToBase: {
  6498. APValue DerivedObject;
  6499. if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
  6500. return false;
  6501. if (!DerivedObject.isStruct())
  6502. return Error(E->getSubExpr());
  6503. // Derived-to-base rvalue conversion: just slice off the derived part.
  6504. APValue *Value = &DerivedObject;
  6505. const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
  6506. for (CastExpr::path_const_iterator PathI = E->path_begin(),
  6507. PathE = E->path_end(); PathI != PathE; ++PathI) {
  6508. assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
  6509. const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
  6510. Value = &Value->getStructBase(getBaseIndex(RD, Base));
  6511. RD = Base;
  6512. }
  6513. Result = *Value;
  6514. return true;
  6515. }
  6516. }
  6517. }
  6518. bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6519. if (E->isTransparent())
  6520. return Visit(E->getInit(0));
  6521. const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
  6522. if (RD->isInvalidDecl()) return false;
  6523. const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
  6524. auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  6525. EvalInfo::EvaluatingConstructorRAII EvalObj(
  6526. Info,
  6527. ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
  6528. CXXRD && CXXRD->getNumBases());
  6529. if (RD->isUnion()) {
  6530. const FieldDecl *Field = E->getInitializedFieldInUnion();
  6531. Result = APValue(Field);
  6532. if (!Field)
  6533. return true;
  6534. // If the initializer list for a union does not contain any elements, the
  6535. // first element of the union is value-initialized.
  6536. // FIXME: The element should be initialized from an initializer list.
  6537. // Is this difference ever observable for initializer lists which
  6538. // we don't build?
  6539. ImplicitValueInitExpr VIE(Field->getType());
  6540. const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
  6541. LValue Subobject = This;
  6542. if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
  6543. return false;
  6544. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6545. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6546. isa<CXXDefaultInitExpr>(InitExpr));
  6547. return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
  6548. }
  6549. if (!Result.hasValue())
  6550. Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
  6551. std::distance(RD->field_begin(), RD->field_end()));
  6552. unsigned ElementNo = 0;
  6553. bool Success = true;
  6554. // Initialize base classes.
  6555. if (CXXRD && CXXRD->getNumBases()) {
  6556. for (const auto &Base : CXXRD->bases()) {
  6557. assert(ElementNo < E->getNumInits() && "missing init for base class");
  6558. const Expr *Init = E->getInit(ElementNo);
  6559. LValue Subobject = This;
  6560. if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
  6561. return false;
  6562. APValue &FieldVal = Result.getStructBase(ElementNo);
  6563. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
  6564. if (!Info.noteFailure())
  6565. return false;
  6566. Success = false;
  6567. }
  6568. ++ElementNo;
  6569. }
  6570. EvalObj.finishedConstructingBases();
  6571. }
  6572. // Initialize members.
  6573. for (const auto *Field : RD->fields()) {
  6574. // Anonymous bit-fields are not considered members of the class for
  6575. // purposes of aggregate initialization.
  6576. if (Field->isUnnamedBitfield())
  6577. continue;
  6578. LValue Subobject = This;
  6579. bool HaveInit = ElementNo < E->getNumInits();
  6580. // FIXME: Diagnostics here should point to the end of the initializer
  6581. // list, not the start.
  6582. if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
  6583. Subobject, Field, &Layout))
  6584. return false;
  6585. // Perform an implicit value-initialization for members beyond the end of
  6586. // the initializer list.
  6587. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
  6588. const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
  6589. // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
  6590. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
  6591. isa<CXXDefaultInitExpr>(Init));
  6592. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  6593. if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
  6594. (Field->isBitField() && !truncateBitfieldValue(Info, Init,
  6595. FieldVal, Field))) {
  6596. if (!Info.noteFailure())
  6597. return false;
  6598. Success = false;
  6599. }
  6600. }
  6601. return Success;
  6602. }
  6603. bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  6604. QualType T) {
  6605. // Note that E's type is not necessarily the type of our class here; we might
  6606. // be initializing an array element instead.
  6607. const CXXConstructorDecl *FD = E->getConstructor();
  6608. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
  6609. bool ZeroInit = E->requiresZeroInitialization();
  6610. if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
  6611. // If we've already performed zero-initialization, we're already done.
  6612. if (Result.hasValue())
  6613. return true;
  6614. // We can get here in two different ways:
  6615. // 1) We're performing value-initialization, and should zero-initialize
  6616. // the object, or
  6617. // 2) We're performing default-initialization of an object with a trivial
  6618. // constexpr default constructor, in which case we should start the
  6619. // lifetimes of all the base subobjects (there can be no data member
  6620. // subobjects in this case) per [basic.life]p1.
  6621. // Either way, ZeroInitialization is appropriate.
  6622. return ZeroInitialization(E, T);
  6623. }
  6624. const FunctionDecl *Definition = nullptr;
  6625. auto Body = FD->getBody(Definition);
  6626. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  6627. return false;
  6628. // Avoid materializing a temporary for an elidable copy/move constructor.
  6629. if (E->isElidable() && !ZeroInit)
  6630. if (const MaterializeTemporaryExpr *ME
  6631. = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
  6632. return Visit(ME->GetTemporaryExpr());
  6633. if (ZeroInit && !ZeroInitialization(E, T))
  6634. return false;
  6635. auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
  6636. return HandleConstructorCall(E, This, Args,
  6637. cast<CXXConstructorDecl>(Definition), Info,
  6638. Result);
  6639. }
  6640. bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
  6641. const CXXInheritedCtorInitExpr *E) {
  6642. if (!Info.CurrentCall) {
  6643. assert(Info.checkingPotentialConstantExpression());
  6644. return false;
  6645. }
  6646. const CXXConstructorDecl *FD = E->getConstructor();
  6647. if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
  6648. return false;
  6649. const FunctionDecl *Definition = nullptr;
  6650. auto Body = FD->getBody(Definition);
  6651. if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
  6652. return false;
  6653. return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
  6654. cast<CXXConstructorDecl>(Definition), Info,
  6655. Result);
  6656. }
  6657. bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
  6658. const CXXStdInitializerListExpr *E) {
  6659. const ConstantArrayType *ArrayType =
  6660. Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  6661. LValue Array;
  6662. if (!EvaluateLValue(E->getSubExpr(), Array, Info))
  6663. return false;
  6664. // Get a pointer to the first element of the array.
  6665. Array.addArray(Info, E, ArrayType);
  6666. // FIXME: Perform the checks on the field types in SemaInit.
  6667. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  6668. RecordDecl::field_iterator Field = Record->field_begin();
  6669. if (Field == Record->field_end())
  6670. return Error(E);
  6671. // Start pointer.
  6672. if (!Field->getType()->isPointerType() ||
  6673. !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  6674. ArrayType->getElementType()))
  6675. return Error(E);
  6676. // FIXME: What if the initializer_list type has base classes, etc?
  6677. Result = APValue(APValue::UninitStruct(), 0, 2);
  6678. Array.moveInto(Result.getStructField(0));
  6679. if (++Field == Record->field_end())
  6680. return Error(E);
  6681. if (Field->getType()->isPointerType() &&
  6682. Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
  6683. ArrayType->getElementType())) {
  6684. // End pointer.
  6685. if (!HandleLValueArrayAdjustment(Info, E, Array,
  6686. ArrayType->getElementType(),
  6687. ArrayType->getSize().getZExtValue()))
  6688. return false;
  6689. Array.moveInto(Result.getStructField(1));
  6690. } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
  6691. // Length.
  6692. Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
  6693. else
  6694. return Error(E);
  6695. if (++Field != Record->field_end())
  6696. return Error(E);
  6697. return true;
  6698. }
  6699. bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
  6700. const CXXRecordDecl *ClosureClass = E->getLambdaClass();
  6701. if (ClosureClass->isInvalidDecl()) return false;
  6702. if (Info.checkingPotentialConstantExpression()) return true;
  6703. const size_t NumFields =
  6704. std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
  6705. assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
  6706. E->capture_init_end()) &&
  6707. "The number of lambda capture initializers should equal the number of "
  6708. "fields within the closure type");
  6709. Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
  6710. // Iterate through all the lambda's closure object's fields and initialize
  6711. // them.
  6712. auto *CaptureInitIt = E->capture_init_begin();
  6713. const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
  6714. bool Success = true;
  6715. for (const auto *Field : ClosureClass->fields()) {
  6716. assert(CaptureInitIt != E->capture_init_end());
  6717. // Get the initializer for this field
  6718. Expr *const CurFieldInit = *CaptureInitIt++;
  6719. // If there is no initializer, either this is a VLA or an error has
  6720. // occurred.
  6721. if (!CurFieldInit)
  6722. return Error(E);
  6723. APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
  6724. if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
  6725. if (!Info.keepEvaluatingAfterFailure())
  6726. return false;
  6727. Success = false;
  6728. }
  6729. ++CaptureIt;
  6730. }
  6731. return Success;
  6732. }
  6733. static bool EvaluateRecord(const Expr *E, const LValue &This,
  6734. APValue &Result, EvalInfo &Info) {
  6735. assert(E->isRValue() && E->getType()->isRecordType() &&
  6736. "can't evaluate expression as a record rvalue");
  6737. return RecordExprEvaluator(Info, This, Result).Visit(E);
  6738. }
  6739. //===----------------------------------------------------------------------===//
  6740. // Temporary Evaluation
  6741. //
  6742. // Temporaries are represented in the AST as rvalues, but generally behave like
  6743. // lvalues. The full-object of which the temporary is a subobject is implicitly
  6744. // materialized so that a reference can bind to it.
  6745. //===----------------------------------------------------------------------===//
  6746. namespace {
  6747. class TemporaryExprEvaluator
  6748. : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
  6749. public:
  6750. TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
  6751. LValueExprEvaluatorBaseTy(Info, Result, false) {}
  6752. /// Visit an expression which constructs the value of this temporary.
  6753. bool VisitConstructExpr(const Expr *E) {
  6754. APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
  6755. return EvaluateInPlace(Value, Info, Result, E);
  6756. }
  6757. bool VisitCastExpr(const CastExpr *E) {
  6758. switch (E->getCastKind()) {
  6759. default:
  6760. return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
  6761. case CK_ConstructorConversion:
  6762. return VisitConstructExpr(E->getSubExpr());
  6763. }
  6764. }
  6765. bool VisitInitListExpr(const InitListExpr *E) {
  6766. return VisitConstructExpr(E);
  6767. }
  6768. bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
  6769. return VisitConstructExpr(E);
  6770. }
  6771. bool VisitCallExpr(const CallExpr *E) {
  6772. return VisitConstructExpr(E);
  6773. }
  6774. bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
  6775. return VisitConstructExpr(E);
  6776. }
  6777. bool VisitLambdaExpr(const LambdaExpr *E) {
  6778. return VisitConstructExpr(E);
  6779. }
  6780. };
  6781. } // end anonymous namespace
  6782. /// Evaluate an expression of record type as a temporary.
  6783. static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
  6784. assert(E->isRValue() && E->getType()->isRecordType());
  6785. return TemporaryExprEvaluator(Info, Result).Visit(E);
  6786. }
  6787. //===----------------------------------------------------------------------===//
  6788. // Vector Evaluation
  6789. //===----------------------------------------------------------------------===//
  6790. namespace {
  6791. class VectorExprEvaluator
  6792. : public ExprEvaluatorBase<VectorExprEvaluator> {
  6793. APValue &Result;
  6794. public:
  6795. VectorExprEvaluator(EvalInfo &info, APValue &Result)
  6796. : ExprEvaluatorBaseTy(info), Result(Result) {}
  6797. bool Success(ArrayRef<APValue> V, const Expr *E) {
  6798. assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
  6799. // FIXME: remove this APValue copy.
  6800. Result = APValue(V.data(), V.size());
  6801. return true;
  6802. }
  6803. bool Success(const APValue &V, const Expr *E) {
  6804. assert(V.isVector());
  6805. Result = V;
  6806. return true;
  6807. }
  6808. bool ZeroInitialization(const Expr *E);
  6809. bool VisitUnaryReal(const UnaryOperator *E)
  6810. { return Visit(E->getSubExpr()); }
  6811. bool VisitCastExpr(const CastExpr* E);
  6812. bool VisitInitListExpr(const InitListExpr *E);
  6813. bool VisitUnaryImag(const UnaryOperator *E);
  6814. // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
  6815. // binary comparisons, binary and/or/xor,
  6816. // shufflevector, ExtVectorElementExpr
  6817. };
  6818. } // end anonymous namespace
  6819. static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
  6820. assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
  6821. return VectorExprEvaluator(Info, Result).Visit(E);
  6822. }
  6823. bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
  6824. const VectorType *VTy = E->getType()->castAs<VectorType>();
  6825. unsigned NElts = VTy->getNumElements();
  6826. const Expr *SE = E->getSubExpr();
  6827. QualType SETy = SE->getType();
  6828. switch (E->getCastKind()) {
  6829. case CK_VectorSplat: {
  6830. APValue Val = APValue();
  6831. if (SETy->isIntegerType()) {
  6832. APSInt IntResult;
  6833. if (!EvaluateInteger(SE, IntResult, Info))
  6834. return false;
  6835. Val = APValue(std::move(IntResult));
  6836. } else if (SETy->isRealFloatingType()) {
  6837. APFloat FloatResult(0.0);
  6838. if (!EvaluateFloat(SE, FloatResult, Info))
  6839. return false;
  6840. Val = APValue(std::move(FloatResult));
  6841. } else {
  6842. return Error(E);
  6843. }
  6844. // Splat and create vector APValue.
  6845. SmallVector<APValue, 4> Elts(NElts, Val);
  6846. return Success(Elts, E);
  6847. }
  6848. case CK_BitCast: {
  6849. // Evaluate the operand into an APInt we can extract from.
  6850. llvm::APInt SValInt;
  6851. if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
  6852. return false;
  6853. // Extract the elements
  6854. QualType EltTy = VTy->getElementType();
  6855. unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
  6856. bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
  6857. SmallVector<APValue, 4> Elts;
  6858. if (EltTy->isRealFloatingType()) {
  6859. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
  6860. unsigned FloatEltSize = EltSize;
  6861. if (&Sem == &APFloat::x87DoubleExtended())
  6862. FloatEltSize = 80;
  6863. for (unsigned i = 0; i < NElts; i++) {
  6864. llvm::APInt Elt;
  6865. if (BigEndian)
  6866. Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
  6867. else
  6868. Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
  6869. Elts.push_back(APValue(APFloat(Sem, Elt)));
  6870. }
  6871. } else if (EltTy->isIntegerType()) {
  6872. for (unsigned i = 0; i < NElts; i++) {
  6873. llvm::APInt Elt;
  6874. if (BigEndian)
  6875. Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
  6876. else
  6877. Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
  6878. Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
  6879. }
  6880. } else {
  6881. return Error(E);
  6882. }
  6883. return Success(Elts, E);
  6884. }
  6885. default:
  6886. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  6887. }
  6888. }
  6889. bool
  6890. VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  6891. const VectorType *VT = E->getType()->castAs<VectorType>();
  6892. unsigned NumInits = E->getNumInits();
  6893. unsigned NumElements = VT->getNumElements();
  6894. QualType EltTy = VT->getElementType();
  6895. SmallVector<APValue, 4> Elements;
  6896. // The number of initializers can be less than the number of
  6897. // vector elements. For OpenCL, this can be due to nested vector
  6898. // initialization. For GCC compatibility, missing trailing elements
  6899. // should be initialized with zeroes.
  6900. unsigned CountInits = 0, CountElts = 0;
  6901. while (CountElts < NumElements) {
  6902. // Handle nested vector initialization.
  6903. if (CountInits < NumInits
  6904. && E->getInit(CountInits)->getType()->isVectorType()) {
  6905. APValue v;
  6906. if (!EvaluateVector(E->getInit(CountInits), v, Info))
  6907. return Error(E);
  6908. unsigned vlen = v.getVectorLength();
  6909. for (unsigned j = 0; j < vlen; j++)
  6910. Elements.push_back(v.getVectorElt(j));
  6911. CountElts += vlen;
  6912. } else if (EltTy->isIntegerType()) {
  6913. llvm::APSInt sInt(32);
  6914. if (CountInits < NumInits) {
  6915. if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
  6916. return false;
  6917. } else // trailing integer zero.
  6918. sInt = Info.Ctx.MakeIntValue(0, EltTy);
  6919. Elements.push_back(APValue(sInt));
  6920. CountElts++;
  6921. } else {
  6922. llvm::APFloat f(0.0);
  6923. if (CountInits < NumInits) {
  6924. if (!EvaluateFloat(E->getInit(CountInits), f, Info))
  6925. return false;
  6926. } else // trailing float zero.
  6927. f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
  6928. Elements.push_back(APValue(f));
  6929. CountElts++;
  6930. }
  6931. CountInits++;
  6932. }
  6933. return Success(Elements, E);
  6934. }
  6935. bool
  6936. VectorExprEvaluator::ZeroInitialization(const Expr *E) {
  6937. const VectorType *VT = E->getType()->getAs<VectorType>();
  6938. QualType EltTy = VT->getElementType();
  6939. APValue ZeroElement;
  6940. if (EltTy->isIntegerType())
  6941. ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
  6942. else
  6943. ZeroElement =
  6944. APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
  6945. SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
  6946. return Success(Elements, E);
  6947. }
  6948. bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  6949. VisitIgnoredValue(E->getSubExpr());
  6950. return ZeroInitialization(E);
  6951. }
  6952. //===----------------------------------------------------------------------===//
  6953. // Array Evaluation
  6954. //===----------------------------------------------------------------------===//
  6955. namespace {
  6956. class ArrayExprEvaluator
  6957. : public ExprEvaluatorBase<ArrayExprEvaluator> {
  6958. const LValue &This;
  6959. APValue &Result;
  6960. public:
  6961. ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
  6962. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  6963. bool Success(const APValue &V, const Expr *E) {
  6964. assert(V.isArray() && "expected array");
  6965. Result = V;
  6966. return true;
  6967. }
  6968. bool ZeroInitialization(const Expr *E) {
  6969. const ConstantArrayType *CAT =
  6970. Info.Ctx.getAsConstantArrayType(E->getType());
  6971. if (!CAT)
  6972. return Error(E);
  6973. Result = APValue(APValue::UninitArray(), 0,
  6974. CAT->getSize().getZExtValue());
  6975. if (!Result.hasArrayFiller()) return true;
  6976. // Zero-initialize all elements.
  6977. LValue Subobject = This;
  6978. Subobject.addArray(Info, E, CAT);
  6979. ImplicitValueInitExpr VIE(CAT->getElementType());
  6980. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
  6981. }
  6982. bool VisitCallExpr(const CallExpr *E) {
  6983. return handleCallExpr(E, Result, &This);
  6984. }
  6985. bool VisitInitListExpr(const InitListExpr *E);
  6986. bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
  6987. bool VisitCXXConstructExpr(const CXXConstructExpr *E);
  6988. bool VisitCXXConstructExpr(const CXXConstructExpr *E,
  6989. const LValue &Subobject,
  6990. APValue *Value, QualType Type);
  6991. bool VisitStringLiteral(const StringLiteral *E) {
  6992. expandStringLiteral(Info, E, Result);
  6993. return true;
  6994. }
  6995. };
  6996. } // end anonymous namespace
  6997. static bool EvaluateArray(const Expr *E, const LValue &This,
  6998. APValue &Result, EvalInfo &Info) {
  6999. assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
  7000. return ArrayExprEvaluator(Info, This, Result).Visit(E);
  7001. }
  7002. // Return true iff the given array filler may depend on the element index.
  7003. static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
  7004. // For now, just whitelist non-class value-initialization and initialization
  7005. // lists comprised of them.
  7006. if (isa<ImplicitValueInitExpr>(FillerExpr))
  7007. return false;
  7008. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
  7009. for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
  7010. if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
  7011. return true;
  7012. }
  7013. return false;
  7014. }
  7015. return true;
  7016. }
  7017. bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  7018. const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
  7019. if (!CAT)
  7020. return Error(E);
  7021. // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
  7022. // an appropriately-typed string literal enclosed in braces.
  7023. if (E->isStringLiteralInit())
  7024. return Visit(E->getInit(0));
  7025. bool Success = true;
  7026. assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
  7027. "zero-initialized array shouldn't have any initialized elts");
  7028. APValue Filler;
  7029. if (Result.isArray() && Result.hasArrayFiller())
  7030. Filler = Result.getArrayFiller();
  7031. unsigned NumEltsToInit = E->getNumInits();
  7032. unsigned NumElts = CAT->getSize().getZExtValue();
  7033. const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
  7034. // If the initializer might depend on the array index, run it for each
  7035. // array element.
  7036. if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
  7037. NumEltsToInit = NumElts;
  7038. LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
  7039. << NumEltsToInit << ".\n");
  7040. Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
  7041. // If the array was previously zero-initialized, preserve the
  7042. // zero-initialized values.
  7043. if (Filler.hasValue()) {
  7044. for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
  7045. Result.getArrayInitializedElt(I) = Filler;
  7046. if (Result.hasArrayFiller())
  7047. Result.getArrayFiller() = Filler;
  7048. }
  7049. LValue Subobject = This;
  7050. Subobject.addArray(Info, E, CAT);
  7051. for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
  7052. const Expr *Init =
  7053. Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
  7054. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7055. Info, Subobject, Init) ||
  7056. !HandleLValueArrayAdjustment(Info, Init, Subobject,
  7057. CAT->getElementType(), 1)) {
  7058. if (!Info.noteFailure())
  7059. return false;
  7060. Success = false;
  7061. }
  7062. }
  7063. if (!Result.hasArrayFiller())
  7064. return Success;
  7065. // If we get here, we have a trivial filler, which we can just evaluate
  7066. // once and splat over the rest of the array elements.
  7067. assert(FillerExpr && "no array filler for incomplete init list");
  7068. return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
  7069. FillerExpr) && Success;
  7070. }
  7071. bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
  7072. if (E->getCommonExpr() &&
  7073. !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
  7074. Info, E->getCommonExpr()->getSourceExpr()))
  7075. return false;
  7076. auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
  7077. uint64_t Elements = CAT->getSize().getZExtValue();
  7078. Result = APValue(APValue::UninitArray(), Elements, Elements);
  7079. LValue Subobject = This;
  7080. Subobject.addArray(Info, E, CAT);
  7081. bool Success = true;
  7082. for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
  7083. if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
  7084. Info, Subobject, E->getSubExpr()) ||
  7085. !HandleLValueArrayAdjustment(Info, E, Subobject,
  7086. CAT->getElementType(), 1)) {
  7087. if (!Info.noteFailure())
  7088. return false;
  7089. Success = false;
  7090. }
  7091. }
  7092. return Success;
  7093. }
  7094. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  7095. return VisitCXXConstructExpr(E, This, &Result, E->getType());
  7096. }
  7097. bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
  7098. const LValue &Subobject,
  7099. APValue *Value,
  7100. QualType Type) {
  7101. bool HadZeroInit = Value->hasValue();
  7102. if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
  7103. unsigned N = CAT->getSize().getZExtValue();
  7104. // Preserve the array filler if we had prior zero-initialization.
  7105. APValue Filler =
  7106. HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
  7107. : APValue();
  7108. *Value = APValue(APValue::UninitArray(), N, N);
  7109. if (HadZeroInit)
  7110. for (unsigned I = 0; I != N; ++I)
  7111. Value->getArrayInitializedElt(I) = Filler;
  7112. // Initialize the elements.
  7113. LValue ArrayElt = Subobject;
  7114. ArrayElt.addArray(Info, E, CAT);
  7115. for (unsigned I = 0; I != N; ++I)
  7116. if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
  7117. CAT->getElementType()) ||
  7118. !HandleLValueArrayAdjustment(Info, E, ArrayElt,
  7119. CAT->getElementType(), 1))
  7120. return false;
  7121. return true;
  7122. }
  7123. if (!Type->isRecordType())
  7124. return Error(E);
  7125. return RecordExprEvaluator(Info, Subobject, *Value)
  7126. .VisitCXXConstructExpr(E, Type);
  7127. }
  7128. //===----------------------------------------------------------------------===//
  7129. // Integer Evaluation
  7130. //
  7131. // As a GNU extension, we support casting pointers to sufficiently-wide integer
  7132. // types and back in constant folding. Integer values are thus represented
  7133. // either as an integer-valued APValue, or as an lvalue-valued APValue.
  7134. //===----------------------------------------------------------------------===//
  7135. namespace {
  7136. class IntExprEvaluator
  7137. : public ExprEvaluatorBase<IntExprEvaluator> {
  7138. APValue &Result;
  7139. public:
  7140. IntExprEvaluator(EvalInfo &info, APValue &result)
  7141. : ExprEvaluatorBaseTy(info), Result(result) {}
  7142. bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
  7143. assert(E->getType()->isIntegralOrEnumerationType() &&
  7144. "Invalid evaluation result.");
  7145. assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
  7146. "Invalid evaluation result.");
  7147. assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7148. "Invalid evaluation result.");
  7149. Result = APValue(SI);
  7150. return true;
  7151. }
  7152. bool Success(const llvm::APSInt &SI, const Expr *E) {
  7153. return Success(SI, E, Result);
  7154. }
  7155. bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
  7156. assert(E->getType()->isIntegralOrEnumerationType() &&
  7157. "Invalid evaluation result.");
  7158. assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7159. "Invalid evaluation result.");
  7160. Result = APValue(APSInt(I));
  7161. Result.getInt().setIsUnsigned(
  7162. E->getType()->isUnsignedIntegerOrEnumerationType());
  7163. return true;
  7164. }
  7165. bool Success(const llvm::APInt &I, const Expr *E) {
  7166. return Success(I, E, Result);
  7167. }
  7168. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  7169. assert(E->getType()->isIntegralOrEnumerationType() &&
  7170. "Invalid evaluation result.");
  7171. Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
  7172. return true;
  7173. }
  7174. bool Success(uint64_t Value, const Expr *E) {
  7175. return Success(Value, E, Result);
  7176. }
  7177. bool Success(CharUnits Size, const Expr *E) {
  7178. return Success(Size.getQuantity(), E);
  7179. }
  7180. bool Success(const APValue &V, const Expr *E) {
  7181. if (V.isLValue() || V.isAddrLabelDiff()) {
  7182. Result = V;
  7183. return true;
  7184. }
  7185. return Success(V.getInt(), E);
  7186. }
  7187. bool ZeroInitialization(const Expr *E) { return Success(0, E); }
  7188. //===--------------------------------------------------------------------===//
  7189. // Visitor Methods
  7190. //===--------------------------------------------------------------------===//
  7191. bool VisitConstantExpr(const ConstantExpr *E);
  7192. bool VisitIntegerLiteral(const IntegerLiteral *E) {
  7193. return Success(E->getValue(), E);
  7194. }
  7195. bool VisitCharacterLiteral(const CharacterLiteral *E) {
  7196. return Success(E->getValue(), E);
  7197. }
  7198. bool CheckReferencedDecl(const Expr *E, const Decl *D);
  7199. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  7200. if (CheckReferencedDecl(E, E->getDecl()))
  7201. return true;
  7202. return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
  7203. }
  7204. bool VisitMemberExpr(const MemberExpr *E) {
  7205. if (CheckReferencedDecl(E, E->getMemberDecl())) {
  7206. VisitIgnoredBaseExpression(E->getBase());
  7207. return true;
  7208. }
  7209. return ExprEvaluatorBaseTy::VisitMemberExpr(E);
  7210. }
  7211. bool VisitCallExpr(const CallExpr *E);
  7212. bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
  7213. bool VisitBinaryOperator(const BinaryOperator *E);
  7214. bool VisitOffsetOfExpr(const OffsetOfExpr *E);
  7215. bool VisitUnaryOperator(const UnaryOperator *E);
  7216. bool VisitCastExpr(const CastExpr* E);
  7217. bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  7218. bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
  7219. return Success(E->getValue(), E);
  7220. }
  7221. bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
  7222. return Success(E->getValue(), E);
  7223. }
  7224. bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
  7225. if (Info.ArrayInitIndex == uint64_t(-1)) {
  7226. // We were asked to evaluate this subexpression independent of the
  7227. // enclosing ArrayInitLoopExpr. We can't do that.
  7228. Info.FFDiag(E);
  7229. return false;
  7230. }
  7231. return Success(Info.ArrayInitIndex, E);
  7232. }
  7233. // Note, GNU defines __null as an integer, not a pointer.
  7234. bool VisitGNUNullExpr(const GNUNullExpr *E) {
  7235. return ZeroInitialization(E);
  7236. }
  7237. bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
  7238. return Success(E->getValue(), E);
  7239. }
  7240. bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  7241. return Success(E->getValue(), E);
  7242. }
  7243. bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  7244. return Success(E->getValue(), E);
  7245. }
  7246. bool VisitUnaryReal(const UnaryOperator *E);
  7247. bool VisitUnaryImag(const UnaryOperator *E);
  7248. bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
  7249. bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  7250. bool VisitSourceLocExpr(const SourceLocExpr *E);
  7251. // FIXME: Missing: array subscript of vector, member of vector
  7252. };
  7253. class FixedPointExprEvaluator
  7254. : public ExprEvaluatorBase<FixedPointExprEvaluator> {
  7255. APValue &Result;
  7256. public:
  7257. FixedPointExprEvaluator(EvalInfo &info, APValue &result)
  7258. : ExprEvaluatorBaseTy(info), Result(result) {}
  7259. bool Success(const llvm::APInt &I, const Expr *E) {
  7260. return Success(
  7261. APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7262. }
  7263. bool Success(uint64_t Value, const Expr *E) {
  7264. return Success(
  7265. APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
  7266. }
  7267. bool Success(const APValue &V, const Expr *E) {
  7268. return Success(V.getFixedPoint(), E);
  7269. }
  7270. bool Success(const APFixedPoint &V, const Expr *E) {
  7271. assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
  7272. assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
  7273. "Invalid evaluation result.");
  7274. Result = APValue(V);
  7275. return true;
  7276. }
  7277. //===--------------------------------------------------------------------===//
  7278. // Visitor Methods
  7279. //===--------------------------------------------------------------------===//
  7280. bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
  7281. return Success(E->getValue(), E);
  7282. }
  7283. bool VisitCastExpr(const CastExpr *E);
  7284. bool VisitUnaryOperator(const UnaryOperator *E);
  7285. bool VisitBinaryOperator(const BinaryOperator *E);
  7286. };
  7287. } // end anonymous namespace
  7288. /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
  7289. /// produce either the integer value or a pointer.
  7290. ///
  7291. /// GCC has a heinous extension which folds casts between pointer types and
  7292. /// pointer-sized integral types. We support this by allowing the evaluation of
  7293. /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
  7294. /// Some simple arithmetic on such values is supported (they are treated much
  7295. /// like char*).
  7296. static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
  7297. EvalInfo &Info) {
  7298. assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
  7299. return IntExprEvaluator(Info, Result).Visit(E);
  7300. }
  7301. static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
  7302. APValue Val;
  7303. if (!EvaluateIntegerOrLValue(E, Val, Info))
  7304. return false;
  7305. if (!Val.isInt()) {
  7306. // FIXME: It would be better to produce the diagnostic for casting
  7307. // a pointer to an integer.
  7308. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7309. return false;
  7310. }
  7311. Result = Val.getInt();
  7312. return true;
  7313. }
  7314. bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
  7315. APValue Evaluated = E->EvaluateInContext(
  7316. Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
  7317. return Success(Evaluated, E);
  7318. }
  7319. static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
  7320. EvalInfo &Info) {
  7321. if (E->getType()->isFixedPointType()) {
  7322. APValue Val;
  7323. if (!FixedPointExprEvaluator(Info, Val).Visit(E))
  7324. return false;
  7325. if (!Val.isFixedPoint())
  7326. return false;
  7327. Result = Val.getFixedPoint();
  7328. return true;
  7329. }
  7330. return false;
  7331. }
  7332. static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
  7333. EvalInfo &Info) {
  7334. if (E->getType()->isIntegerType()) {
  7335. auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
  7336. APSInt Val;
  7337. if (!EvaluateInteger(E, Val, Info))
  7338. return false;
  7339. Result = APFixedPoint(Val, FXSema);
  7340. return true;
  7341. } else if (E->getType()->isFixedPointType()) {
  7342. return EvaluateFixedPoint(E, Result, Info);
  7343. }
  7344. return false;
  7345. }
  7346. /// Check whether the given declaration can be directly converted to an integral
  7347. /// rvalue. If not, no diagnostic is produced; there are other things we can
  7348. /// try.
  7349. bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
  7350. // Enums are integer constant exprs.
  7351. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
  7352. // Check for signedness/width mismatches between E type and ECD value.
  7353. bool SameSign = (ECD->getInitVal().isSigned()
  7354. == E->getType()->isSignedIntegerOrEnumerationType());
  7355. bool SameWidth = (ECD->getInitVal().getBitWidth()
  7356. == Info.Ctx.getIntWidth(E->getType()));
  7357. if (SameSign && SameWidth)
  7358. return Success(ECD->getInitVal(), E);
  7359. else {
  7360. // Get rid of mismatch (otherwise Success assertions will fail)
  7361. // by computing a new value matching the type of E.
  7362. llvm::APSInt Val = ECD->getInitVal();
  7363. if (!SameSign)
  7364. Val.setIsSigned(!ECD->getInitVal().isSigned());
  7365. if (!SameWidth)
  7366. Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
  7367. return Success(Val, E);
  7368. }
  7369. }
  7370. return false;
  7371. }
  7372. /// Values returned by __builtin_classify_type, chosen to match the values
  7373. /// produced by GCC's builtin.
  7374. enum class GCCTypeClass {
  7375. None = -1,
  7376. Void = 0,
  7377. Integer = 1,
  7378. // GCC reserves 2 for character types, but instead classifies them as
  7379. // integers.
  7380. Enum = 3,
  7381. Bool = 4,
  7382. Pointer = 5,
  7383. // GCC reserves 6 for references, but appears to never use it (because
  7384. // expressions never have reference type, presumably).
  7385. PointerToDataMember = 7,
  7386. RealFloat = 8,
  7387. Complex = 9,
  7388. // GCC reserves 10 for functions, but does not use it since GCC version 6 due
  7389. // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7390. // GCC claims to reserve 11 for pointers to member functions, but *actually*
  7391. // uses 12 for that purpose, same as for a class or struct. Maybe it
  7392. // internally implements a pointer to member as a struct? Who knows.
  7393. PointerToMemberFunction = 12, // Not a bug, see above.
  7394. ClassOrStruct = 12,
  7395. Union = 13,
  7396. // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
  7397. // decay to pointer. (Prior to version 6 it was only used in C++ mode).
  7398. // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
  7399. // literals.
  7400. };
  7401. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7402. /// as GCC.
  7403. static GCCTypeClass
  7404. EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
  7405. assert(!T->isDependentType() && "unexpected dependent type");
  7406. QualType CanTy = T.getCanonicalType();
  7407. const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
  7408. switch (CanTy->getTypeClass()) {
  7409. #define TYPE(ID, BASE)
  7410. #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7411. #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
  7412. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
  7413. #include "clang/AST/TypeNodes.def"
  7414. case Type::Auto:
  7415. case Type::DeducedTemplateSpecialization:
  7416. llvm_unreachable("unexpected non-canonical or dependent type");
  7417. case Type::Builtin:
  7418. switch (BT->getKind()) {
  7419. #define BUILTIN_TYPE(ID, SINGLETON_ID)
  7420. #define SIGNED_TYPE(ID, SINGLETON_ID) \
  7421. case BuiltinType::ID: return GCCTypeClass::Integer;
  7422. #define FLOATING_TYPE(ID, SINGLETON_ID) \
  7423. case BuiltinType::ID: return GCCTypeClass::RealFloat;
  7424. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
  7425. case BuiltinType::ID: break;
  7426. #include "clang/AST/BuiltinTypes.def"
  7427. case BuiltinType::Void:
  7428. return GCCTypeClass::Void;
  7429. case BuiltinType::Bool:
  7430. return GCCTypeClass::Bool;
  7431. case BuiltinType::Char_U:
  7432. case BuiltinType::UChar:
  7433. case BuiltinType::WChar_U:
  7434. case BuiltinType::Char8:
  7435. case BuiltinType::Char16:
  7436. case BuiltinType::Char32:
  7437. case BuiltinType::UShort:
  7438. case BuiltinType::UInt:
  7439. case BuiltinType::ULong:
  7440. case BuiltinType::ULongLong:
  7441. case BuiltinType::UInt128:
  7442. return GCCTypeClass::Integer;
  7443. case BuiltinType::UShortAccum:
  7444. case BuiltinType::UAccum:
  7445. case BuiltinType::ULongAccum:
  7446. case BuiltinType::UShortFract:
  7447. case BuiltinType::UFract:
  7448. case BuiltinType::ULongFract:
  7449. case BuiltinType::SatUShortAccum:
  7450. case BuiltinType::SatUAccum:
  7451. case BuiltinType::SatULongAccum:
  7452. case BuiltinType::SatUShortFract:
  7453. case BuiltinType::SatUFract:
  7454. case BuiltinType::SatULongFract:
  7455. return GCCTypeClass::None;
  7456. case BuiltinType::NullPtr:
  7457. case BuiltinType::ObjCId:
  7458. case BuiltinType::ObjCClass:
  7459. case BuiltinType::ObjCSel:
  7460. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  7461. case BuiltinType::Id:
  7462. #include "clang/Basic/OpenCLImageTypes.def"
  7463. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  7464. case BuiltinType::Id:
  7465. #include "clang/Basic/OpenCLExtensionTypes.def"
  7466. case BuiltinType::OCLSampler:
  7467. case BuiltinType::OCLEvent:
  7468. case BuiltinType::OCLClkEvent:
  7469. case BuiltinType::OCLQueue:
  7470. case BuiltinType::OCLReserveID:
  7471. return GCCTypeClass::None;
  7472. case BuiltinType::Dependent:
  7473. llvm_unreachable("unexpected dependent type");
  7474. };
  7475. llvm_unreachable("unexpected placeholder type");
  7476. case Type::Enum:
  7477. return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
  7478. case Type::Pointer:
  7479. case Type::ConstantArray:
  7480. case Type::VariableArray:
  7481. case Type::IncompleteArray:
  7482. case Type::FunctionNoProto:
  7483. case Type::FunctionProto:
  7484. return GCCTypeClass::Pointer;
  7485. case Type::MemberPointer:
  7486. return CanTy->isMemberDataPointerType()
  7487. ? GCCTypeClass::PointerToDataMember
  7488. : GCCTypeClass::PointerToMemberFunction;
  7489. case Type::Complex:
  7490. return GCCTypeClass::Complex;
  7491. case Type::Record:
  7492. return CanTy->isUnionType() ? GCCTypeClass::Union
  7493. : GCCTypeClass::ClassOrStruct;
  7494. case Type::Atomic:
  7495. // GCC classifies _Atomic T the same as T.
  7496. return EvaluateBuiltinClassifyType(
  7497. CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
  7498. case Type::BlockPointer:
  7499. case Type::Vector:
  7500. case Type::ExtVector:
  7501. case Type::ObjCObject:
  7502. case Type::ObjCInterface:
  7503. case Type::ObjCObjectPointer:
  7504. case Type::Pipe:
  7505. // GCC classifies vectors as None. We follow its lead and classify all
  7506. // other types that don't fit into the regular classification the same way.
  7507. return GCCTypeClass::None;
  7508. case Type::LValueReference:
  7509. case Type::RValueReference:
  7510. llvm_unreachable("invalid type for expression");
  7511. }
  7512. llvm_unreachable("unexpected type class");
  7513. }
  7514. /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
  7515. /// as GCC.
  7516. static GCCTypeClass
  7517. EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
  7518. // If no argument was supplied, default to None. This isn't
  7519. // ideal, however it is what gcc does.
  7520. if (E->getNumArgs() == 0)
  7521. return GCCTypeClass::None;
  7522. // FIXME: Bizarrely, GCC treats a call with more than one argument as not
  7523. // being an ICE, but still folds it to a constant using the type of the first
  7524. // argument.
  7525. return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
  7526. }
  7527. /// EvaluateBuiltinConstantPForLValue - Determine the result of
  7528. /// __builtin_constant_p when applied to the given pointer.
  7529. ///
  7530. /// A pointer is only "constant" if it is null (or a pointer cast to integer)
  7531. /// or it points to the first character of a string literal.
  7532. static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
  7533. APValue::LValueBase Base = LV.getLValueBase();
  7534. if (Base.isNull()) {
  7535. // A null base is acceptable.
  7536. return true;
  7537. } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
  7538. if (!isa<StringLiteral>(E))
  7539. return false;
  7540. return LV.getLValueOffset().isZero();
  7541. } else if (Base.is<TypeInfoLValue>()) {
  7542. // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
  7543. // evaluate to true.
  7544. return true;
  7545. } else {
  7546. // Any other base is not constant enough for GCC.
  7547. return false;
  7548. }
  7549. }
  7550. /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
  7551. /// GCC as we can manage.
  7552. static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
  7553. // This evaluation is not permitted to have side-effects, so evaluate it in
  7554. // a speculative evaluation context.
  7555. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7556. // Constant-folding is always enabled for the operand of __builtin_constant_p
  7557. // (even when the enclosing evaluation context otherwise requires a strict
  7558. // language-specific constant expression).
  7559. FoldConstant Fold(Info, true);
  7560. QualType ArgType = Arg->getType();
  7561. // __builtin_constant_p always has one operand. The rules which gcc follows
  7562. // are not precisely documented, but are as follows:
  7563. //
  7564. // - If the operand is of integral, floating, complex or enumeration type,
  7565. // and can be folded to a known value of that type, it returns 1.
  7566. // - If the operand can be folded to a pointer to the first character
  7567. // of a string literal (or such a pointer cast to an integral type)
  7568. // or to a null pointer or an integer cast to a pointer, it returns 1.
  7569. //
  7570. // Otherwise, it returns 0.
  7571. //
  7572. // FIXME: GCC also intends to return 1 for literals of aggregate types, but
  7573. // its support for this did not work prior to GCC 9 and is not yet well
  7574. // understood.
  7575. if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
  7576. ArgType->isAnyComplexType() || ArgType->isPointerType() ||
  7577. ArgType->isNullPtrType()) {
  7578. APValue V;
  7579. if (!::EvaluateAsRValue(Info, Arg, V)) {
  7580. Fold.keepDiagnostics();
  7581. return false;
  7582. }
  7583. // For a pointer (possibly cast to integer), there are special rules.
  7584. if (V.getKind() == APValue::LValue)
  7585. return EvaluateBuiltinConstantPForLValue(V);
  7586. // Otherwise, any constant value is good enough.
  7587. return V.hasValue();
  7588. }
  7589. // Anything else isn't considered to be sufficiently constant.
  7590. return false;
  7591. }
  7592. /// Retrieves the "underlying object type" of the given expression,
  7593. /// as used by __builtin_object_size.
  7594. static QualType getObjectType(APValue::LValueBase B) {
  7595. if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
  7596. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  7597. return VD->getType();
  7598. } else if (const Expr *E = B.get<const Expr*>()) {
  7599. if (isa<CompoundLiteralExpr>(E))
  7600. return E->getType();
  7601. } else if (B.is<TypeInfoLValue>()) {
  7602. return B.getTypeInfoType();
  7603. }
  7604. return QualType();
  7605. }
  7606. /// A more selective version of E->IgnoreParenCasts for
  7607. /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
  7608. /// to change the type of E.
  7609. /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
  7610. ///
  7611. /// Always returns an RValue with a pointer representation.
  7612. static const Expr *ignorePointerCastsAndParens(const Expr *E) {
  7613. assert(E->isRValue() && E->getType()->hasPointerRepresentation());
  7614. auto *NoParens = E->IgnoreParens();
  7615. auto *Cast = dyn_cast<CastExpr>(NoParens);
  7616. if (Cast == nullptr)
  7617. return NoParens;
  7618. // We only conservatively allow a few kinds of casts, because this code is
  7619. // inherently a simple solution that seeks to support the common case.
  7620. auto CastKind = Cast->getCastKind();
  7621. if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
  7622. CastKind != CK_AddressSpaceConversion)
  7623. return NoParens;
  7624. auto *SubExpr = Cast->getSubExpr();
  7625. if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
  7626. return NoParens;
  7627. return ignorePointerCastsAndParens(SubExpr);
  7628. }
  7629. /// Checks to see if the given LValue's Designator is at the end of the LValue's
  7630. /// record layout. e.g.
  7631. /// struct { struct { int a, b; } fst, snd; } obj;
  7632. /// obj.fst // no
  7633. /// obj.snd // yes
  7634. /// obj.fst.a // no
  7635. /// obj.fst.b // no
  7636. /// obj.snd.a // no
  7637. /// obj.snd.b // yes
  7638. ///
  7639. /// Please note: this function is specialized for how __builtin_object_size
  7640. /// views "objects".
  7641. ///
  7642. /// If this encounters an invalid RecordDecl or otherwise cannot determine the
  7643. /// correct result, it will always return true.
  7644. static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
  7645. assert(!LVal.Designator.Invalid);
  7646. auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
  7647. const RecordDecl *Parent = FD->getParent();
  7648. Invalid = Parent->isInvalidDecl();
  7649. if (Invalid || Parent->isUnion())
  7650. return true;
  7651. const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
  7652. return FD->getFieldIndex() + 1 == Layout.getFieldCount();
  7653. };
  7654. auto &Base = LVal.getLValueBase();
  7655. if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
  7656. if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  7657. bool Invalid;
  7658. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  7659. return Invalid;
  7660. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
  7661. for (auto *FD : IFD->chain()) {
  7662. bool Invalid;
  7663. if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
  7664. return Invalid;
  7665. }
  7666. }
  7667. }
  7668. unsigned I = 0;
  7669. QualType BaseType = getType(Base);
  7670. if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
  7671. // If we don't know the array bound, conservatively assume we're looking at
  7672. // the final array element.
  7673. ++I;
  7674. if (BaseType->isIncompleteArrayType())
  7675. BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
  7676. else
  7677. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  7678. }
  7679. for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
  7680. const auto &Entry = LVal.Designator.Entries[I];
  7681. if (BaseType->isArrayType()) {
  7682. // Because __builtin_object_size treats arrays as objects, we can ignore
  7683. // the index iff this is the last array in the Designator.
  7684. if (I + 1 == E)
  7685. return true;
  7686. const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
  7687. uint64_t Index = Entry.getAsArrayIndex();
  7688. if (Index + 1 != CAT->getSize())
  7689. return false;
  7690. BaseType = CAT->getElementType();
  7691. } else if (BaseType->isAnyComplexType()) {
  7692. const auto *CT = BaseType->castAs<ComplexType>();
  7693. uint64_t Index = Entry.getAsArrayIndex();
  7694. if (Index != 1)
  7695. return false;
  7696. BaseType = CT->getElementType();
  7697. } else if (auto *FD = getAsField(Entry)) {
  7698. bool Invalid;
  7699. if (!IsLastOrInvalidFieldDecl(FD, Invalid))
  7700. return Invalid;
  7701. BaseType = FD->getType();
  7702. } else {
  7703. assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
  7704. return false;
  7705. }
  7706. }
  7707. return true;
  7708. }
  7709. /// Tests to see if the LValue has a user-specified designator (that isn't
  7710. /// necessarily valid). Note that this always returns 'true' if the LValue has
  7711. /// an unsized array as its first designator entry, because there's currently no
  7712. /// way to tell if the user typed *foo or foo[0].
  7713. static bool refersToCompleteObject(const LValue &LVal) {
  7714. if (LVal.Designator.Invalid)
  7715. return false;
  7716. if (!LVal.Designator.Entries.empty())
  7717. return LVal.Designator.isMostDerivedAnUnsizedArray();
  7718. if (!LVal.InvalidBase)
  7719. return true;
  7720. // If `E` is a MemberExpr, then the first part of the designator is hiding in
  7721. // the LValueBase.
  7722. const auto *E = LVal.Base.dyn_cast<const Expr *>();
  7723. return !E || !isa<MemberExpr>(E);
  7724. }
  7725. /// Attempts to detect a user writing into a piece of memory that's impossible
  7726. /// to figure out the size of by just using types.
  7727. static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
  7728. const SubobjectDesignator &Designator = LVal.Designator;
  7729. // Notes:
  7730. // - Users can only write off of the end when we have an invalid base. Invalid
  7731. // bases imply we don't know where the memory came from.
  7732. // - We used to be a bit more aggressive here; we'd only be conservative if
  7733. // the array at the end was flexible, or if it had 0 or 1 elements. This
  7734. // broke some common standard library extensions (PR30346), but was
  7735. // otherwise seemingly fine. It may be useful to reintroduce this behavior
  7736. // with some sort of whitelist. OTOH, it seems that GCC is always
  7737. // conservative with the last element in structs (if it's an array), so our
  7738. // current behavior is more compatible than a whitelisting approach would
  7739. // be.
  7740. return LVal.InvalidBase &&
  7741. Designator.Entries.size() == Designator.MostDerivedPathLength &&
  7742. Designator.MostDerivedIsArrayElement &&
  7743. isDesignatorAtObjectEnd(Ctx, LVal);
  7744. }
  7745. /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
  7746. /// Fails if the conversion would cause loss of precision.
  7747. static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
  7748. CharUnits &Result) {
  7749. auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
  7750. if (Int.ugt(CharUnitsMax))
  7751. return false;
  7752. Result = CharUnits::fromQuantity(Int.getZExtValue());
  7753. return true;
  7754. }
  7755. /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
  7756. /// determine how many bytes exist from the beginning of the object to either
  7757. /// the end of the current subobject, or the end of the object itself, depending
  7758. /// on what the LValue looks like + the value of Type.
  7759. ///
  7760. /// If this returns false, the value of Result is undefined.
  7761. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
  7762. unsigned Type, const LValue &LVal,
  7763. CharUnits &EndOffset) {
  7764. bool DetermineForCompleteObject = refersToCompleteObject(LVal);
  7765. auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
  7766. if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
  7767. return false;
  7768. return HandleSizeof(Info, ExprLoc, Ty, Result);
  7769. };
  7770. // We want to evaluate the size of the entire object. This is a valid fallback
  7771. // for when Type=1 and the designator is invalid, because we're asked for an
  7772. // upper-bound.
  7773. if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
  7774. // Type=3 wants a lower bound, so we can't fall back to this.
  7775. if (Type == 3 && !DetermineForCompleteObject)
  7776. return false;
  7777. llvm::APInt APEndOffset;
  7778. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7779. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7780. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7781. if (LVal.InvalidBase)
  7782. return false;
  7783. QualType BaseTy = getObjectType(LVal.getLValueBase());
  7784. return CheckedHandleSizeof(BaseTy, EndOffset);
  7785. }
  7786. // We want to evaluate the size of a subobject.
  7787. const SubobjectDesignator &Designator = LVal.Designator;
  7788. // The following is a moderately common idiom in C:
  7789. //
  7790. // struct Foo { int a; char c[1]; };
  7791. // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
  7792. // strcpy(&F->c[0], Bar);
  7793. //
  7794. // In order to not break too much legacy code, we need to support it.
  7795. if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
  7796. // If we can resolve this to an alloc_size call, we can hand that back,
  7797. // because we know for certain how many bytes there are to write to.
  7798. llvm::APInt APEndOffset;
  7799. if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
  7800. getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
  7801. return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
  7802. // If we cannot determine the size of the initial allocation, then we can't
  7803. // given an accurate upper-bound. However, we are still able to give
  7804. // conservative lower-bounds for Type=3.
  7805. if (Type == 1)
  7806. return false;
  7807. }
  7808. CharUnits BytesPerElem;
  7809. if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
  7810. return false;
  7811. // According to the GCC documentation, we want the size of the subobject
  7812. // denoted by the pointer. But that's not quite right -- what we actually
  7813. // want is the size of the immediately-enclosing array, if there is one.
  7814. int64_t ElemsRemaining;
  7815. if (Designator.MostDerivedIsArrayElement &&
  7816. Designator.Entries.size() == Designator.MostDerivedPathLength) {
  7817. uint64_t ArraySize = Designator.getMostDerivedArraySize();
  7818. uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
  7819. ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
  7820. } else {
  7821. ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
  7822. }
  7823. EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
  7824. return true;
  7825. }
  7826. /// Tries to evaluate the __builtin_object_size for @p E. If successful,
  7827. /// returns true and stores the result in @p Size.
  7828. ///
  7829. /// If @p WasError is non-null, this will report whether the failure to evaluate
  7830. /// is to be treated as an Error in IntExprEvaluator.
  7831. static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
  7832. EvalInfo &Info, uint64_t &Size) {
  7833. // Determine the denoted object.
  7834. LValue LVal;
  7835. {
  7836. // The operand of __builtin_object_size is never evaluated for side-effects.
  7837. // If there are any, but we can determine the pointed-to object anyway, then
  7838. // ignore the side-effects.
  7839. SpeculativeEvaluationRAII SpeculativeEval(Info);
  7840. IgnoreSideEffectsRAII Fold(Info);
  7841. if (E->isGLValue()) {
  7842. // It's possible for us to be given GLValues if we're called via
  7843. // Expr::tryEvaluateObjectSize.
  7844. APValue RVal;
  7845. if (!EvaluateAsRValue(Info, E, RVal))
  7846. return false;
  7847. LVal.setFrom(Info.Ctx, RVal);
  7848. } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
  7849. /*InvalidBaseOK=*/true))
  7850. return false;
  7851. }
  7852. // If we point to before the start of the object, there are no accessible
  7853. // bytes.
  7854. if (LVal.getLValueOffset().isNegative()) {
  7855. Size = 0;
  7856. return true;
  7857. }
  7858. CharUnits EndOffset;
  7859. if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
  7860. return false;
  7861. // If we've fallen outside of the end offset, just pretend there's nothing to
  7862. // write to/read from.
  7863. if (EndOffset <= LVal.getLValueOffset())
  7864. Size = 0;
  7865. else
  7866. Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
  7867. return true;
  7868. }
  7869. bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
  7870. llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
  7871. return ExprEvaluatorBaseTy::VisitConstantExpr(E);
  7872. }
  7873. bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
  7874. if (unsigned BuiltinOp = E->getBuiltinCallee())
  7875. return VisitBuiltinCallExpr(E, BuiltinOp);
  7876. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7877. }
  7878. bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
  7879. unsigned BuiltinOp) {
  7880. switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
  7881. default:
  7882. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  7883. case Builtin::BI__builtin_dynamic_object_size:
  7884. case Builtin::BI__builtin_object_size: {
  7885. // The type was checked when we built the expression.
  7886. unsigned Type =
  7887. E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7888. assert(Type <= 3 && "unexpected type");
  7889. uint64_t Size;
  7890. if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
  7891. return Success(Size, E);
  7892. if (E->getArg(0)->HasSideEffects(Info.Ctx))
  7893. return Success((Type & 2) ? 0 : -1, E);
  7894. // Expression had no side effects, but we couldn't statically determine the
  7895. // size of the referenced object.
  7896. switch (Info.EvalMode) {
  7897. case EvalInfo::EM_ConstantExpression:
  7898. case EvalInfo::EM_PotentialConstantExpression:
  7899. case EvalInfo::EM_ConstantFold:
  7900. case EvalInfo::EM_EvaluateForOverflow:
  7901. case EvalInfo::EM_IgnoreSideEffects:
  7902. // Leave it to IR generation.
  7903. return Error(E);
  7904. case EvalInfo::EM_ConstantExpressionUnevaluated:
  7905. case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
  7906. // Reduce it to a constant now.
  7907. return Success((Type & 2) ? 0 : -1, E);
  7908. }
  7909. llvm_unreachable("unexpected EvalMode");
  7910. }
  7911. case Builtin::BI__builtin_os_log_format_buffer_size: {
  7912. analyze_os_log::OSLogBufferLayout Layout;
  7913. analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
  7914. return Success(Layout.size().getQuantity(), E);
  7915. }
  7916. case Builtin::BI__builtin_bswap16:
  7917. case Builtin::BI__builtin_bswap32:
  7918. case Builtin::BI__builtin_bswap64: {
  7919. APSInt Val;
  7920. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7921. return false;
  7922. return Success(Val.byteSwap(), E);
  7923. }
  7924. case Builtin::BI__builtin_classify_type:
  7925. return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
  7926. case Builtin::BI__builtin_clrsb:
  7927. case Builtin::BI__builtin_clrsbl:
  7928. case Builtin::BI__builtin_clrsbll: {
  7929. APSInt Val;
  7930. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7931. return false;
  7932. return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
  7933. }
  7934. case Builtin::BI__builtin_clz:
  7935. case Builtin::BI__builtin_clzl:
  7936. case Builtin::BI__builtin_clzll:
  7937. case Builtin::BI__builtin_clzs: {
  7938. APSInt Val;
  7939. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7940. return false;
  7941. if (!Val)
  7942. return Error(E);
  7943. return Success(Val.countLeadingZeros(), E);
  7944. }
  7945. case Builtin::BI__builtin_constant_p: {
  7946. const Expr *Arg = E->getArg(0);
  7947. if (EvaluateBuiltinConstantP(Info, Arg))
  7948. return Success(true, E);
  7949. if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
  7950. // Outside a constant context, eagerly evaluate to false in the presence
  7951. // of side-effects in order to avoid -Wunsequenced false-positives in
  7952. // a branch on __builtin_constant_p(expr).
  7953. return Success(false, E);
  7954. }
  7955. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  7956. return false;
  7957. }
  7958. case Builtin::BI__builtin_is_constant_evaluated:
  7959. return Success(Info.InConstantContext, E);
  7960. case Builtin::BI__builtin_ctz:
  7961. case Builtin::BI__builtin_ctzl:
  7962. case Builtin::BI__builtin_ctzll:
  7963. case Builtin::BI__builtin_ctzs: {
  7964. APSInt Val;
  7965. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7966. return false;
  7967. if (!Val)
  7968. return Error(E);
  7969. return Success(Val.countTrailingZeros(), E);
  7970. }
  7971. case Builtin::BI__builtin_eh_return_data_regno: {
  7972. int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
  7973. Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
  7974. return Success(Operand, E);
  7975. }
  7976. case Builtin::BI__builtin_expect:
  7977. return Visit(E->getArg(0));
  7978. case Builtin::BI__builtin_ffs:
  7979. case Builtin::BI__builtin_ffsl:
  7980. case Builtin::BI__builtin_ffsll: {
  7981. APSInt Val;
  7982. if (!EvaluateInteger(E->getArg(0), Val, Info))
  7983. return false;
  7984. unsigned N = Val.countTrailingZeros();
  7985. return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
  7986. }
  7987. case Builtin::BI__builtin_fpclassify: {
  7988. APFloat Val(0.0);
  7989. if (!EvaluateFloat(E->getArg(5), Val, Info))
  7990. return false;
  7991. unsigned Arg;
  7992. switch (Val.getCategory()) {
  7993. case APFloat::fcNaN: Arg = 0; break;
  7994. case APFloat::fcInfinity: Arg = 1; break;
  7995. case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
  7996. case APFloat::fcZero: Arg = 4; break;
  7997. }
  7998. return Visit(E->getArg(Arg));
  7999. }
  8000. case Builtin::BI__builtin_isinf_sign: {
  8001. APFloat Val(0.0);
  8002. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8003. Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
  8004. }
  8005. case Builtin::BI__builtin_isinf: {
  8006. APFloat Val(0.0);
  8007. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8008. Success(Val.isInfinity() ? 1 : 0, E);
  8009. }
  8010. case Builtin::BI__builtin_isfinite: {
  8011. APFloat Val(0.0);
  8012. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8013. Success(Val.isFinite() ? 1 : 0, E);
  8014. }
  8015. case Builtin::BI__builtin_isnan: {
  8016. APFloat Val(0.0);
  8017. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8018. Success(Val.isNaN() ? 1 : 0, E);
  8019. }
  8020. case Builtin::BI__builtin_isnormal: {
  8021. APFloat Val(0.0);
  8022. return EvaluateFloat(E->getArg(0), Val, Info) &&
  8023. Success(Val.isNormal() ? 1 : 0, E);
  8024. }
  8025. case Builtin::BI__builtin_parity:
  8026. case Builtin::BI__builtin_parityl:
  8027. case Builtin::BI__builtin_parityll: {
  8028. APSInt Val;
  8029. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8030. return false;
  8031. return Success(Val.countPopulation() % 2, E);
  8032. }
  8033. case Builtin::BI__builtin_popcount:
  8034. case Builtin::BI__builtin_popcountl:
  8035. case Builtin::BI__builtin_popcountll: {
  8036. APSInt Val;
  8037. if (!EvaluateInteger(E->getArg(0), Val, Info))
  8038. return false;
  8039. return Success(Val.countPopulation(), E);
  8040. }
  8041. case Builtin::BIstrlen:
  8042. case Builtin::BIwcslen:
  8043. // A call to strlen is not a constant expression.
  8044. if (Info.getLangOpts().CPlusPlus11)
  8045. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8046. << /*isConstexpr*/0 << /*isConstructor*/0
  8047. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8048. else
  8049. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8050. LLVM_FALLTHROUGH;
  8051. case Builtin::BI__builtin_strlen:
  8052. case Builtin::BI__builtin_wcslen: {
  8053. // As an extension, we support __builtin_strlen() as a constant expression,
  8054. // and support folding strlen() to a constant.
  8055. LValue String;
  8056. if (!EvaluatePointer(E->getArg(0), String, Info))
  8057. return false;
  8058. QualType CharTy = E->getArg(0)->getType()->getPointeeType();
  8059. // Fast path: if it's a string literal, search the string value.
  8060. if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
  8061. String.getLValueBase().dyn_cast<const Expr *>())) {
  8062. // The string literal may have embedded null characters. Find the first
  8063. // one and truncate there.
  8064. StringRef Str = S->getBytes();
  8065. int64_t Off = String.Offset.getQuantity();
  8066. if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
  8067. S->getCharByteWidth() == 1 &&
  8068. // FIXME: Add fast-path for wchar_t too.
  8069. Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
  8070. Str = Str.substr(Off);
  8071. StringRef::size_type Pos = Str.find(0);
  8072. if (Pos != StringRef::npos)
  8073. Str = Str.substr(0, Pos);
  8074. return Success(Str.size(), E);
  8075. }
  8076. // Fall through to slow path to issue appropriate diagnostic.
  8077. }
  8078. // Slow path: scan the bytes of the string looking for the terminating 0.
  8079. for (uint64_t Strlen = 0; /**/; ++Strlen) {
  8080. APValue Char;
  8081. if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
  8082. !Char.isInt())
  8083. return false;
  8084. if (!Char.getInt())
  8085. return Success(Strlen, E);
  8086. if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
  8087. return false;
  8088. }
  8089. }
  8090. case Builtin::BIstrcmp:
  8091. case Builtin::BIwcscmp:
  8092. case Builtin::BIstrncmp:
  8093. case Builtin::BIwcsncmp:
  8094. case Builtin::BImemcmp:
  8095. case Builtin::BIbcmp:
  8096. case Builtin::BIwmemcmp:
  8097. // A call to strlen is not a constant expression.
  8098. if (Info.getLangOpts().CPlusPlus11)
  8099. Info.CCEDiag(E, diag::note_constexpr_invalid_function)
  8100. << /*isConstexpr*/0 << /*isConstructor*/0
  8101. << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
  8102. else
  8103. Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8104. LLVM_FALLTHROUGH;
  8105. case Builtin::BI__builtin_strcmp:
  8106. case Builtin::BI__builtin_wcscmp:
  8107. case Builtin::BI__builtin_strncmp:
  8108. case Builtin::BI__builtin_wcsncmp:
  8109. case Builtin::BI__builtin_memcmp:
  8110. case Builtin::BI__builtin_bcmp:
  8111. case Builtin::BI__builtin_wmemcmp: {
  8112. LValue String1, String2;
  8113. if (!EvaluatePointer(E->getArg(0), String1, Info) ||
  8114. !EvaluatePointer(E->getArg(1), String2, Info))
  8115. return false;
  8116. uint64_t MaxLength = uint64_t(-1);
  8117. if (BuiltinOp != Builtin::BIstrcmp &&
  8118. BuiltinOp != Builtin::BIwcscmp &&
  8119. BuiltinOp != Builtin::BI__builtin_strcmp &&
  8120. BuiltinOp != Builtin::BI__builtin_wcscmp) {
  8121. APSInt N;
  8122. if (!EvaluateInteger(E->getArg(2), N, Info))
  8123. return false;
  8124. MaxLength = N.getExtValue();
  8125. }
  8126. // Empty substrings compare equal by definition.
  8127. if (MaxLength == 0u)
  8128. return Success(0, E);
  8129. if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8130. !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
  8131. String1.Designator.Invalid || String2.Designator.Invalid)
  8132. return false;
  8133. QualType CharTy1 = String1.Designator.getType(Info.Ctx);
  8134. QualType CharTy2 = String2.Designator.getType(Info.Ctx);
  8135. bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
  8136. BuiltinOp == Builtin::BIbcmp ||
  8137. BuiltinOp == Builtin::BI__builtin_memcmp ||
  8138. BuiltinOp == Builtin::BI__builtin_bcmp;
  8139. assert(IsRawByte ||
  8140. (Info.Ctx.hasSameUnqualifiedType(
  8141. CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
  8142. Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
  8143. const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
  8144. return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
  8145. handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
  8146. Char1.isInt() && Char2.isInt();
  8147. };
  8148. const auto &AdvanceElems = [&] {
  8149. return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
  8150. HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
  8151. };
  8152. if (IsRawByte) {
  8153. uint64_t BytesRemaining = MaxLength;
  8154. // Pointers to const void may point to objects of incomplete type.
  8155. if (CharTy1->isIncompleteType()) {
  8156. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
  8157. return false;
  8158. }
  8159. if (CharTy2->isIncompleteType()) {
  8160. Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
  8161. return false;
  8162. }
  8163. uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
  8164. CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
  8165. // Give up on comparing between elements with disparate widths.
  8166. if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
  8167. return false;
  8168. uint64_t BytesPerElement = CharTy1Size.getQuantity();
  8169. assert(BytesRemaining && "BytesRemaining should not be zero: the "
  8170. "following loop considers at least one element");
  8171. while (true) {
  8172. APValue Char1, Char2;
  8173. if (!ReadCurElems(Char1, Char2))
  8174. return false;
  8175. // We have compatible in-memory widths, but a possible type and
  8176. // (for `bool`) internal representation mismatch.
  8177. // Assuming two's complement representation, including 0 for `false` and
  8178. // 1 for `true`, we can check an appropriate number of elements for
  8179. // equality even if they are not byte-sized.
  8180. APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
  8181. APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
  8182. if (Char1InMem.ne(Char2InMem)) {
  8183. // If the elements are byte-sized, then we can produce a three-way
  8184. // comparison result in a straightforward manner.
  8185. if (BytesPerElement == 1u) {
  8186. // memcmp always compares unsigned chars.
  8187. return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
  8188. }
  8189. // The result is byte-order sensitive, and we have multibyte elements.
  8190. // FIXME: We can compare the remaining bytes in the correct order.
  8191. return false;
  8192. }
  8193. if (!AdvanceElems())
  8194. return false;
  8195. if (BytesRemaining <= BytesPerElement)
  8196. break;
  8197. BytesRemaining -= BytesPerElement;
  8198. }
  8199. // Enough elements are equal to account for the memcmp limit.
  8200. return Success(0, E);
  8201. }
  8202. bool StopAtNull =
  8203. (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
  8204. BuiltinOp != Builtin::BIwmemcmp &&
  8205. BuiltinOp != Builtin::BI__builtin_memcmp &&
  8206. BuiltinOp != Builtin::BI__builtin_bcmp &&
  8207. BuiltinOp != Builtin::BI__builtin_wmemcmp);
  8208. bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
  8209. BuiltinOp == Builtin::BIwcsncmp ||
  8210. BuiltinOp == Builtin::BIwmemcmp ||
  8211. BuiltinOp == Builtin::BI__builtin_wcscmp ||
  8212. BuiltinOp == Builtin::BI__builtin_wcsncmp ||
  8213. BuiltinOp == Builtin::BI__builtin_wmemcmp;
  8214. for (; MaxLength; --MaxLength) {
  8215. APValue Char1, Char2;
  8216. if (!ReadCurElems(Char1, Char2))
  8217. return false;
  8218. if (Char1.getInt() != Char2.getInt()) {
  8219. if (IsWide) // wmemcmp compares with wchar_t signedness.
  8220. return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
  8221. // memcmp always compares unsigned chars.
  8222. return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
  8223. }
  8224. if (StopAtNull && !Char1.getInt())
  8225. return Success(0, E);
  8226. assert(!(StopAtNull && !Char2.getInt()));
  8227. if (!AdvanceElems())
  8228. return false;
  8229. }
  8230. // We hit the strncmp / memcmp limit.
  8231. return Success(0, E);
  8232. }
  8233. case Builtin::BI__atomic_always_lock_free:
  8234. case Builtin::BI__atomic_is_lock_free:
  8235. case Builtin::BI__c11_atomic_is_lock_free: {
  8236. APSInt SizeVal;
  8237. if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
  8238. return false;
  8239. // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
  8240. // of two less than the maximum inline atomic width, we know it is
  8241. // lock-free. If the size isn't a power of two, or greater than the
  8242. // maximum alignment where we promote atomics, we know it is not lock-free
  8243. // (at least not in the sense of atomic_is_lock_free). Otherwise,
  8244. // the answer can only be determined at runtime; for example, 16-byte
  8245. // atomics have lock-free implementations on some, but not all,
  8246. // x86-64 processors.
  8247. // Check power-of-two.
  8248. CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
  8249. if (Size.isPowerOfTwo()) {
  8250. // Check against inlining width.
  8251. unsigned InlineWidthBits =
  8252. Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
  8253. if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
  8254. if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
  8255. Size == CharUnits::One() ||
  8256. E->getArg(1)->isNullPointerConstant(Info.Ctx,
  8257. Expr::NPC_NeverValueDependent))
  8258. // OK, we will inline appropriately-aligned operations of this size,
  8259. // and _Atomic(T) is appropriately-aligned.
  8260. return Success(1, E);
  8261. QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
  8262. castAs<PointerType>()->getPointeeType();
  8263. if (!PointeeType->isIncompleteType() &&
  8264. Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
  8265. // OK, we will inline operations on this object.
  8266. return Success(1, E);
  8267. }
  8268. }
  8269. }
  8270. return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
  8271. Success(0, E) : Error(E);
  8272. }
  8273. case Builtin::BIomp_is_initial_device:
  8274. // We can decide statically which value the runtime would return if called.
  8275. return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
  8276. case Builtin::BI__builtin_add_overflow:
  8277. case Builtin::BI__builtin_sub_overflow:
  8278. case Builtin::BI__builtin_mul_overflow:
  8279. case Builtin::BI__builtin_sadd_overflow:
  8280. case Builtin::BI__builtin_uadd_overflow:
  8281. case Builtin::BI__builtin_uaddl_overflow:
  8282. case Builtin::BI__builtin_uaddll_overflow:
  8283. case Builtin::BI__builtin_usub_overflow:
  8284. case Builtin::BI__builtin_usubl_overflow:
  8285. case Builtin::BI__builtin_usubll_overflow:
  8286. case Builtin::BI__builtin_umul_overflow:
  8287. case Builtin::BI__builtin_umull_overflow:
  8288. case Builtin::BI__builtin_umulll_overflow:
  8289. case Builtin::BI__builtin_saddl_overflow:
  8290. case Builtin::BI__builtin_saddll_overflow:
  8291. case Builtin::BI__builtin_ssub_overflow:
  8292. case Builtin::BI__builtin_ssubl_overflow:
  8293. case Builtin::BI__builtin_ssubll_overflow:
  8294. case Builtin::BI__builtin_smul_overflow:
  8295. case Builtin::BI__builtin_smull_overflow:
  8296. case Builtin::BI__builtin_smulll_overflow: {
  8297. LValue ResultLValue;
  8298. APSInt LHS, RHS;
  8299. QualType ResultType = E->getArg(2)->getType()->getPointeeType();
  8300. if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
  8301. !EvaluateInteger(E->getArg(1), RHS, Info) ||
  8302. !EvaluatePointer(E->getArg(2), ResultLValue, Info))
  8303. return false;
  8304. APSInt Result;
  8305. bool DidOverflow = false;
  8306. // If the types don't have to match, enlarge all 3 to the largest of them.
  8307. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8308. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8309. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8310. bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
  8311. ResultType->isSignedIntegerOrEnumerationType();
  8312. bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
  8313. ResultType->isSignedIntegerOrEnumerationType();
  8314. uint64_t LHSSize = LHS.getBitWidth();
  8315. uint64_t RHSSize = RHS.getBitWidth();
  8316. uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
  8317. uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
  8318. // Add an additional bit if the signedness isn't uniformly agreed to. We
  8319. // could do this ONLY if there is a signed and an unsigned that both have
  8320. // MaxBits, but the code to check that is pretty nasty. The issue will be
  8321. // caught in the shrink-to-result later anyway.
  8322. if (IsSigned && !AllSigned)
  8323. ++MaxBits;
  8324. LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
  8325. RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
  8326. Result = APSInt(MaxBits, !IsSigned);
  8327. }
  8328. // Find largest int.
  8329. switch (BuiltinOp) {
  8330. default:
  8331. llvm_unreachable("Invalid value for BuiltinOp");
  8332. case Builtin::BI__builtin_add_overflow:
  8333. case Builtin::BI__builtin_sadd_overflow:
  8334. case Builtin::BI__builtin_saddl_overflow:
  8335. case Builtin::BI__builtin_saddll_overflow:
  8336. case Builtin::BI__builtin_uadd_overflow:
  8337. case Builtin::BI__builtin_uaddl_overflow:
  8338. case Builtin::BI__builtin_uaddll_overflow:
  8339. Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
  8340. : LHS.uadd_ov(RHS, DidOverflow);
  8341. break;
  8342. case Builtin::BI__builtin_sub_overflow:
  8343. case Builtin::BI__builtin_ssub_overflow:
  8344. case Builtin::BI__builtin_ssubl_overflow:
  8345. case Builtin::BI__builtin_ssubll_overflow:
  8346. case Builtin::BI__builtin_usub_overflow:
  8347. case Builtin::BI__builtin_usubl_overflow:
  8348. case Builtin::BI__builtin_usubll_overflow:
  8349. Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
  8350. : LHS.usub_ov(RHS, DidOverflow);
  8351. break;
  8352. case Builtin::BI__builtin_mul_overflow:
  8353. case Builtin::BI__builtin_smul_overflow:
  8354. case Builtin::BI__builtin_smull_overflow:
  8355. case Builtin::BI__builtin_smulll_overflow:
  8356. case Builtin::BI__builtin_umul_overflow:
  8357. case Builtin::BI__builtin_umull_overflow:
  8358. case Builtin::BI__builtin_umulll_overflow:
  8359. Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
  8360. : LHS.umul_ov(RHS, DidOverflow);
  8361. break;
  8362. }
  8363. // In the case where multiple sizes are allowed, truncate and see if
  8364. // the values are the same.
  8365. if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
  8366. BuiltinOp == Builtin::BI__builtin_sub_overflow ||
  8367. BuiltinOp == Builtin::BI__builtin_mul_overflow) {
  8368. // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
  8369. // since it will give us the behavior of a TruncOrSelf in the case where
  8370. // its parameter <= its size. We previously set Result to be at least the
  8371. // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
  8372. // will work exactly like TruncOrSelf.
  8373. APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
  8374. Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
  8375. if (!APSInt::isSameValue(Temp, Result))
  8376. DidOverflow = true;
  8377. Result = Temp;
  8378. }
  8379. APValue APV{Result};
  8380. if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
  8381. return false;
  8382. return Success(DidOverflow, E);
  8383. }
  8384. }
  8385. }
  8386. /// Determine whether this is a pointer past the end of the complete
  8387. /// object referred to by the lvalue.
  8388. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
  8389. const LValue &LV) {
  8390. // A null pointer can be viewed as being "past the end" but we don't
  8391. // choose to look at it that way here.
  8392. if (!LV.getLValueBase())
  8393. return false;
  8394. // If the designator is valid and refers to a subobject, we're not pointing
  8395. // past the end.
  8396. if (!LV.getLValueDesignator().Invalid &&
  8397. !LV.getLValueDesignator().isOnePastTheEnd())
  8398. return false;
  8399. // A pointer to an incomplete type might be past-the-end if the type's size is
  8400. // zero. We cannot tell because the type is incomplete.
  8401. QualType Ty = getType(LV.getLValueBase());
  8402. if (Ty->isIncompleteType())
  8403. return true;
  8404. // We're a past-the-end pointer if we point to the byte after the object,
  8405. // no matter what our type or path is.
  8406. auto Size = Ctx.getTypeSizeInChars(Ty);
  8407. return LV.getLValueOffset() == Size;
  8408. }
  8409. namespace {
  8410. /// Data recursive integer evaluator of certain binary operators.
  8411. ///
  8412. /// We use a data recursive algorithm for binary operators so that we are able
  8413. /// to handle extreme cases of chained binary operators without causing stack
  8414. /// overflow.
  8415. class DataRecursiveIntBinOpEvaluator {
  8416. struct EvalResult {
  8417. APValue Val;
  8418. bool Failed;
  8419. EvalResult() : Failed(false) { }
  8420. void swap(EvalResult &RHS) {
  8421. Val.swap(RHS.Val);
  8422. Failed = RHS.Failed;
  8423. RHS.Failed = false;
  8424. }
  8425. };
  8426. struct Job {
  8427. const Expr *E;
  8428. EvalResult LHSResult; // meaningful only for binary operator expression.
  8429. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
  8430. Job() = default;
  8431. Job(Job &&) = default;
  8432. void startSpeculativeEval(EvalInfo &Info) {
  8433. SpecEvalRAII = SpeculativeEvaluationRAII(Info);
  8434. }
  8435. private:
  8436. SpeculativeEvaluationRAII SpecEvalRAII;
  8437. };
  8438. SmallVector<Job, 16> Queue;
  8439. IntExprEvaluator &IntEval;
  8440. EvalInfo &Info;
  8441. APValue &FinalResult;
  8442. public:
  8443. DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
  8444. : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
  8445. /// True if \param E is a binary operator that we are going to handle
  8446. /// data recursively.
  8447. /// We handle binary operators that are comma, logical, or that have operands
  8448. /// with integral or enumeration type.
  8449. static bool shouldEnqueue(const BinaryOperator *E) {
  8450. return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
  8451. (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
  8452. E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8453. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8454. }
  8455. bool Traverse(const BinaryOperator *E) {
  8456. enqueue(E);
  8457. EvalResult PrevResult;
  8458. while (!Queue.empty())
  8459. process(PrevResult);
  8460. if (PrevResult.Failed) return false;
  8461. FinalResult.swap(PrevResult.Val);
  8462. return true;
  8463. }
  8464. private:
  8465. bool Success(uint64_t Value, const Expr *E, APValue &Result) {
  8466. return IntEval.Success(Value, E, Result);
  8467. }
  8468. bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
  8469. return IntEval.Success(Value, E, Result);
  8470. }
  8471. bool Error(const Expr *E) {
  8472. return IntEval.Error(E);
  8473. }
  8474. bool Error(const Expr *E, diag::kind D) {
  8475. return IntEval.Error(E, D);
  8476. }
  8477. OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
  8478. return Info.CCEDiag(E, D);
  8479. }
  8480. // Returns true if visiting the RHS is necessary, false otherwise.
  8481. bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8482. bool &SuppressRHSDiags);
  8483. bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8484. const BinaryOperator *E, APValue &Result);
  8485. void EvaluateExpr(const Expr *E, EvalResult &Result) {
  8486. Result.Failed = !Evaluate(Result.Val, Info, E);
  8487. if (Result.Failed)
  8488. Result.Val = APValue();
  8489. }
  8490. void process(EvalResult &Result);
  8491. void enqueue(const Expr *E) {
  8492. E = E->IgnoreParens();
  8493. Queue.resize(Queue.size()+1);
  8494. Queue.back().E = E;
  8495. Queue.back().Kind = Job::AnyExprKind;
  8496. }
  8497. };
  8498. }
  8499. bool DataRecursiveIntBinOpEvaluator::
  8500. VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
  8501. bool &SuppressRHSDiags) {
  8502. if (E->getOpcode() == BO_Comma) {
  8503. // Ignore LHS but note if we could not evaluate it.
  8504. if (LHSResult.Failed)
  8505. return Info.noteSideEffect();
  8506. return true;
  8507. }
  8508. if (E->isLogicalOp()) {
  8509. bool LHSAsBool;
  8510. if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
  8511. // We were able to evaluate the LHS, see if we can get away with not
  8512. // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
  8513. if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
  8514. Success(LHSAsBool, E, LHSResult.Val);
  8515. return false; // Ignore RHS
  8516. }
  8517. } else {
  8518. LHSResult.Failed = true;
  8519. // Since we weren't able to evaluate the left hand side, it
  8520. // might have had side effects.
  8521. if (!Info.noteSideEffect())
  8522. return false;
  8523. // We can't evaluate the LHS; however, sometimes the result
  8524. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8525. // Don't ignore RHS and suppress diagnostics from this arm.
  8526. SuppressRHSDiags = true;
  8527. }
  8528. return true;
  8529. }
  8530. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8531. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8532. if (LHSResult.Failed && !Info.noteFailure())
  8533. return false; // Ignore RHS;
  8534. return true;
  8535. }
  8536. static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
  8537. bool IsSub) {
  8538. // Compute the new offset in the appropriate width, wrapping at 64 bits.
  8539. // FIXME: When compiling for a 32-bit target, we should use 32-bit
  8540. // offsets.
  8541. assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
  8542. CharUnits &Offset = LVal.getLValueOffset();
  8543. uint64_t Offset64 = Offset.getQuantity();
  8544. uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
  8545. Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
  8546. : Offset64 + Index64);
  8547. }
  8548. bool DataRecursiveIntBinOpEvaluator::
  8549. VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
  8550. const BinaryOperator *E, APValue &Result) {
  8551. if (E->getOpcode() == BO_Comma) {
  8552. if (RHSResult.Failed)
  8553. return false;
  8554. Result = RHSResult.Val;
  8555. return true;
  8556. }
  8557. if (E->isLogicalOp()) {
  8558. bool lhsResult, rhsResult;
  8559. bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
  8560. bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
  8561. if (LHSIsOK) {
  8562. if (RHSIsOK) {
  8563. if (E->getOpcode() == BO_LOr)
  8564. return Success(lhsResult || rhsResult, E, Result);
  8565. else
  8566. return Success(lhsResult && rhsResult, E, Result);
  8567. }
  8568. } else {
  8569. if (RHSIsOK) {
  8570. // We can't evaluate the LHS; however, sometimes the result
  8571. // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
  8572. if (rhsResult == (E->getOpcode() == BO_LOr))
  8573. return Success(rhsResult, E, Result);
  8574. }
  8575. }
  8576. return false;
  8577. }
  8578. assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
  8579. E->getRHS()->getType()->isIntegralOrEnumerationType());
  8580. if (LHSResult.Failed || RHSResult.Failed)
  8581. return false;
  8582. const APValue &LHSVal = LHSResult.Val;
  8583. const APValue &RHSVal = RHSResult.Val;
  8584. // Handle cases like (unsigned long)&a + 4.
  8585. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
  8586. Result = LHSVal;
  8587. addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
  8588. return true;
  8589. }
  8590. // Handle cases like 4 + (unsigned long)&a
  8591. if (E->getOpcode() == BO_Add &&
  8592. RHSVal.isLValue() && LHSVal.isInt()) {
  8593. Result = RHSVal;
  8594. addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
  8595. return true;
  8596. }
  8597. if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
  8598. // Handle (intptr_t)&&A - (intptr_t)&&B.
  8599. if (!LHSVal.getLValueOffset().isZero() ||
  8600. !RHSVal.getLValueOffset().isZero())
  8601. return false;
  8602. const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
  8603. const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
  8604. if (!LHSExpr || !RHSExpr)
  8605. return false;
  8606. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  8607. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  8608. if (!LHSAddrExpr || !RHSAddrExpr)
  8609. return false;
  8610. // Make sure both labels come from the same function.
  8611. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  8612. RHSAddrExpr->getLabel()->getDeclContext())
  8613. return false;
  8614. Result = APValue(LHSAddrExpr, RHSAddrExpr);
  8615. return true;
  8616. }
  8617. // All the remaining cases expect both operands to be an integer
  8618. if (!LHSVal.isInt() || !RHSVal.isInt())
  8619. return Error(E);
  8620. // Set up the width and signedness manually, in case it can't be deduced
  8621. // from the operation we're performing.
  8622. // FIXME: Don't do this in the cases where we can deduce it.
  8623. APSInt Value(Info.Ctx.getIntWidth(E->getType()),
  8624. E->getType()->isUnsignedIntegerOrEnumerationType());
  8625. if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
  8626. RHSVal.getInt(), Value))
  8627. return false;
  8628. return Success(Value, E, Result);
  8629. }
  8630. void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
  8631. Job &job = Queue.back();
  8632. switch (job.Kind) {
  8633. case Job::AnyExprKind: {
  8634. if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
  8635. if (shouldEnqueue(Bop)) {
  8636. job.Kind = Job::BinOpKind;
  8637. enqueue(Bop->getLHS());
  8638. return;
  8639. }
  8640. }
  8641. EvaluateExpr(job.E, Result);
  8642. Queue.pop_back();
  8643. return;
  8644. }
  8645. case Job::BinOpKind: {
  8646. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  8647. bool SuppressRHSDiags = false;
  8648. if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
  8649. Queue.pop_back();
  8650. return;
  8651. }
  8652. if (SuppressRHSDiags)
  8653. job.startSpeculativeEval(Info);
  8654. job.LHSResult.swap(Result);
  8655. job.Kind = Job::BinOpVisitedLHSKind;
  8656. enqueue(Bop->getRHS());
  8657. return;
  8658. }
  8659. case Job::BinOpVisitedLHSKind: {
  8660. const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
  8661. EvalResult RHS;
  8662. RHS.swap(Result);
  8663. Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
  8664. Queue.pop_back();
  8665. return;
  8666. }
  8667. }
  8668. llvm_unreachable("Invalid Job::Kind!");
  8669. }
  8670. namespace {
  8671. /// Used when we determine that we should fail, but can keep evaluating prior to
  8672. /// noting that we had a failure.
  8673. class DelayedNoteFailureRAII {
  8674. EvalInfo &Info;
  8675. bool NoteFailure;
  8676. public:
  8677. DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
  8678. : Info(Info), NoteFailure(NoteFailure) {}
  8679. ~DelayedNoteFailureRAII() {
  8680. if (NoteFailure) {
  8681. bool ContinueAfterFailure = Info.noteFailure();
  8682. (void)ContinueAfterFailure;
  8683. assert(ContinueAfterFailure &&
  8684. "Shouldn't have kept evaluating on failure.");
  8685. }
  8686. }
  8687. };
  8688. }
  8689. template <class SuccessCB, class AfterCB>
  8690. static bool
  8691. EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
  8692. SuccessCB &&Success, AfterCB &&DoAfter) {
  8693. assert(E->isComparisonOp() && "expected comparison operator");
  8694. assert((E->getOpcode() == BO_Cmp ||
  8695. E->getType()->isIntegralOrEnumerationType()) &&
  8696. "unsupported binary expression evaluation");
  8697. auto Error = [&](const Expr *E) {
  8698. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  8699. return false;
  8700. };
  8701. using CCR = ComparisonCategoryResult;
  8702. bool IsRelational = E->isRelationalOp();
  8703. bool IsEquality = E->isEqualityOp();
  8704. if (E->getOpcode() == BO_Cmp) {
  8705. const ComparisonCategoryInfo &CmpInfo =
  8706. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8707. IsRelational = CmpInfo.isOrdered();
  8708. IsEquality = CmpInfo.isEquality();
  8709. }
  8710. QualType LHSTy = E->getLHS()->getType();
  8711. QualType RHSTy = E->getRHS()->getType();
  8712. if (LHSTy->isIntegralOrEnumerationType() &&
  8713. RHSTy->isIntegralOrEnumerationType()) {
  8714. APSInt LHS, RHS;
  8715. bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
  8716. if (!LHSOK && !Info.noteFailure())
  8717. return false;
  8718. if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
  8719. return false;
  8720. if (LHS < RHS)
  8721. return Success(CCR::Less, E);
  8722. if (LHS > RHS)
  8723. return Success(CCR::Greater, E);
  8724. return Success(CCR::Equal, E);
  8725. }
  8726. if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
  8727. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
  8728. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
  8729. bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
  8730. if (!LHSOK && !Info.noteFailure())
  8731. return false;
  8732. if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
  8733. return false;
  8734. if (LHSFX < RHSFX)
  8735. return Success(CCR::Less, E);
  8736. if (LHSFX > RHSFX)
  8737. return Success(CCR::Greater, E);
  8738. return Success(CCR::Equal, E);
  8739. }
  8740. if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
  8741. ComplexValue LHS, RHS;
  8742. bool LHSOK;
  8743. if (E->isAssignmentOp()) {
  8744. LValue LV;
  8745. EvaluateLValue(E->getLHS(), LV, Info);
  8746. LHSOK = false;
  8747. } else if (LHSTy->isRealFloatingType()) {
  8748. LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
  8749. if (LHSOK) {
  8750. LHS.makeComplexFloat();
  8751. LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
  8752. }
  8753. } else {
  8754. LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
  8755. }
  8756. if (!LHSOK && !Info.noteFailure())
  8757. return false;
  8758. if (E->getRHS()->getType()->isRealFloatingType()) {
  8759. if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
  8760. return false;
  8761. RHS.makeComplexFloat();
  8762. RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
  8763. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  8764. return false;
  8765. if (LHS.isComplexFloat()) {
  8766. APFloat::cmpResult CR_r =
  8767. LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
  8768. APFloat::cmpResult CR_i =
  8769. LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
  8770. bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
  8771. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  8772. } else {
  8773. assert(IsEquality && "invalid complex comparison");
  8774. bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
  8775. LHS.getComplexIntImag() == RHS.getComplexIntImag();
  8776. return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
  8777. }
  8778. }
  8779. if (LHSTy->isRealFloatingType() &&
  8780. RHSTy->isRealFloatingType()) {
  8781. APFloat RHS(0.0), LHS(0.0);
  8782. bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
  8783. if (!LHSOK && !Info.noteFailure())
  8784. return false;
  8785. if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
  8786. return false;
  8787. assert(E->isComparisonOp() && "Invalid binary operator!");
  8788. auto GetCmpRes = [&]() {
  8789. switch (LHS.compare(RHS)) {
  8790. case APFloat::cmpEqual:
  8791. return CCR::Equal;
  8792. case APFloat::cmpLessThan:
  8793. return CCR::Less;
  8794. case APFloat::cmpGreaterThan:
  8795. return CCR::Greater;
  8796. case APFloat::cmpUnordered:
  8797. return CCR::Unordered;
  8798. }
  8799. llvm_unreachable("Unrecognised APFloat::cmpResult enum");
  8800. };
  8801. return Success(GetCmpRes(), E);
  8802. }
  8803. if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
  8804. LValue LHSValue, RHSValue;
  8805. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  8806. if (!LHSOK && !Info.noteFailure())
  8807. return false;
  8808. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8809. return false;
  8810. // Reject differing bases from the normal codepath; we special-case
  8811. // comparisons to null.
  8812. if (!HasSameBase(LHSValue, RHSValue)) {
  8813. // Inequalities and subtractions between unrelated pointers have
  8814. // unspecified or undefined behavior.
  8815. if (!IsEquality)
  8816. return Error(E);
  8817. // A constant address may compare equal to the address of a symbol.
  8818. // The one exception is that address of an object cannot compare equal
  8819. // to a null pointer constant.
  8820. if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
  8821. (!RHSValue.Base && !RHSValue.Offset.isZero()))
  8822. return Error(E);
  8823. // It's implementation-defined whether distinct literals will have
  8824. // distinct addresses. In clang, the result of such a comparison is
  8825. // unspecified, so it is not a constant expression. However, we do know
  8826. // that the address of a literal will be non-null.
  8827. if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
  8828. LHSValue.Base && RHSValue.Base)
  8829. return Error(E);
  8830. // We can't tell whether weak symbols will end up pointing to the same
  8831. // object.
  8832. if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
  8833. return Error(E);
  8834. // We can't compare the address of the start of one object with the
  8835. // past-the-end address of another object, per C++ DR1652.
  8836. if ((LHSValue.Base && LHSValue.Offset.isZero() &&
  8837. isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
  8838. (RHSValue.Base && RHSValue.Offset.isZero() &&
  8839. isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
  8840. return Error(E);
  8841. // We can't tell whether an object is at the same address as another
  8842. // zero sized object.
  8843. if ((RHSValue.Base && isZeroSized(LHSValue)) ||
  8844. (LHSValue.Base && isZeroSized(RHSValue)))
  8845. return Error(E);
  8846. return Success(CCR::Nonequal, E);
  8847. }
  8848. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  8849. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  8850. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  8851. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  8852. // C++11 [expr.rel]p3:
  8853. // Pointers to void (after pointer conversions) can be compared, with a
  8854. // result defined as follows: If both pointers represent the same
  8855. // address or are both the null pointer value, the result is true if the
  8856. // operator is <= or >= and false otherwise; otherwise the result is
  8857. // unspecified.
  8858. // We interpret this as applying to pointers to *cv* void.
  8859. if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
  8860. Info.CCEDiag(E, diag::note_constexpr_void_comparison);
  8861. // C++11 [expr.rel]p2:
  8862. // - If two pointers point to non-static data members of the same object,
  8863. // or to subobjects or array elements fo such members, recursively, the
  8864. // pointer to the later declared member compares greater provided the
  8865. // two members have the same access control and provided their class is
  8866. // not a union.
  8867. // [...]
  8868. // - Otherwise pointer comparisons are unspecified.
  8869. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
  8870. bool WasArrayIndex;
  8871. unsigned Mismatch = FindDesignatorMismatch(
  8872. getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
  8873. // At the point where the designators diverge, the comparison has a
  8874. // specified value if:
  8875. // - we are comparing array indices
  8876. // - we are comparing fields of a union, or fields with the same access
  8877. // Otherwise, the result is unspecified and thus the comparison is not a
  8878. // constant expression.
  8879. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
  8880. Mismatch < RHSDesignator.Entries.size()) {
  8881. const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
  8882. const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
  8883. if (!LF && !RF)
  8884. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
  8885. else if (!LF)
  8886. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8887. << getAsBaseClass(LHSDesignator.Entries[Mismatch])
  8888. << RF->getParent() << RF;
  8889. else if (!RF)
  8890. Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
  8891. << getAsBaseClass(RHSDesignator.Entries[Mismatch])
  8892. << LF->getParent() << LF;
  8893. else if (!LF->getParent()->isUnion() &&
  8894. LF->getAccess() != RF->getAccess())
  8895. Info.CCEDiag(E,
  8896. diag::note_constexpr_pointer_comparison_differing_access)
  8897. << LF << LF->getAccess() << RF << RF->getAccess()
  8898. << LF->getParent();
  8899. }
  8900. }
  8901. // The comparison here must be unsigned, and performed with the same
  8902. // width as the pointer.
  8903. unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
  8904. uint64_t CompareLHS = LHSOffset.getQuantity();
  8905. uint64_t CompareRHS = RHSOffset.getQuantity();
  8906. assert(PtrSize <= 64 && "Unexpected pointer width");
  8907. uint64_t Mask = ~0ULL >> (64 - PtrSize);
  8908. CompareLHS &= Mask;
  8909. CompareRHS &= Mask;
  8910. // If there is a base and this is a relational operator, we can only
  8911. // compare pointers within the object in question; otherwise, the result
  8912. // depends on where the object is located in memory.
  8913. if (!LHSValue.Base.isNull() && IsRelational) {
  8914. QualType BaseTy = getType(LHSValue.Base);
  8915. if (BaseTy->isIncompleteType())
  8916. return Error(E);
  8917. CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
  8918. uint64_t OffsetLimit = Size.getQuantity();
  8919. if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
  8920. return Error(E);
  8921. }
  8922. if (CompareLHS < CompareRHS)
  8923. return Success(CCR::Less, E);
  8924. if (CompareLHS > CompareRHS)
  8925. return Success(CCR::Greater, E);
  8926. return Success(CCR::Equal, E);
  8927. }
  8928. if (LHSTy->isMemberPointerType()) {
  8929. assert(IsEquality && "unexpected member pointer operation");
  8930. assert(RHSTy->isMemberPointerType() && "invalid comparison");
  8931. MemberPtr LHSValue, RHSValue;
  8932. bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
  8933. if (!LHSOK && !Info.noteFailure())
  8934. return false;
  8935. if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  8936. return false;
  8937. // C++11 [expr.eq]p2:
  8938. // If both operands are null, they compare equal. Otherwise if only one is
  8939. // null, they compare unequal.
  8940. if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
  8941. bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
  8942. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8943. }
  8944. // Otherwise if either is a pointer to a virtual member function, the
  8945. // result is unspecified.
  8946. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
  8947. if (MD->isVirtual())
  8948. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8949. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
  8950. if (MD->isVirtual())
  8951. Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
  8952. // Otherwise they compare equal if and only if they would refer to the
  8953. // same member of the same most derived object or the same subobject if
  8954. // they were dereferenced with a hypothetical object of the associated
  8955. // class type.
  8956. bool Equal = LHSValue == RHSValue;
  8957. return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
  8958. }
  8959. if (LHSTy->isNullPtrType()) {
  8960. assert(E->isComparisonOp() && "unexpected nullptr operation");
  8961. assert(RHSTy->isNullPtrType() && "missing pointer conversion");
  8962. // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
  8963. // are compared, the result is true of the operator is <=, >= or ==, and
  8964. // false otherwise.
  8965. return Success(CCR::Equal, E);
  8966. }
  8967. return DoAfter();
  8968. }
  8969. bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
  8970. if (!CheckLiteralType(Info, E))
  8971. return false;
  8972. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  8973. const BinaryOperator *E) {
  8974. // Evaluation succeeded. Lookup the information for the comparison category
  8975. // type and fetch the VarDecl for the result.
  8976. const ComparisonCategoryInfo &CmpInfo =
  8977. Info.Ctx.CompCategories.getInfoForType(E->getType());
  8978. const VarDecl *VD =
  8979. CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
  8980. // Check and evaluate the result as a constant expression.
  8981. LValue LV;
  8982. LV.set(VD);
  8983. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  8984. return false;
  8985. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  8986. };
  8987. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  8988. return ExprEvaluatorBaseTy::VisitBinCmp(E);
  8989. });
  8990. }
  8991. bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  8992. // We don't call noteFailure immediately because the assignment happens after
  8993. // we evaluate LHS and RHS.
  8994. if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
  8995. return Error(E);
  8996. DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
  8997. if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
  8998. return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
  8999. assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
  9000. !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
  9001. "DataRecursiveIntBinOpEvaluator should have handled integral types");
  9002. if (E->isComparisonOp()) {
  9003. // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
  9004. // comparisons and then translating the result.
  9005. auto OnSuccess = [&](ComparisonCategoryResult ResKind,
  9006. const BinaryOperator *E) {
  9007. using CCR = ComparisonCategoryResult;
  9008. bool IsEqual = ResKind == CCR::Equal,
  9009. IsLess = ResKind == CCR::Less,
  9010. IsGreater = ResKind == CCR::Greater;
  9011. auto Op = E->getOpcode();
  9012. switch (Op) {
  9013. default:
  9014. llvm_unreachable("unsupported binary operator");
  9015. case BO_EQ:
  9016. case BO_NE:
  9017. return Success(IsEqual == (Op == BO_EQ), E);
  9018. case BO_LT: return Success(IsLess, E);
  9019. case BO_GT: return Success(IsGreater, E);
  9020. case BO_LE: return Success(IsEqual || IsLess, E);
  9021. case BO_GE: return Success(IsEqual || IsGreater, E);
  9022. }
  9023. };
  9024. return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
  9025. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9026. });
  9027. }
  9028. QualType LHSTy = E->getLHS()->getType();
  9029. QualType RHSTy = E->getRHS()->getType();
  9030. if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
  9031. E->getOpcode() == BO_Sub) {
  9032. LValue LHSValue, RHSValue;
  9033. bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
  9034. if (!LHSOK && !Info.noteFailure())
  9035. return false;
  9036. if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
  9037. return false;
  9038. // Reject differing bases from the normal codepath; we special-case
  9039. // comparisons to null.
  9040. if (!HasSameBase(LHSValue, RHSValue)) {
  9041. // Handle &&A - &&B.
  9042. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
  9043. return Error(E);
  9044. const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
  9045. const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
  9046. if (!LHSExpr || !RHSExpr)
  9047. return Error(E);
  9048. const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
  9049. const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
  9050. if (!LHSAddrExpr || !RHSAddrExpr)
  9051. return Error(E);
  9052. // Make sure both labels come from the same function.
  9053. if (LHSAddrExpr->getLabel()->getDeclContext() !=
  9054. RHSAddrExpr->getLabel()->getDeclContext())
  9055. return Error(E);
  9056. return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
  9057. }
  9058. const CharUnits &LHSOffset = LHSValue.getLValueOffset();
  9059. const CharUnits &RHSOffset = RHSValue.getLValueOffset();
  9060. SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
  9061. SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
  9062. // C++11 [expr.add]p6:
  9063. // Unless both pointers point to elements of the same array object, or
  9064. // one past the last element of the array object, the behavior is
  9065. // undefined.
  9066. if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
  9067. !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
  9068. RHSDesignator))
  9069. Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
  9070. QualType Type = E->getLHS()->getType();
  9071. QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
  9072. CharUnits ElementSize;
  9073. if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
  9074. return false;
  9075. // As an extension, a type may have zero size (empty struct or union in
  9076. // C, array of zero length). Pointer subtraction in such cases has
  9077. // undefined behavior, so is not constant.
  9078. if (ElementSize.isZero()) {
  9079. Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
  9080. << ElementType;
  9081. return false;
  9082. }
  9083. // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
  9084. // and produce incorrect results when it overflows. Such behavior
  9085. // appears to be non-conforming, but is common, so perhaps we should
  9086. // assume the standard intended for such cases to be undefined behavior
  9087. // and check for them.
  9088. // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
  9089. // overflow in the final conversion to ptrdiff_t.
  9090. APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
  9091. APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
  9092. APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
  9093. false);
  9094. APSInt TrueResult = (LHS - RHS) / ElemSize;
  9095. APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
  9096. if (Result.extend(65) != TrueResult &&
  9097. !HandleOverflow(Info, E, TrueResult, E->getType()))
  9098. return false;
  9099. return Success(Result, E);
  9100. }
  9101. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9102. }
  9103. /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
  9104. /// a result as the expression's type.
  9105. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
  9106. const UnaryExprOrTypeTraitExpr *E) {
  9107. switch(E->getKind()) {
  9108. case UETT_PreferredAlignOf:
  9109. case UETT_AlignOf: {
  9110. if (E->isArgumentType())
  9111. return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
  9112. E);
  9113. else
  9114. return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
  9115. E);
  9116. }
  9117. case UETT_VecStep: {
  9118. QualType Ty = E->getTypeOfArgument();
  9119. if (Ty->isVectorType()) {
  9120. unsigned n = Ty->castAs<VectorType>()->getNumElements();
  9121. // The vec_step built-in functions that take a 3-component
  9122. // vector return 4. (OpenCL 1.1 spec 6.11.12)
  9123. if (n == 3)
  9124. n = 4;
  9125. return Success(n, E);
  9126. } else
  9127. return Success(1, E);
  9128. }
  9129. case UETT_SizeOf: {
  9130. QualType SrcTy = E->getTypeOfArgument();
  9131. // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
  9132. // the result is the size of the referenced type."
  9133. if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
  9134. SrcTy = Ref->getPointeeType();
  9135. CharUnits Sizeof;
  9136. if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
  9137. return false;
  9138. return Success(Sizeof, E);
  9139. }
  9140. case UETT_OpenMPRequiredSimdAlign:
  9141. assert(E->isArgumentType());
  9142. return Success(
  9143. Info.Ctx.toCharUnitsFromBits(
  9144. Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
  9145. .getQuantity(),
  9146. E);
  9147. }
  9148. llvm_unreachable("unknown expr/type trait");
  9149. }
  9150. bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
  9151. CharUnits Result;
  9152. unsigned n = OOE->getNumComponents();
  9153. if (n == 0)
  9154. return Error(OOE);
  9155. QualType CurrentType = OOE->getTypeSourceInfo()->getType();
  9156. for (unsigned i = 0; i != n; ++i) {
  9157. OffsetOfNode ON = OOE->getComponent(i);
  9158. switch (ON.getKind()) {
  9159. case OffsetOfNode::Array: {
  9160. const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
  9161. APSInt IdxResult;
  9162. if (!EvaluateInteger(Idx, IdxResult, Info))
  9163. return false;
  9164. const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
  9165. if (!AT)
  9166. return Error(OOE);
  9167. CurrentType = AT->getElementType();
  9168. CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
  9169. Result += IdxResult.getSExtValue() * ElementSize;
  9170. break;
  9171. }
  9172. case OffsetOfNode::Field: {
  9173. FieldDecl *MemberDecl = ON.getField();
  9174. const RecordType *RT = CurrentType->getAs<RecordType>();
  9175. if (!RT)
  9176. return Error(OOE);
  9177. RecordDecl *RD = RT->getDecl();
  9178. if (RD->isInvalidDecl()) return false;
  9179. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  9180. unsigned i = MemberDecl->getFieldIndex();
  9181. assert(i < RL.getFieldCount() && "offsetof field in wrong type");
  9182. Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
  9183. CurrentType = MemberDecl->getType().getNonReferenceType();
  9184. break;
  9185. }
  9186. case OffsetOfNode::Identifier:
  9187. llvm_unreachable("dependent __builtin_offsetof");
  9188. case OffsetOfNode::Base: {
  9189. CXXBaseSpecifier *BaseSpec = ON.getBase();
  9190. if (BaseSpec->isVirtual())
  9191. return Error(OOE);
  9192. // Find the layout of the class whose base we are looking into.
  9193. const RecordType *RT = CurrentType->getAs<RecordType>();
  9194. if (!RT)
  9195. return Error(OOE);
  9196. RecordDecl *RD = RT->getDecl();
  9197. if (RD->isInvalidDecl()) return false;
  9198. const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
  9199. // Find the base class itself.
  9200. CurrentType = BaseSpec->getType();
  9201. const RecordType *BaseRT = CurrentType->getAs<RecordType>();
  9202. if (!BaseRT)
  9203. return Error(OOE);
  9204. // Add the offset to the base.
  9205. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
  9206. break;
  9207. }
  9208. }
  9209. }
  9210. return Success(Result, OOE);
  9211. }
  9212. bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9213. switch (E->getOpcode()) {
  9214. default:
  9215. // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
  9216. // See C99 6.6p3.
  9217. return Error(E);
  9218. case UO_Extension:
  9219. // FIXME: Should extension allow i-c-e extension expressions in its scope?
  9220. // If so, we could clear the diagnostic ID.
  9221. return Visit(E->getSubExpr());
  9222. case UO_Plus:
  9223. // The result is just the value.
  9224. return Visit(E->getSubExpr());
  9225. case UO_Minus: {
  9226. if (!Visit(E->getSubExpr()))
  9227. return false;
  9228. if (!Result.isInt()) return Error(E);
  9229. const APSInt &Value = Result.getInt();
  9230. if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
  9231. !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
  9232. E->getType()))
  9233. return false;
  9234. return Success(-Value, E);
  9235. }
  9236. case UO_Not: {
  9237. if (!Visit(E->getSubExpr()))
  9238. return false;
  9239. if (!Result.isInt()) return Error(E);
  9240. return Success(~Result.getInt(), E);
  9241. }
  9242. case UO_LNot: {
  9243. bool bres;
  9244. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9245. return false;
  9246. return Success(!bres, E);
  9247. }
  9248. }
  9249. }
  9250. /// HandleCast - This is used to evaluate implicit or explicit casts where the
  9251. /// result type is integer.
  9252. bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9253. const Expr *SubExpr = E->getSubExpr();
  9254. QualType DestType = E->getType();
  9255. QualType SrcType = SubExpr->getType();
  9256. switch (E->getCastKind()) {
  9257. case CK_BaseToDerived:
  9258. case CK_DerivedToBase:
  9259. case CK_UncheckedDerivedToBase:
  9260. case CK_Dynamic:
  9261. case CK_ToUnion:
  9262. case CK_ArrayToPointerDecay:
  9263. case CK_FunctionToPointerDecay:
  9264. case CK_NullToPointer:
  9265. case CK_NullToMemberPointer:
  9266. case CK_BaseToDerivedMemberPointer:
  9267. case CK_DerivedToBaseMemberPointer:
  9268. case CK_ReinterpretMemberPointer:
  9269. case CK_ConstructorConversion:
  9270. case CK_IntegralToPointer:
  9271. case CK_ToVoid:
  9272. case CK_VectorSplat:
  9273. case CK_IntegralToFloating:
  9274. case CK_FloatingCast:
  9275. case CK_CPointerToObjCPointerCast:
  9276. case CK_BlockPointerToObjCPointerCast:
  9277. case CK_AnyPointerToBlockPointerCast:
  9278. case CK_ObjCObjectLValueCast:
  9279. case CK_FloatingRealToComplex:
  9280. case CK_FloatingComplexToReal:
  9281. case CK_FloatingComplexCast:
  9282. case CK_FloatingComplexToIntegralComplex:
  9283. case CK_IntegralRealToComplex:
  9284. case CK_IntegralComplexCast:
  9285. case CK_IntegralComplexToFloatingComplex:
  9286. case CK_BuiltinFnToFnPtr:
  9287. case CK_ZeroToOCLOpaqueType:
  9288. case CK_NonAtomicToAtomic:
  9289. case CK_AddressSpaceConversion:
  9290. case CK_IntToOCLSampler:
  9291. case CK_FixedPointCast:
  9292. case CK_IntegralToFixedPoint:
  9293. llvm_unreachable("invalid cast kind for integral value");
  9294. case CK_BitCast:
  9295. case CK_Dependent:
  9296. case CK_LValueBitCast:
  9297. case CK_ARCProduceObject:
  9298. case CK_ARCConsumeObject:
  9299. case CK_ARCReclaimReturnedObject:
  9300. case CK_ARCExtendBlockObject:
  9301. case CK_CopyAndAutoreleaseBlockObject:
  9302. return Error(E);
  9303. case CK_UserDefinedConversion:
  9304. case CK_LValueToRValue:
  9305. case CK_AtomicToNonAtomic:
  9306. case CK_NoOp:
  9307. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9308. case CK_MemberPointerToBoolean:
  9309. case CK_PointerToBoolean:
  9310. case CK_IntegralToBoolean:
  9311. case CK_FloatingToBoolean:
  9312. case CK_BooleanToSignedIntegral:
  9313. case CK_FloatingComplexToBoolean:
  9314. case CK_IntegralComplexToBoolean: {
  9315. bool BoolResult;
  9316. if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
  9317. return false;
  9318. uint64_t IntResult = BoolResult;
  9319. if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
  9320. IntResult = (uint64_t)-1;
  9321. return Success(IntResult, E);
  9322. }
  9323. case CK_FixedPointToIntegral: {
  9324. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
  9325. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9326. return false;
  9327. bool Overflowed;
  9328. llvm::APSInt Result = Src.convertToInt(
  9329. Info.Ctx.getIntWidth(DestType),
  9330. DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
  9331. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9332. return false;
  9333. return Success(Result, E);
  9334. }
  9335. case CK_FixedPointToBoolean: {
  9336. // Unsigned padding does not affect this.
  9337. APValue Val;
  9338. if (!Evaluate(Val, Info, SubExpr))
  9339. return false;
  9340. return Success(Val.getFixedPoint().getBoolValue(), E);
  9341. }
  9342. case CK_IntegralCast: {
  9343. if (!Visit(SubExpr))
  9344. return false;
  9345. if (!Result.isInt()) {
  9346. // Allow casts of address-of-label differences if they are no-ops
  9347. // or narrowing. (The narrowing case isn't actually guaranteed to
  9348. // be constant-evaluatable except in some narrow cases which are hard
  9349. // to detect here. We let it through on the assumption the user knows
  9350. // what they are doing.)
  9351. if (Result.isAddrLabelDiff())
  9352. return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
  9353. // Only allow casts of lvalues if they are lossless.
  9354. return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
  9355. }
  9356. return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
  9357. Result.getInt()), E);
  9358. }
  9359. case CK_PointerToIntegral: {
  9360. CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
  9361. LValue LV;
  9362. if (!EvaluatePointer(SubExpr, LV, Info))
  9363. return false;
  9364. if (LV.getLValueBase()) {
  9365. // Only allow based lvalue casts if they are lossless.
  9366. // FIXME: Allow a larger integer size than the pointer size, and allow
  9367. // narrowing back down to pointer width in subsequent integral casts.
  9368. // FIXME: Check integer type's active bits, not its type size.
  9369. if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
  9370. return Error(E);
  9371. LV.Designator.setInvalid();
  9372. LV.moveInto(Result);
  9373. return true;
  9374. }
  9375. APSInt AsInt;
  9376. APValue V;
  9377. LV.moveInto(V);
  9378. if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
  9379. llvm_unreachable("Can't cast this!");
  9380. return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
  9381. }
  9382. case CK_IntegralComplexToReal: {
  9383. ComplexValue C;
  9384. if (!EvaluateComplex(SubExpr, C, Info))
  9385. return false;
  9386. return Success(C.getComplexIntReal(), E);
  9387. }
  9388. case CK_FloatingToIntegral: {
  9389. APFloat F(0.0);
  9390. if (!EvaluateFloat(SubExpr, F, Info))
  9391. return false;
  9392. APSInt Value;
  9393. if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
  9394. return false;
  9395. return Success(Value, E);
  9396. }
  9397. }
  9398. llvm_unreachable("unknown cast resulting in integral value");
  9399. }
  9400. bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9401. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9402. ComplexValue LV;
  9403. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9404. return false;
  9405. if (!LV.isComplexInt())
  9406. return Error(E);
  9407. return Success(LV.getComplexIntReal(), E);
  9408. }
  9409. return Visit(E->getSubExpr());
  9410. }
  9411. bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9412. if (E->getSubExpr()->getType()->isComplexIntegerType()) {
  9413. ComplexValue LV;
  9414. if (!EvaluateComplex(E->getSubExpr(), LV, Info))
  9415. return false;
  9416. if (!LV.isComplexInt())
  9417. return Error(E);
  9418. return Success(LV.getComplexIntImag(), E);
  9419. }
  9420. VisitIgnoredValue(E->getSubExpr());
  9421. return Success(0, E);
  9422. }
  9423. bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  9424. return Success(E->getPackLength(), E);
  9425. }
  9426. bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
  9427. return Success(E->getValue(), E);
  9428. }
  9429. bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9430. switch (E->getOpcode()) {
  9431. default:
  9432. // Invalid unary operators
  9433. return Error(E);
  9434. case UO_Plus:
  9435. // The result is just the value.
  9436. return Visit(E->getSubExpr());
  9437. case UO_Minus: {
  9438. if (!Visit(E->getSubExpr())) return false;
  9439. if (!Result.isFixedPoint())
  9440. return Error(E);
  9441. bool Overflowed;
  9442. APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
  9443. if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
  9444. return false;
  9445. return Success(Negated, E);
  9446. }
  9447. case UO_LNot: {
  9448. bool bres;
  9449. if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
  9450. return false;
  9451. return Success(!bres, E);
  9452. }
  9453. }
  9454. }
  9455. bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9456. const Expr *SubExpr = E->getSubExpr();
  9457. QualType DestType = E->getType();
  9458. assert(DestType->isFixedPointType() &&
  9459. "Expected destination type to be a fixed point type");
  9460. auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
  9461. switch (E->getCastKind()) {
  9462. case CK_FixedPointCast: {
  9463. APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
  9464. if (!EvaluateFixedPoint(SubExpr, Src, Info))
  9465. return false;
  9466. bool Overflowed;
  9467. APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
  9468. if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
  9469. return false;
  9470. return Success(Result, E);
  9471. }
  9472. case CK_IntegralToFixedPoint: {
  9473. APSInt Src;
  9474. if (!EvaluateInteger(SubExpr, Src, Info))
  9475. return false;
  9476. bool Overflowed;
  9477. APFixedPoint IntResult = APFixedPoint::getFromIntValue(
  9478. Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
  9479. if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
  9480. return false;
  9481. return Success(IntResult, E);
  9482. }
  9483. case CK_NoOp:
  9484. case CK_LValueToRValue:
  9485. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9486. default:
  9487. return Error(E);
  9488. }
  9489. }
  9490. bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9491. const Expr *LHS = E->getLHS();
  9492. const Expr *RHS = E->getRHS();
  9493. FixedPointSemantics ResultFXSema =
  9494. Info.Ctx.getFixedPointSemantics(E->getType());
  9495. APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
  9496. if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
  9497. return false;
  9498. APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
  9499. if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
  9500. return false;
  9501. switch (E->getOpcode()) {
  9502. case BO_Add: {
  9503. bool AddOverflow, ConversionOverflow;
  9504. APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
  9505. .convert(ResultFXSema, &ConversionOverflow);
  9506. if ((AddOverflow || ConversionOverflow) &&
  9507. !HandleOverflow(Info, E, Result, E->getType()))
  9508. return false;
  9509. return Success(Result, E);
  9510. }
  9511. default:
  9512. return false;
  9513. }
  9514. llvm_unreachable("Should've exited before this");
  9515. }
  9516. //===----------------------------------------------------------------------===//
  9517. // Float Evaluation
  9518. //===----------------------------------------------------------------------===//
  9519. namespace {
  9520. class FloatExprEvaluator
  9521. : public ExprEvaluatorBase<FloatExprEvaluator> {
  9522. APFloat &Result;
  9523. public:
  9524. FloatExprEvaluator(EvalInfo &info, APFloat &result)
  9525. : ExprEvaluatorBaseTy(info), Result(result) {}
  9526. bool Success(const APValue &V, const Expr *e) {
  9527. Result = V.getFloat();
  9528. return true;
  9529. }
  9530. bool ZeroInitialization(const Expr *E) {
  9531. Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
  9532. return true;
  9533. }
  9534. bool VisitCallExpr(const CallExpr *E);
  9535. bool VisitUnaryOperator(const UnaryOperator *E);
  9536. bool VisitBinaryOperator(const BinaryOperator *E);
  9537. bool VisitFloatingLiteral(const FloatingLiteral *E);
  9538. bool VisitCastExpr(const CastExpr *E);
  9539. bool VisitUnaryReal(const UnaryOperator *E);
  9540. bool VisitUnaryImag(const UnaryOperator *E);
  9541. // FIXME: Missing: array subscript of vector, member of vector
  9542. };
  9543. } // end anonymous namespace
  9544. static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
  9545. assert(E->isRValue() && E->getType()->isRealFloatingType());
  9546. return FloatExprEvaluator(Info, Result).Visit(E);
  9547. }
  9548. static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
  9549. QualType ResultTy,
  9550. const Expr *Arg,
  9551. bool SNaN,
  9552. llvm::APFloat &Result) {
  9553. const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  9554. if (!S) return false;
  9555. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
  9556. llvm::APInt fill;
  9557. // Treat empty strings as if they were zero.
  9558. if (S->getString().empty())
  9559. fill = llvm::APInt(32, 0);
  9560. else if (S->getString().getAsInteger(0, fill))
  9561. return false;
  9562. if (Context.getTargetInfo().isNan2008()) {
  9563. if (SNaN)
  9564. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  9565. else
  9566. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  9567. } else {
  9568. // Prior to IEEE 754-2008, architectures were allowed to choose whether
  9569. // the first bit of their significand was set for qNaN or sNaN. MIPS chose
  9570. // a different encoding to what became a standard in 2008, and for pre-
  9571. // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
  9572. // sNaN. This is now known as "legacy NaN" encoding.
  9573. if (SNaN)
  9574. Result = llvm::APFloat::getQNaN(Sem, false, &fill);
  9575. else
  9576. Result = llvm::APFloat::getSNaN(Sem, false, &fill);
  9577. }
  9578. return true;
  9579. }
  9580. bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
  9581. switch (E->getBuiltinCallee()) {
  9582. default:
  9583. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  9584. case Builtin::BI__builtin_huge_val:
  9585. case Builtin::BI__builtin_huge_valf:
  9586. case Builtin::BI__builtin_huge_vall:
  9587. case Builtin::BI__builtin_huge_valf128:
  9588. case Builtin::BI__builtin_inf:
  9589. case Builtin::BI__builtin_inff:
  9590. case Builtin::BI__builtin_infl:
  9591. case Builtin::BI__builtin_inff128: {
  9592. const llvm::fltSemantics &Sem =
  9593. Info.Ctx.getFloatTypeSemantics(E->getType());
  9594. Result = llvm::APFloat::getInf(Sem);
  9595. return true;
  9596. }
  9597. case Builtin::BI__builtin_nans:
  9598. case Builtin::BI__builtin_nansf:
  9599. case Builtin::BI__builtin_nansl:
  9600. case Builtin::BI__builtin_nansf128:
  9601. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  9602. true, Result))
  9603. return Error(E);
  9604. return true;
  9605. case Builtin::BI__builtin_nan:
  9606. case Builtin::BI__builtin_nanf:
  9607. case Builtin::BI__builtin_nanl:
  9608. case Builtin::BI__builtin_nanf128:
  9609. // If this is __builtin_nan() turn this into a nan, otherwise we
  9610. // can't constant fold it.
  9611. if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
  9612. false, Result))
  9613. return Error(E);
  9614. return true;
  9615. case Builtin::BI__builtin_fabs:
  9616. case Builtin::BI__builtin_fabsf:
  9617. case Builtin::BI__builtin_fabsl:
  9618. case Builtin::BI__builtin_fabsf128:
  9619. if (!EvaluateFloat(E->getArg(0), Result, Info))
  9620. return false;
  9621. if (Result.isNegative())
  9622. Result.changeSign();
  9623. return true;
  9624. // FIXME: Builtin::BI__builtin_powi
  9625. // FIXME: Builtin::BI__builtin_powif
  9626. // FIXME: Builtin::BI__builtin_powil
  9627. case Builtin::BI__builtin_copysign:
  9628. case Builtin::BI__builtin_copysignf:
  9629. case Builtin::BI__builtin_copysignl:
  9630. case Builtin::BI__builtin_copysignf128: {
  9631. APFloat RHS(0.);
  9632. if (!EvaluateFloat(E->getArg(0), Result, Info) ||
  9633. !EvaluateFloat(E->getArg(1), RHS, Info))
  9634. return false;
  9635. Result.copySign(RHS);
  9636. return true;
  9637. }
  9638. }
  9639. }
  9640. bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
  9641. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9642. ComplexValue CV;
  9643. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  9644. return false;
  9645. Result = CV.FloatReal;
  9646. return true;
  9647. }
  9648. return Visit(E->getSubExpr());
  9649. }
  9650. bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
  9651. if (E->getSubExpr()->getType()->isAnyComplexType()) {
  9652. ComplexValue CV;
  9653. if (!EvaluateComplex(E->getSubExpr(), CV, Info))
  9654. return false;
  9655. Result = CV.FloatImag;
  9656. return true;
  9657. }
  9658. VisitIgnoredValue(E->getSubExpr());
  9659. const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
  9660. Result = llvm::APFloat::getZero(Sem);
  9661. return true;
  9662. }
  9663. bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  9664. switch (E->getOpcode()) {
  9665. default: return Error(E);
  9666. case UO_Plus:
  9667. return EvaluateFloat(E->getSubExpr(), Result, Info);
  9668. case UO_Minus:
  9669. if (!EvaluateFloat(E->getSubExpr(), Result, Info))
  9670. return false;
  9671. Result.changeSign();
  9672. return true;
  9673. }
  9674. }
  9675. bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9676. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  9677. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9678. APFloat RHS(0.0);
  9679. bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
  9680. if (!LHSOK && !Info.noteFailure())
  9681. return false;
  9682. return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
  9683. handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
  9684. }
  9685. bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
  9686. Result = E->getValue();
  9687. return true;
  9688. }
  9689. bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9690. const Expr* SubExpr = E->getSubExpr();
  9691. switch (E->getCastKind()) {
  9692. default:
  9693. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9694. case CK_IntegralToFloating: {
  9695. APSInt IntResult;
  9696. return EvaluateInteger(SubExpr, IntResult, Info) &&
  9697. HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
  9698. E->getType(), Result);
  9699. }
  9700. case CK_FloatingCast: {
  9701. if (!Visit(SubExpr))
  9702. return false;
  9703. return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
  9704. Result);
  9705. }
  9706. case CK_FloatingComplexToReal: {
  9707. ComplexValue V;
  9708. if (!EvaluateComplex(SubExpr, V, Info))
  9709. return false;
  9710. Result = V.getComplexFloatReal();
  9711. return true;
  9712. }
  9713. }
  9714. }
  9715. //===----------------------------------------------------------------------===//
  9716. // Complex Evaluation (for float and integer)
  9717. //===----------------------------------------------------------------------===//
  9718. namespace {
  9719. class ComplexExprEvaluator
  9720. : public ExprEvaluatorBase<ComplexExprEvaluator> {
  9721. ComplexValue &Result;
  9722. public:
  9723. ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
  9724. : ExprEvaluatorBaseTy(info), Result(Result) {}
  9725. bool Success(const APValue &V, const Expr *e) {
  9726. Result.setFrom(V);
  9727. return true;
  9728. }
  9729. bool ZeroInitialization(const Expr *E);
  9730. //===--------------------------------------------------------------------===//
  9731. // Visitor Methods
  9732. //===--------------------------------------------------------------------===//
  9733. bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
  9734. bool VisitCastExpr(const CastExpr *E);
  9735. bool VisitBinaryOperator(const BinaryOperator *E);
  9736. bool VisitUnaryOperator(const UnaryOperator *E);
  9737. bool VisitInitListExpr(const InitListExpr *E);
  9738. };
  9739. } // end anonymous namespace
  9740. static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
  9741. EvalInfo &Info) {
  9742. assert(E->isRValue() && E->getType()->isAnyComplexType());
  9743. return ComplexExprEvaluator(Info, Result).Visit(E);
  9744. }
  9745. bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
  9746. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  9747. if (ElemTy->isRealFloatingType()) {
  9748. Result.makeComplexFloat();
  9749. APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
  9750. Result.FloatReal = Zero;
  9751. Result.FloatImag = Zero;
  9752. } else {
  9753. Result.makeComplexInt();
  9754. APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
  9755. Result.IntReal = Zero;
  9756. Result.IntImag = Zero;
  9757. }
  9758. return true;
  9759. }
  9760. bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
  9761. const Expr* SubExpr = E->getSubExpr();
  9762. if (SubExpr->getType()->isRealFloatingType()) {
  9763. Result.makeComplexFloat();
  9764. APFloat &Imag = Result.FloatImag;
  9765. if (!EvaluateFloat(SubExpr, Imag, Info))
  9766. return false;
  9767. Result.FloatReal = APFloat(Imag.getSemantics());
  9768. return true;
  9769. } else {
  9770. assert(SubExpr->getType()->isIntegerType() &&
  9771. "Unexpected imaginary literal.");
  9772. Result.makeComplexInt();
  9773. APSInt &Imag = Result.IntImag;
  9774. if (!EvaluateInteger(SubExpr, Imag, Info))
  9775. return false;
  9776. Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
  9777. return true;
  9778. }
  9779. }
  9780. bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
  9781. switch (E->getCastKind()) {
  9782. case CK_BitCast:
  9783. case CK_BaseToDerived:
  9784. case CK_DerivedToBase:
  9785. case CK_UncheckedDerivedToBase:
  9786. case CK_Dynamic:
  9787. case CK_ToUnion:
  9788. case CK_ArrayToPointerDecay:
  9789. case CK_FunctionToPointerDecay:
  9790. case CK_NullToPointer:
  9791. case CK_NullToMemberPointer:
  9792. case CK_BaseToDerivedMemberPointer:
  9793. case CK_DerivedToBaseMemberPointer:
  9794. case CK_MemberPointerToBoolean:
  9795. case CK_ReinterpretMemberPointer:
  9796. case CK_ConstructorConversion:
  9797. case CK_IntegralToPointer:
  9798. case CK_PointerToIntegral:
  9799. case CK_PointerToBoolean:
  9800. case CK_ToVoid:
  9801. case CK_VectorSplat:
  9802. case CK_IntegralCast:
  9803. case CK_BooleanToSignedIntegral:
  9804. case CK_IntegralToBoolean:
  9805. case CK_IntegralToFloating:
  9806. case CK_FloatingToIntegral:
  9807. case CK_FloatingToBoolean:
  9808. case CK_FloatingCast:
  9809. case CK_CPointerToObjCPointerCast:
  9810. case CK_BlockPointerToObjCPointerCast:
  9811. case CK_AnyPointerToBlockPointerCast:
  9812. case CK_ObjCObjectLValueCast:
  9813. case CK_FloatingComplexToReal:
  9814. case CK_FloatingComplexToBoolean:
  9815. case CK_IntegralComplexToReal:
  9816. case CK_IntegralComplexToBoolean:
  9817. case CK_ARCProduceObject:
  9818. case CK_ARCConsumeObject:
  9819. case CK_ARCReclaimReturnedObject:
  9820. case CK_ARCExtendBlockObject:
  9821. case CK_CopyAndAutoreleaseBlockObject:
  9822. case CK_BuiltinFnToFnPtr:
  9823. case CK_ZeroToOCLOpaqueType:
  9824. case CK_NonAtomicToAtomic:
  9825. case CK_AddressSpaceConversion:
  9826. case CK_IntToOCLSampler:
  9827. case CK_FixedPointCast:
  9828. case CK_FixedPointToBoolean:
  9829. case CK_FixedPointToIntegral:
  9830. case CK_IntegralToFixedPoint:
  9831. llvm_unreachable("invalid cast kind for complex value");
  9832. case CK_LValueToRValue:
  9833. case CK_AtomicToNonAtomic:
  9834. case CK_NoOp:
  9835. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  9836. case CK_Dependent:
  9837. case CK_LValueBitCast:
  9838. case CK_UserDefinedConversion:
  9839. return Error(E);
  9840. case CK_FloatingRealToComplex: {
  9841. APFloat &Real = Result.FloatReal;
  9842. if (!EvaluateFloat(E->getSubExpr(), Real, Info))
  9843. return false;
  9844. Result.makeComplexFloat();
  9845. Result.FloatImag = APFloat(Real.getSemantics());
  9846. return true;
  9847. }
  9848. case CK_FloatingComplexCast: {
  9849. if (!Visit(E->getSubExpr()))
  9850. return false;
  9851. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  9852. QualType From
  9853. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  9854. return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
  9855. HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
  9856. }
  9857. case CK_FloatingComplexToIntegralComplex: {
  9858. if (!Visit(E->getSubExpr()))
  9859. return false;
  9860. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  9861. QualType From
  9862. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  9863. Result.makeComplexInt();
  9864. return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
  9865. To, Result.IntReal) &&
  9866. HandleFloatToIntCast(Info, E, From, Result.FloatImag,
  9867. To, Result.IntImag);
  9868. }
  9869. case CK_IntegralRealToComplex: {
  9870. APSInt &Real = Result.IntReal;
  9871. if (!EvaluateInteger(E->getSubExpr(), Real, Info))
  9872. return false;
  9873. Result.makeComplexInt();
  9874. Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
  9875. return true;
  9876. }
  9877. case CK_IntegralComplexCast: {
  9878. if (!Visit(E->getSubExpr()))
  9879. return false;
  9880. QualType To = E->getType()->getAs<ComplexType>()->getElementType();
  9881. QualType From
  9882. = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
  9883. Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
  9884. Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
  9885. return true;
  9886. }
  9887. case CK_IntegralComplexToFloatingComplex: {
  9888. if (!Visit(E->getSubExpr()))
  9889. return false;
  9890. QualType To = E->getType()->castAs<ComplexType>()->getElementType();
  9891. QualType From
  9892. = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
  9893. Result.makeComplexFloat();
  9894. return HandleIntToFloatCast(Info, E, From, Result.IntReal,
  9895. To, Result.FloatReal) &&
  9896. HandleIntToFloatCast(Info, E, From, Result.IntImag,
  9897. To, Result.FloatImag);
  9898. }
  9899. }
  9900. llvm_unreachable("unknown cast resulting in complex value");
  9901. }
  9902. bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  9903. if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
  9904. return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
  9905. // Track whether the LHS or RHS is real at the type system level. When this is
  9906. // the case we can simplify our evaluation strategy.
  9907. bool LHSReal = false, RHSReal = false;
  9908. bool LHSOK;
  9909. if (E->getLHS()->getType()->isRealFloatingType()) {
  9910. LHSReal = true;
  9911. APFloat &Real = Result.FloatReal;
  9912. LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
  9913. if (LHSOK) {
  9914. Result.makeComplexFloat();
  9915. Result.FloatImag = APFloat(Real.getSemantics());
  9916. }
  9917. } else {
  9918. LHSOK = Visit(E->getLHS());
  9919. }
  9920. if (!LHSOK && !Info.noteFailure())
  9921. return false;
  9922. ComplexValue RHS;
  9923. if (E->getRHS()->getType()->isRealFloatingType()) {
  9924. RHSReal = true;
  9925. APFloat &Real = RHS.FloatReal;
  9926. if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
  9927. return false;
  9928. RHS.makeComplexFloat();
  9929. RHS.FloatImag = APFloat(Real.getSemantics());
  9930. } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
  9931. return false;
  9932. assert(!(LHSReal && RHSReal) &&
  9933. "Cannot have both operands of a complex operation be real.");
  9934. switch (E->getOpcode()) {
  9935. default: return Error(E);
  9936. case BO_Add:
  9937. if (Result.isComplexFloat()) {
  9938. Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
  9939. APFloat::rmNearestTiesToEven);
  9940. if (LHSReal)
  9941. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9942. else if (!RHSReal)
  9943. Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
  9944. APFloat::rmNearestTiesToEven);
  9945. } else {
  9946. Result.getComplexIntReal() += RHS.getComplexIntReal();
  9947. Result.getComplexIntImag() += RHS.getComplexIntImag();
  9948. }
  9949. break;
  9950. case BO_Sub:
  9951. if (Result.isComplexFloat()) {
  9952. Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
  9953. APFloat::rmNearestTiesToEven);
  9954. if (LHSReal) {
  9955. Result.getComplexFloatImag() = RHS.getComplexFloatImag();
  9956. Result.getComplexFloatImag().changeSign();
  9957. } else if (!RHSReal) {
  9958. Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
  9959. APFloat::rmNearestTiesToEven);
  9960. }
  9961. } else {
  9962. Result.getComplexIntReal() -= RHS.getComplexIntReal();
  9963. Result.getComplexIntImag() -= RHS.getComplexIntImag();
  9964. }
  9965. break;
  9966. case BO_Mul:
  9967. if (Result.isComplexFloat()) {
  9968. // This is an implementation of complex multiplication according to the
  9969. // constraints laid out in C11 Annex G. The implementation uses the
  9970. // following naming scheme:
  9971. // (a + ib) * (c + id)
  9972. ComplexValue LHS = Result;
  9973. APFloat &A = LHS.getComplexFloatReal();
  9974. APFloat &B = LHS.getComplexFloatImag();
  9975. APFloat &C = RHS.getComplexFloatReal();
  9976. APFloat &D = RHS.getComplexFloatImag();
  9977. APFloat &ResR = Result.getComplexFloatReal();
  9978. APFloat &ResI = Result.getComplexFloatImag();
  9979. if (LHSReal) {
  9980. assert(!RHSReal && "Cannot have two real operands for a complex op!");
  9981. ResR = A * C;
  9982. ResI = A * D;
  9983. } else if (RHSReal) {
  9984. ResR = C * A;
  9985. ResI = C * B;
  9986. } else {
  9987. // In the fully general case, we need to handle NaNs and infinities
  9988. // robustly.
  9989. APFloat AC = A * C;
  9990. APFloat BD = B * D;
  9991. APFloat AD = A * D;
  9992. APFloat BC = B * C;
  9993. ResR = AC - BD;
  9994. ResI = AD + BC;
  9995. if (ResR.isNaN() && ResI.isNaN()) {
  9996. bool Recalc = false;
  9997. if (A.isInfinity() || B.isInfinity()) {
  9998. A = APFloat::copySign(
  9999. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10000. B = APFloat::copySign(
  10001. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10002. if (C.isNaN())
  10003. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10004. if (D.isNaN())
  10005. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10006. Recalc = true;
  10007. }
  10008. if (C.isInfinity() || D.isInfinity()) {
  10009. C = APFloat::copySign(
  10010. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10011. D = APFloat::copySign(
  10012. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10013. if (A.isNaN())
  10014. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10015. if (B.isNaN())
  10016. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10017. Recalc = true;
  10018. }
  10019. if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
  10020. AD.isInfinity() || BC.isInfinity())) {
  10021. if (A.isNaN())
  10022. A = APFloat::copySign(APFloat(A.getSemantics()), A);
  10023. if (B.isNaN())
  10024. B = APFloat::copySign(APFloat(B.getSemantics()), B);
  10025. if (C.isNaN())
  10026. C = APFloat::copySign(APFloat(C.getSemantics()), C);
  10027. if (D.isNaN())
  10028. D = APFloat::copySign(APFloat(D.getSemantics()), D);
  10029. Recalc = true;
  10030. }
  10031. if (Recalc) {
  10032. ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
  10033. ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
  10034. }
  10035. }
  10036. }
  10037. } else {
  10038. ComplexValue LHS = Result;
  10039. Result.getComplexIntReal() =
  10040. (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
  10041. LHS.getComplexIntImag() * RHS.getComplexIntImag());
  10042. Result.getComplexIntImag() =
  10043. (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
  10044. LHS.getComplexIntImag() * RHS.getComplexIntReal());
  10045. }
  10046. break;
  10047. case BO_Div:
  10048. if (Result.isComplexFloat()) {
  10049. // This is an implementation of complex division according to the
  10050. // constraints laid out in C11 Annex G. The implementation uses the
  10051. // following naming scheme:
  10052. // (a + ib) / (c + id)
  10053. ComplexValue LHS = Result;
  10054. APFloat &A = LHS.getComplexFloatReal();
  10055. APFloat &B = LHS.getComplexFloatImag();
  10056. APFloat &C = RHS.getComplexFloatReal();
  10057. APFloat &D = RHS.getComplexFloatImag();
  10058. APFloat &ResR = Result.getComplexFloatReal();
  10059. APFloat &ResI = Result.getComplexFloatImag();
  10060. if (RHSReal) {
  10061. ResR = A / C;
  10062. ResI = B / C;
  10063. } else {
  10064. if (LHSReal) {
  10065. // No real optimizations we can do here, stub out with zero.
  10066. B = APFloat::getZero(A.getSemantics());
  10067. }
  10068. int DenomLogB = 0;
  10069. APFloat MaxCD = maxnum(abs(C), abs(D));
  10070. if (MaxCD.isFinite()) {
  10071. DenomLogB = ilogb(MaxCD);
  10072. C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
  10073. D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
  10074. }
  10075. APFloat Denom = C * C + D * D;
  10076. ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
  10077. APFloat::rmNearestTiesToEven);
  10078. ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
  10079. APFloat::rmNearestTiesToEven);
  10080. if (ResR.isNaN() && ResI.isNaN()) {
  10081. if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
  10082. ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
  10083. ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
  10084. } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
  10085. D.isFinite()) {
  10086. A = APFloat::copySign(
  10087. APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
  10088. B = APFloat::copySign(
  10089. APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
  10090. ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
  10091. ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
  10092. } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
  10093. C = APFloat::copySign(
  10094. APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
  10095. D = APFloat::copySign(
  10096. APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
  10097. ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
  10098. ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
  10099. }
  10100. }
  10101. }
  10102. } else {
  10103. if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
  10104. return Error(E, diag::note_expr_divide_by_zero);
  10105. ComplexValue LHS = Result;
  10106. APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
  10107. RHS.getComplexIntImag() * RHS.getComplexIntImag();
  10108. Result.getComplexIntReal() =
  10109. (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
  10110. LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
  10111. Result.getComplexIntImag() =
  10112. (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
  10113. LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
  10114. }
  10115. break;
  10116. }
  10117. return true;
  10118. }
  10119. bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  10120. // Get the operand value into 'Result'.
  10121. if (!Visit(E->getSubExpr()))
  10122. return false;
  10123. switch (E->getOpcode()) {
  10124. default:
  10125. return Error(E);
  10126. case UO_Extension:
  10127. return true;
  10128. case UO_Plus:
  10129. // The result is always just the subexpr.
  10130. return true;
  10131. case UO_Minus:
  10132. if (Result.isComplexFloat()) {
  10133. Result.getComplexFloatReal().changeSign();
  10134. Result.getComplexFloatImag().changeSign();
  10135. }
  10136. else {
  10137. Result.getComplexIntReal() = -Result.getComplexIntReal();
  10138. Result.getComplexIntImag() = -Result.getComplexIntImag();
  10139. }
  10140. return true;
  10141. case UO_Not:
  10142. if (Result.isComplexFloat())
  10143. Result.getComplexFloatImag().changeSign();
  10144. else
  10145. Result.getComplexIntImag() = -Result.getComplexIntImag();
  10146. return true;
  10147. }
  10148. }
  10149. bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
  10150. if (E->getNumInits() == 2) {
  10151. if (E->getType()->isComplexType()) {
  10152. Result.makeComplexFloat();
  10153. if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
  10154. return false;
  10155. if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
  10156. return false;
  10157. } else {
  10158. Result.makeComplexInt();
  10159. if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
  10160. return false;
  10161. if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
  10162. return false;
  10163. }
  10164. return true;
  10165. }
  10166. return ExprEvaluatorBaseTy::VisitInitListExpr(E);
  10167. }
  10168. //===----------------------------------------------------------------------===//
  10169. // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
  10170. // implicit conversion.
  10171. //===----------------------------------------------------------------------===//
  10172. namespace {
  10173. class AtomicExprEvaluator :
  10174. public ExprEvaluatorBase<AtomicExprEvaluator> {
  10175. const LValue *This;
  10176. APValue &Result;
  10177. public:
  10178. AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
  10179. : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
  10180. bool Success(const APValue &V, const Expr *E) {
  10181. Result = V;
  10182. return true;
  10183. }
  10184. bool ZeroInitialization(const Expr *E) {
  10185. ImplicitValueInitExpr VIE(
  10186. E->getType()->castAs<AtomicType>()->getValueType());
  10187. // For atomic-qualified class (and array) types in C++, initialize the
  10188. // _Atomic-wrapped subobject directly, in-place.
  10189. return This ? EvaluateInPlace(Result, Info, *This, &VIE)
  10190. : Evaluate(Result, Info, &VIE);
  10191. }
  10192. bool VisitCastExpr(const CastExpr *E) {
  10193. switch (E->getCastKind()) {
  10194. default:
  10195. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10196. case CK_NonAtomicToAtomic:
  10197. return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
  10198. : Evaluate(Result, Info, E->getSubExpr());
  10199. }
  10200. }
  10201. };
  10202. } // end anonymous namespace
  10203. static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
  10204. EvalInfo &Info) {
  10205. assert(E->isRValue() && E->getType()->isAtomicType());
  10206. return AtomicExprEvaluator(Info, This, Result).Visit(E);
  10207. }
  10208. //===----------------------------------------------------------------------===//
  10209. // Void expression evaluation, primarily for a cast to void on the LHS of a
  10210. // comma operator
  10211. //===----------------------------------------------------------------------===//
  10212. namespace {
  10213. class VoidExprEvaluator
  10214. : public ExprEvaluatorBase<VoidExprEvaluator> {
  10215. public:
  10216. VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
  10217. bool Success(const APValue &V, const Expr *e) { return true; }
  10218. bool ZeroInitialization(const Expr *E) { return true; }
  10219. bool VisitCastExpr(const CastExpr *E) {
  10220. switch (E->getCastKind()) {
  10221. default:
  10222. return ExprEvaluatorBaseTy::VisitCastExpr(E);
  10223. case CK_ToVoid:
  10224. VisitIgnoredValue(E->getSubExpr());
  10225. return true;
  10226. }
  10227. }
  10228. bool VisitCallExpr(const CallExpr *E) {
  10229. switch (E->getBuiltinCallee()) {
  10230. default:
  10231. return ExprEvaluatorBaseTy::VisitCallExpr(E);
  10232. case Builtin::BI__assume:
  10233. case Builtin::BI__builtin_assume:
  10234. // The argument is not evaluated!
  10235. return true;
  10236. }
  10237. }
  10238. };
  10239. } // end anonymous namespace
  10240. static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
  10241. assert(E->isRValue() && E->getType()->isVoidType());
  10242. return VoidExprEvaluator(Info).Visit(E);
  10243. }
  10244. //===----------------------------------------------------------------------===//
  10245. // Top level Expr::EvaluateAsRValue method.
  10246. //===----------------------------------------------------------------------===//
  10247. static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
  10248. // In C, function designators are not lvalues, but we evaluate them as if they
  10249. // are.
  10250. QualType T = E->getType();
  10251. if (E->isGLValue() || T->isFunctionType()) {
  10252. LValue LV;
  10253. if (!EvaluateLValue(E, LV, Info))
  10254. return false;
  10255. LV.moveInto(Result);
  10256. } else if (T->isVectorType()) {
  10257. if (!EvaluateVector(E, Result, Info))
  10258. return false;
  10259. } else if (T->isIntegralOrEnumerationType()) {
  10260. if (!IntExprEvaluator(Info, Result).Visit(E))
  10261. return false;
  10262. } else if (T->hasPointerRepresentation()) {
  10263. LValue LV;
  10264. if (!EvaluatePointer(E, LV, Info))
  10265. return false;
  10266. LV.moveInto(Result);
  10267. } else if (T->isRealFloatingType()) {
  10268. llvm::APFloat F(0.0);
  10269. if (!EvaluateFloat(E, F, Info))
  10270. return false;
  10271. Result = APValue(F);
  10272. } else if (T->isAnyComplexType()) {
  10273. ComplexValue C;
  10274. if (!EvaluateComplex(E, C, Info))
  10275. return false;
  10276. C.moveInto(Result);
  10277. } else if (T->isFixedPointType()) {
  10278. if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
  10279. } else if (T->isMemberPointerType()) {
  10280. MemberPtr P;
  10281. if (!EvaluateMemberPointer(E, P, Info))
  10282. return false;
  10283. P.moveInto(Result);
  10284. return true;
  10285. } else if (T->isArrayType()) {
  10286. LValue LV;
  10287. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10288. if (!EvaluateArray(E, LV, Value, Info))
  10289. return false;
  10290. Result = Value;
  10291. } else if (T->isRecordType()) {
  10292. LValue LV;
  10293. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10294. if (!EvaluateRecord(E, LV, Value, Info))
  10295. return false;
  10296. Result = Value;
  10297. } else if (T->isVoidType()) {
  10298. if (!Info.getLangOpts().CPlusPlus11)
  10299. Info.CCEDiag(E, diag::note_constexpr_nonliteral)
  10300. << E->getType();
  10301. if (!EvaluateVoid(E, Info))
  10302. return false;
  10303. } else if (T->isAtomicType()) {
  10304. QualType Unqual = T.getAtomicUnqualifiedType();
  10305. if (Unqual->isArrayType() || Unqual->isRecordType()) {
  10306. LValue LV;
  10307. APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
  10308. if (!EvaluateAtomic(E, &LV, Value, Info))
  10309. return false;
  10310. } else {
  10311. if (!EvaluateAtomic(E, nullptr, Result, Info))
  10312. return false;
  10313. }
  10314. } else if (Info.getLangOpts().CPlusPlus11) {
  10315. Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
  10316. return false;
  10317. } else {
  10318. Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
  10319. return false;
  10320. }
  10321. return true;
  10322. }
  10323. /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
  10324. /// cases, the in-place evaluation is essential, since later initializers for
  10325. /// an object can indirectly refer to subobjects which were initialized earlier.
  10326. static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
  10327. const Expr *E, bool AllowNonLiteralTypes) {
  10328. assert(!E->isValueDependent());
  10329. if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
  10330. return false;
  10331. if (E->isRValue()) {
  10332. // Evaluate arrays and record types in-place, so that later initializers can
  10333. // refer to earlier-initialized members of the object.
  10334. QualType T = E->getType();
  10335. if (T->isArrayType())
  10336. return EvaluateArray(E, This, Result, Info);
  10337. else if (T->isRecordType())
  10338. return EvaluateRecord(E, This, Result, Info);
  10339. else if (T->isAtomicType()) {
  10340. QualType Unqual = T.getAtomicUnqualifiedType();
  10341. if (Unqual->isArrayType() || Unqual->isRecordType())
  10342. return EvaluateAtomic(E, &This, Result, Info);
  10343. }
  10344. }
  10345. // For any other type, in-place evaluation is unimportant.
  10346. return Evaluate(Result, Info, E);
  10347. }
  10348. /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
  10349. /// lvalue-to-rvalue cast if it is an lvalue.
  10350. static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
  10351. if (E->getType().isNull())
  10352. return false;
  10353. if (!CheckLiteralType(Info, E))
  10354. return false;
  10355. if (!::Evaluate(Result, Info, E))
  10356. return false;
  10357. if (E->isGLValue()) {
  10358. LValue LV;
  10359. LV.setFrom(Info.Ctx, Result);
  10360. if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
  10361. return false;
  10362. }
  10363. // Check this core constant expression is a constant expression.
  10364. return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
  10365. }
  10366. static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
  10367. const ASTContext &Ctx, bool &IsConst) {
  10368. // Fast-path evaluations of integer literals, since we sometimes see files
  10369. // containing vast quantities of these.
  10370. if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
  10371. Result.Val = APValue(APSInt(L->getValue(),
  10372. L->getType()->isUnsignedIntegerType()));
  10373. IsConst = true;
  10374. return true;
  10375. }
  10376. // This case should be rare, but we need to check it before we check on
  10377. // the type below.
  10378. if (Exp->getType().isNull()) {
  10379. IsConst = false;
  10380. return true;
  10381. }
  10382. // FIXME: Evaluating values of large array and record types can cause
  10383. // performance problems. Only do so in C++11 for now.
  10384. if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
  10385. Exp->getType()->isRecordType()) &&
  10386. !Ctx.getLangOpts().CPlusPlus11) {
  10387. IsConst = false;
  10388. return true;
  10389. }
  10390. return false;
  10391. }
  10392. static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
  10393. Expr::SideEffectsKind SEK) {
  10394. return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
  10395. (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
  10396. }
  10397. static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
  10398. const ASTContext &Ctx, EvalInfo &Info) {
  10399. bool IsConst;
  10400. if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
  10401. return IsConst;
  10402. return EvaluateAsRValue(Info, E, Result.Val);
  10403. }
  10404. static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
  10405. const ASTContext &Ctx,
  10406. Expr::SideEffectsKind AllowSideEffects,
  10407. EvalInfo &Info) {
  10408. if (!E->getType()->isIntegralOrEnumerationType())
  10409. return false;
  10410. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
  10411. !ExprResult.Val.isInt() ||
  10412. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10413. return false;
  10414. return true;
  10415. }
  10416. static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
  10417. const ASTContext &Ctx,
  10418. Expr::SideEffectsKind AllowSideEffects,
  10419. EvalInfo &Info) {
  10420. if (!E->getType()->isFixedPointType())
  10421. return false;
  10422. if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
  10423. return false;
  10424. if (!ExprResult.Val.isFixedPoint() ||
  10425. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10426. return false;
  10427. return true;
  10428. }
  10429. /// EvaluateAsRValue - Return true if this is a constant which we can fold using
  10430. /// any crazy technique (that has nothing to do with language standards) that
  10431. /// we want to. If this function returns true, it returns the folded constant
  10432. /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
  10433. /// will be applied to the result.
  10434. bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
  10435. bool InConstantContext) const {
  10436. assert(!isValueDependent() &&
  10437. "Expression evaluator can't be called on a dependent expression.");
  10438. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10439. Info.InConstantContext = InConstantContext;
  10440. return ::EvaluateAsRValue(this, Result, Ctx, Info);
  10441. }
  10442. bool Expr::EvaluateAsBooleanCondition(bool &Result,
  10443. const ASTContext &Ctx) const {
  10444. assert(!isValueDependent() &&
  10445. "Expression evaluator can't be called on a dependent expression.");
  10446. EvalResult Scratch;
  10447. return EvaluateAsRValue(Scratch, Ctx) &&
  10448. HandleConversionToBool(Scratch.Val, Result);
  10449. }
  10450. bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
  10451. SideEffectsKind AllowSideEffects) const {
  10452. assert(!isValueDependent() &&
  10453. "Expression evaluator can't be called on a dependent expression.");
  10454. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10455. return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
  10456. }
  10457. bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
  10458. SideEffectsKind AllowSideEffects) const {
  10459. assert(!isValueDependent() &&
  10460. "Expression evaluator can't be called on a dependent expression.");
  10461. EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
  10462. return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
  10463. }
  10464. bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
  10465. SideEffectsKind AllowSideEffects) const {
  10466. assert(!isValueDependent() &&
  10467. "Expression evaluator can't be called on a dependent expression.");
  10468. if (!getType()->isRealFloatingType())
  10469. return false;
  10470. EvalResult ExprResult;
  10471. if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
  10472. hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
  10473. return false;
  10474. Result = ExprResult.Val.getFloat();
  10475. return true;
  10476. }
  10477. bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
  10478. assert(!isValueDependent() &&
  10479. "Expression evaluator can't be called on a dependent expression.");
  10480. EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
  10481. LValue LV;
  10482. if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
  10483. !CheckLValueConstantExpression(Info, getExprLoc(),
  10484. Ctx.getLValueReferenceType(getType()), LV,
  10485. Expr::EvaluateForCodeGen))
  10486. return false;
  10487. LV.moveInto(Result.Val);
  10488. return true;
  10489. }
  10490. bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
  10491. const ASTContext &Ctx) const {
  10492. assert(!isValueDependent() &&
  10493. "Expression evaluator can't be called on a dependent expression.");
  10494. EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
  10495. EvalInfo Info(Ctx, Result, EM);
  10496. Info.InConstantContext = true;
  10497. if (!::Evaluate(Result.Val, Info, this))
  10498. return false;
  10499. return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
  10500. Usage);
  10501. }
  10502. bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
  10503. const VarDecl *VD,
  10504. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  10505. assert(!isValueDependent() &&
  10506. "Expression evaluator can't be called on a dependent expression.");
  10507. // FIXME: Evaluating initializers for large array and record types can cause
  10508. // performance problems. Only do so in C++11 for now.
  10509. if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
  10510. !Ctx.getLangOpts().CPlusPlus11)
  10511. return false;
  10512. Expr::EvalStatus EStatus;
  10513. EStatus.Diag = &Notes;
  10514. EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
  10515. ? EvalInfo::EM_ConstantExpression
  10516. : EvalInfo::EM_ConstantFold);
  10517. InitInfo.setEvaluatingDecl(VD, Value);
  10518. InitInfo.InConstantContext = true;
  10519. LValue LVal;
  10520. LVal.set(VD);
  10521. // C++11 [basic.start.init]p2:
  10522. // Variables with static storage duration or thread storage duration shall be
  10523. // zero-initialized before any other initialization takes place.
  10524. // This behavior is not present in C.
  10525. if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
  10526. !VD->getType()->isReferenceType()) {
  10527. ImplicitValueInitExpr VIE(VD->getType());
  10528. if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
  10529. /*AllowNonLiteralTypes=*/true))
  10530. return false;
  10531. }
  10532. if (!EvaluateInPlace(Value, InitInfo, LVal, this,
  10533. /*AllowNonLiteralTypes=*/true) ||
  10534. EStatus.HasSideEffects)
  10535. return false;
  10536. return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
  10537. Value);
  10538. }
  10539. /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
  10540. /// constant folded, but discard the result.
  10541. bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
  10542. assert(!isValueDependent() &&
  10543. "Expression evaluator can't be called on a dependent expression.");
  10544. EvalResult Result;
  10545. return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
  10546. !hasUnacceptableSideEffect(Result, SEK);
  10547. }
  10548. APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
  10549. SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  10550. assert(!isValueDependent() &&
  10551. "Expression evaluator can't be called on a dependent expression.");
  10552. EvalResult EVResult;
  10553. EVResult.Diag = Diag;
  10554. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
  10555. Info.InConstantContext = true;
  10556. bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
  10557. (void)Result;
  10558. assert(Result && "Could not evaluate expression");
  10559. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  10560. return EVResult.Val.getInt();
  10561. }
  10562. APSInt Expr::EvaluateKnownConstIntCheckOverflow(
  10563. const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
  10564. assert(!isValueDependent() &&
  10565. "Expression evaluator can't be called on a dependent expression.");
  10566. EvalResult EVResult;
  10567. EVResult.Diag = Diag;
  10568. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  10569. Info.InConstantContext = true;
  10570. bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
  10571. (void)Result;
  10572. assert(Result && "Could not evaluate expression");
  10573. assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
  10574. return EVResult.Val.getInt();
  10575. }
  10576. void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
  10577. assert(!isValueDependent() &&
  10578. "Expression evaluator can't be called on a dependent expression.");
  10579. bool IsConst;
  10580. EvalResult EVResult;
  10581. if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
  10582. EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
  10583. (void)::EvaluateAsRValue(Info, this, EVResult.Val);
  10584. }
  10585. }
  10586. bool Expr::EvalResult::isGlobalLValue() const {
  10587. assert(Val.isLValue());
  10588. return IsGlobalLValue(Val.getLValueBase());
  10589. }
  10590. /// isIntegerConstantExpr - this recursive routine will test if an expression is
  10591. /// an integer constant expression.
  10592. /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
  10593. /// comma, etc
  10594. // CheckICE - This function does the fundamental ICE checking: the returned
  10595. // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
  10596. // and a (possibly null) SourceLocation indicating the location of the problem.
  10597. //
  10598. // Note that to reduce code duplication, this helper does no evaluation
  10599. // itself; the caller checks whether the expression is evaluatable, and
  10600. // in the rare cases where CheckICE actually cares about the evaluated
  10601. // value, it calls into Evaluate.
  10602. namespace {
  10603. enum ICEKind {
  10604. /// This expression is an ICE.
  10605. IK_ICE,
  10606. /// This expression is not an ICE, but if it isn't evaluated, it's
  10607. /// a legal subexpression for an ICE. This return value is used to handle
  10608. /// the comma operator in C99 mode, and non-constant subexpressions.
  10609. IK_ICEIfUnevaluated,
  10610. /// This expression is not an ICE, and is not a legal subexpression for one.
  10611. IK_NotICE
  10612. };
  10613. struct ICEDiag {
  10614. ICEKind Kind;
  10615. SourceLocation Loc;
  10616. ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
  10617. };
  10618. }
  10619. static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
  10620. static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
  10621. static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
  10622. Expr::EvalResult EVResult;
  10623. Expr::EvalStatus Status;
  10624. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  10625. Info.InConstantContext = true;
  10626. if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
  10627. !EVResult.Val.isInt())
  10628. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10629. return NoDiag();
  10630. }
  10631. static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
  10632. assert(!E->isValueDependent() && "Should not see value dependent exprs!");
  10633. if (!E->getType()->isIntegralOrEnumerationType())
  10634. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10635. switch (E->getStmtClass()) {
  10636. #define ABSTRACT_STMT(Node)
  10637. #define STMT(Node, Base) case Expr::Node##Class:
  10638. #define EXPR(Node, Base)
  10639. #include "clang/AST/StmtNodes.inc"
  10640. case Expr::PredefinedExprClass:
  10641. case Expr::FloatingLiteralClass:
  10642. case Expr::ImaginaryLiteralClass:
  10643. case Expr::StringLiteralClass:
  10644. case Expr::ArraySubscriptExprClass:
  10645. case Expr::OMPArraySectionExprClass:
  10646. case Expr::MemberExprClass:
  10647. case Expr::CompoundAssignOperatorClass:
  10648. case Expr::CompoundLiteralExprClass:
  10649. case Expr::ExtVectorElementExprClass:
  10650. case Expr::DesignatedInitExprClass:
  10651. case Expr::ArrayInitLoopExprClass:
  10652. case Expr::ArrayInitIndexExprClass:
  10653. case Expr::NoInitExprClass:
  10654. case Expr::DesignatedInitUpdateExprClass:
  10655. case Expr::ImplicitValueInitExprClass:
  10656. case Expr::ParenListExprClass:
  10657. case Expr::VAArgExprClass:
  10658. case Expr::AddrLabelExprClass:
  10659. case Expr::StmtExprClass:
  10660. case Expr::CXXMemberCallExprClass:
  10661. case Expr::CUDAKernelCallExprClass:
  10662. case Expr::CXXDynamicCastExprClass:
  10663. case Expr::CXXTypeidExprClass:
  10664. case Expr::CXXUuidofExprClass:
  10665. case Expr::MSPropertyRefExprClass:
  10666. case Expr::MSPropertySubscriptExprClass:
  10667. case Expr::CXXNullPtrLiteralExprClass:
  10668. case Expr::UserDefinedLiteralClass:
  10669. case Expr::CXXThisExprClass:
  10670. case Expr::CXXThrowExprClass:
  10671. case Expr::CXXNewExprClass:
  10672. case Expr::CXXDeleteExprClass:
  10673. case Expr::CXXPseudoDestructorExprClass:
  10674. case Expr::UnresolvedLookupExprClass:
  10675. case Expr::TypoExprClass:
  10676. case Expr::DependentScopeDeclRefExprClass:
  10677. case Expr::CXXConstructExprClass:
  10678. case Expr::CXXInheritedCtorInitExprClass:
  10679. case Expr::CXXStdInitializerListExprClass:
  10680. case Expr::CXXBindTemporaryExprClass:
  10681. case Expr::ExprWithCleanupsClass:
  10682. case Expr::CXXTemporaryObjectExprClass:
  10683. case Expr::CXXUnresolvedConstructExprClass:
  10684. case Expr::CXXDependentScopeMemberExprClass:
  10685. case Expr::UnresolvedMemberExprClass:
  10686. case Expr::ObjCStringLiteralClass:
  10687. case Expr::ObjCBoxedExprClass:
  10688. case Expr::ObjCArrayLiteralClass:
  10689. case Expr::ObjCDictionaryLiteralClass:
  10690. case Expr::ObjCEncodeExprClass:
  10691. case Expr::ObjCMessageExprClass:
  10692. case Expr::ObjCSelectorExprClass:
  10693. case Expr::ObjCProtocolExprClass:
  10694. case Expr::ObjCIvarRefExprClass:
  10695. case Expr::ObjCPropertyRefExprClass:
  10696. case Expr::ObjCSubscriptRefExprClass:
  10697. case Expr::ObjCIsaExprClass:
  10698. case Expr::ObjCAvailabilityCheckExprClass:
  10699. case Expr::ShuffleVectorExprClass:
  10700. case Expr::ConvertVectorExprClass:
  10701. case Expr::BlockExprClass:
  10702. case Expr::NoStmtClass:
  10703. case Expr::OpaqueValueExprClass:
  10704. case Expr::PackExpansionExprClass:
  10705. case Expr::SubstNonTypeTemplateParmPackExprClass:
  10706. case Expr::FunctionParmPackExprClass:
  10707. case Expr::AsTypeExprClass:
  10708. case Expr::ObjCIndirectCopyRestoreExprClass:
  10709. case Expr::MaterializeTemporaryExprClass:
  10710. case Expr::PseudoObjectExprClass:
  10711. case Expr::AtomicExprClass:
  10712. case Expr::LambdaExprClass:
  10713. case Expr::CXXFoldExprClass:
  10714. case Expr::CoawaitExprClass:
  10715. case Expr::DependentCoawaitExprClass:
  10716. case Expr::CoyieldExprClass:
  10717. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10718. case Expr::InitListExprClass: {
  10719. // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
  10720. // form "T x = { a };" is equivalent to "T x = a;".
  10721. // Unless we're initializing a reference, T is a scalar as it is known to be
  10722. // of integral or enumeration type.
  10723. if (E->isRValue())
  10724. if (cast<InitListExpr>(E)->getNumInits() == 1)
  10725. return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
  10726. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10727. }
  10728. case Expr::SizeOfPackExprClass:
  10729. case Expr::GNUNullExprClass:
  10730. case Expr::SourceLocExprClass:
  10731. return NoDiag();
  10732. case Expr::SubstNonTypeTemplateParmExprClass:
  10733. return
  10734. CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
  10735. case Expr::ConstantExprClass:
  10736. return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
  10737. case Expr::ParenExprClass:
  10738. return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
  10739. case Expr::GenericSelectionExprClass:
  10740. return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
  10741. case Expr::IntegerLiteralClass:
  10742. case Expr::FixedPointLiteralClass:
  10743. case Expr::CharacterLiteralClass:
  10744. case Expr::ObjCBoolLiteralExprClass:
  10745. case Expr::CXXBoolLiteralExprClass:
  10746. case Expr::CXXScalarValueInitExprClass:
  10747. case Expr::TypeTraitExprClass:
  10748. case Expr::ArrayTypeTraitExprClass:
  10749. case Expr::ExpressionTraitExprClass:
  10750. case Expr::CXXNoexceptExprClass:
  10751. return NoDiag();
  10752. case Expr::CallExprClass:
  10753. case Expr::CXXOperatorCallExprClass: {
  10754. // C99 6.6/3 allows function calls within unevaluated subexpressions of
  10755. // constant expressions, but they can never be ICEs because an ICE cannot
  10756. // contain an operand of (pointer to) function type.
  10757. const CallExpr *CE = cast<CallExpr>(E);
  10758. if (CE->getBuiltinCallee())
  10759. return CheckEvalInICE(E, Ctx);
  10760. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10761. }
  10762. case Expr::DeclRefExprClass: {
  10763. if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
  10764. return NoDiag();
  10765. const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
  10766. if (Ctx.getLangOpts().CPlusPlus &&
  10767. D && IsConstNonVolatile(D->getType())) {
  10768. // Parameter variables are never constants. Without this check,
  10769. // getAnyInitializer() can find a default argument, which leads
  10770. // to chaos.
  10771. if (isa<ParmVarDecl>(D))
  10772. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  10773. // C++ 7.1.5.1p2
  10774. // A variable of non-volatile const-qualified integral or enumeration
  10775. // type initialized by an ICE can be used in ICEs.
  10776. if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
  10777. if (!Dcl->getType()->isIntegralOrEnumerationType())
  10778. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  10779. const VarDecl *VD;
  10780. // Look for a declaration of this variable that has an initializer, and
  10781. // check whether it is an ICE.
  10782. if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
  10783. return NoDiag();
  10784. else
  10785. return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
  10786. }
  10787. }
  10788. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10789. }
  10790. case Expr::UnaryOperatorClass: {
  10791. const UnaryOperator *Exp = cast<UnaryOperator>(E);
  10792. switch (Exp->getOpcode()) {
  10793. case UO_PostInc:
  10794. case UO_PostDec:
  10795. case UO_PreInc:
  10796. case UO_PreDec:
  10797. case UO_AddrOf:
  10798. case UO_Deref:
  10799. case UO_Coawait:
  10800. // C99 6.6/3 allows increment and decrement within unevaluated
  10801. // subexpressions of constant expressions, but they can never be ICEs
  10802. // because an ICE cannot contain an lvalue operand.
  10803. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10804. case UO_Extension:
  10805. case UO_LNot:
  10806. case UO_Plus:
  10807. case UO_Minus:
  10808. case UO_Not:
  10809. case UO_Real:
  10810. case UO_Imag:
  10811. return CheckICE(Exp->getSubExpr(), Ctx);
  10812. }
  10813. llvm_unreachable("invalid unary operator class");
  10814. }
  10815. case Expr::OffsetOfExprClass: {
  10816. // Note that per C99, offsetof must be an ICE. And AFAIK, using
  10817. // EvaluateAsRValue matches the proposed gcc behavior for cases like
  10818. // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
  10819. // compliance: we should warn earlier for offsetof expressions with
  10820. // array subscripts that aren't ICEs, and if the array subscripts
  10821. // are ICEs, the value of the offsetof must be an integer constant.
  10822. return CheckEvalInICE(E, Ctx);
  10823. }
  10824. case Expr::UnaryExprOrTypeTraitExprClass: {
  10825. const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
  10826. if ((Exp->getKind() == UETT_SizeOf) &&
  10827. Exp->getTypeOfArgument()->isVariableArrayType())
  10828. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10829. return NoDiag();
  10830. }
  10831. case Expr::BinaryOperatorClass: {
  10832. const BinaryOperator *Exp = cast<BinaryOperator>(E);
  10833. switch (Exp->getOpcode()) {
  10834. case BO_PtrMemD:
  10835. case BO_PtrMemI:
  10836. case BO_Assign:
  10837. case BO_MulAssign:
  10838. case BO_DivAssign:
  10839. case BO_RemAssign:
  10840. case BO_AddAssign:
  10841. case BO_SubAssign:
  10842. case BO_ShlAssign:
  10843. case BO_ShrAssign:
  10844. case BO_AndAssign:
  10845. case BO_XorAssign:
  10846. case BO_OrAssign:
  10847. // C99 6.6/3 allows assignments within unevaluated subexpressions of
  10848. // constant expressions, but they can never be ICEs because an ICE cannot
  10849. // contain an lvalue operand.
  10850. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10851. case BO_Mul:
  10852. case BO_Div:
  10853. case BO_Rem:
  10854. case BO_Add:
  10855. case BO_Sub:
  10856. case BO_Shl:
  10857. case BO_Shr:
  10858. case BO_LT:
  10859. case BO_GT:
  10860. case BO_LE:
  10861. case BO_GE:
  10862. case BO_EQ:
  10863. case BO_NE:
  10864. case BO_And:
  10865. case BO_Xor:
  10866. case BO_Or:
  10867. case BO_Comma:
  10868. case BO_Cmp: {
  10869. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  10870. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  10871. if (Exp->getOpcode() == BO_Div ||
  10872. Exp->getOpcode() == BO_Rem) {
  10873. // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
  10874. // we don't evaluate one.
  10875. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
  10876. llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
  10877. if (REval == 0)
  10878. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  10879. if (REval.isSigned() && REval.isAllOnesValue()) {
  10880. llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
  10881. if (LEval.isMinSignedValue())
  10882. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  10883. }
  10884. }
  10885. }
  10886. if (Exp->getOpcode() == BO_Comma) {
  10887. if (Ctx.getLangOpts().C99) {
  10888. // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
  10889. // if it isn't evaluated.
  10890. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
  10891. return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
  10892. } else {
  10893. // In both C89 and C++, commas in ICEs are illegal.
  10894. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10895. }
  10896. }
  10897. return Worst(LHSResult, RHSResult);
  10898. }
  10899. case BO_LAnd:
  10900. case BO_LOr: {
  10901. ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
  10902. ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
  10903. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
  10904. // Rare case where the RHS has a comma "side-effect"; we need
  10905. // to actually check the condition to see whether the side
  10906. // with the comma is evaluated.
  10907. if ((Exp->getOpcode() == BO_LAnd) !=
  10908. (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
  10909. return RHSResult;
  10910. return NoDiag();
  10911. }
  10912. return Worst(LHSResult, RHSResult);
  10913. }
  10914. }
  10915. llvm_unreachable("invalid binary operator kind");
  10916. }
  10917. case Expr::ImplicitCastExprClass:
  10918. case Expr::CStyleCastExprClass:
  10919. case Expr::CXXFunctionalCastExprClass:
  10920. case Expr::CXXStaticCastExprClass:
  10921. case Expr::CXXReinterpretCastExprClass:
  10922. case Expr::CXXConstCastExprClass:
  10923. case Expr::ObjCBridgedCastExprClass: {
  10924. const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
  10925. if (isa<ExplicitCastExpr>(E)) {
  10926. if (const FloatingLiteral *FL
  10927. = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
  10928. unsigned DestWidth = Ctx.getIntWidth(E->getType());
  10929. bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
  10930. APSInt IgnoredVal(DestWidth, !DestSigned);
  10931. bool Ignored;
  10932. // If the value does not fit in the destination type, the behavior is
  10933. // undefined, so we are not required to treat it as a constant
  10934. // expression.
  10935. if (FL->getValue().convertToInteger(IgnoredVal,
  10936. llvm::APFloat::rmTowardZero,
  10937. &Ignored) & APFloat::opInvalidOp)
  10938. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10939. return NoDiag();
  10940. }
  10941. }
  10942. switch (cast<CastExpr>(E)->getCastKind()) {
  10943. case CK_LValueToRValue:
  10944. case CK_AtomicToNonAtomic:
  10945. case CK_NonAtomicToAtomic:
  10946. case CK_NoOp:
  10947. case CK_IntegralToBoolean:
  10948. case CK_IntegralCast:
  10949. return CheckICE(SubExpr, Ctx);
  10950. default:
  10951. return ICEDiag(IK_NotICE, E->getBeginLoc());
  10952. }
  10953. }
  10954. case Expr::BinaryConditionalOperatorClass: {
  10955. const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
  10956. ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
  10957. if (CommonResult.Kind == IK_NotICE) return CommonResult;
  10958. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  10959. if (FalseResult.Kind == IK_NotICE) return FalseResult;
  10960. if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
  10961. if (FalseResult.Kind == IK_ICEIfUnevaluated &&
  10962. Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
  10963. return FalseResult;
  10964. }
  10965. case Expr::ConditionalOperatorClass: {
  10966. const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
  10967. // If the condition (ignoring parens) is a __builtin_constant_p call,
  10968. // then only the true side is actually considered in an integer constant
  10969. // expression, and it is fully evaluated. This is an important GNU
  10970. // extension. See GCC PR38377 for discussion.
  10971. if (const CallExpr *CallCE
  10972. = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
  10973. if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
  10974. return CheckEvalInICE(E, Ctx);
  10975. ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
  10976. if (CondResult.Kind == IK_NotICE)
  10977. return CondResult;
  10978. ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
  10979. ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
  10980. if (TrueResult.Kind == IK_NotICE)
  10981. return TrueResult;
  10982. if (FalseResult.Kind == IK_NotICE)
  10983. return FalseResult;
  10984. if (CondResult.Kind == IK_ICEIfUnevaluated)
  10985. return CondResult;
  10986. if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
  10987. return NoDiag();
  10988. // Rare case where the diagnostics depend on which side is evaluated
  10989. // Note that if we get here, CondResult is 0, and at least one of
  10990. // TrueResult and FalseResult is non-zero.
  10991. if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
  10992. return FalseResult;
  10993. return TrueResult;
  10994. }
  10995. case Expr::CXXDefaultArgExprClass:
  10996. return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
  10997. case Expr::CXXDefaultInitExprClass:
  10998. return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
  10999. case Expr::ChooseExprClass: {
  11000. return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
  11001. }
  11002. }
  11003. llvm_unreachable("Invalid StmtClass!");
  11004. }
  11005. /// Evaluate an expression as a C++11 integral constant expression.
  11006. static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
  11007. const Expr *E,
  11008. llvm::APSInt *Value,
  11009. SourceLocation *Loc) {
  11010. if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  11011. if (Loc) *Loc = E->getExprLoc();
  11012. return false;
  11013. }
  11014. APValue Result;
  11015. if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
  11016. return false;
  11017. if (!Result.isInt()) {
  11018. if (Loc) *Loc = E->getExprLoc();
  11019. return false;
  11020. }
  11021. if (Value) *Value = Result.getInt();
  11022. return true;
  11023. }
  11024. bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
  11025. SourceLocation *Loc) const {
  11026. assert(!isValueDependent() &&
  11027. "Expression evaluator can't be called on a dependent expression.");
  11028. if (Ctx.getLangOpts().CPlusPlus11)
  11029. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
  11030. ICEDiag D = CheckICE(this, Ctx);
  11031. if (D.Kind != IK_ICE) {
  11032. if (Loc) *Loc = D.Loc;
  11033. return false;
  11034. }
  11035. return true;
  11036. }
  11037. bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
  11038. SourceLocation *Loc, bool isEvaluated) const {
  11039. assert(!isValueDependent() &&
  11040. "Expression evaluator can't be called on a dependent expression.");
  11041. if (Ctx.getLangOpts().CPlusPlus11)
  11042. return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
  11043. if (!isIntegerConstantExpr(Ctx, Loc))
  11044. return false;
  11045. // The only possible side-effects here are due to UB discovered in the
  11046. // evaluation (for instance, INT_MAX + 1). In such a case, we are still
  11047. // required to treat the expression as an ICE, so we produce the folded
  11048. // value.
  11049. EvalResult ExprResult;
  11050. Expr::EvalStatus Status;
  11051. EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
  11052. Info.InConstantContext = true;
  11053. if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
  11054. llvm_unreachable("ICE cannot be evaluated!");
  11055. Value = ExprResult.Val.getInt();
  11056. return true;
  11057. }
  11058. bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
  11059. assert(!isValueDependent() &&
  11060. "Expression evaluator can't be called on a dependent expression.");
  11061. return CheckICE(this, Ctx).Kind == IK_ICE;
  11062. }
  11063. bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
  11064. SourceLocation *Loc) const {
  11065. assert(!isValueDependent() &&
  11066. "Expression evaluator can't be called on a dependent expression.");
  11067. // We support this checking in C++98 mode in order to diagnose compatibility
  11068. // issues.
  11069. assert(Ctx.getLangOpts().CPlusPlus);
  11070. // Build evaluation settings.
  11071. Expr::EvalStatus Status;
  11072. SmallVector<PartialDiagnosticAt, 8> Diags;
  11073. Status.Diag = &Diags;
  11074. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
  11075. APValue Scratch;
  11076. bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
  11077. if (!Diags.empty()) {
  11078. IsConstExpr = false;
  11079. if (Loc) *Loc = Diags[0].first;
  11080. } else if (!IsConstExpr) {
  11081. // FIXME: This shouldn't happen.
  11082. if (Loc) *Loc = getExprLoc();
  11083. }
  11084. return IsConstExpr;
  11085. }
  11086. bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
  11087. const FunctionDecl *Callee,
  11088. ArrayRef<const Expr*> Args,
  11089. const Expr *This) const {
  11090. assert(!isValueDependent() &&
  11091. "Expression evaluator can't be called on a dependent expression.");
  11092. Expr::EvalStatus Status;
  11093. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
  11094. Info.InConstantContext = true;
  11095. LValue ThisVal;
  11096. const LValue *ThisPtr = nullptr;
  11097. if (This) {
  11098. #ifndef NDEBUG
  11099. auto *MD = dyn_cast<CXXMethodDecl>(Callee);
  11100. assert(MD && "Don't provide `this` for non-methods.");
  11101. assert(!MD->isStatic() && "Don't provide `this` for static methods.");
  11102. #endif
  11103. if (EvaluateObjectArgument(Info, This, ThisVal))
  11104. ThisPtr = &ThisVal;
  11105. if (Info.EvalStatus.HasSideEffects)
  11106. return false;
  11107. }
  11108. ArgVector ArgValues(Args.size());
  11109. for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
  11110. I != E; ++I) {
  11111. if ((*I)->isValueDependent() ||
  11112. !Evaluate(ArgValues[I - Args.begin()], Info, *I))
  11113. // If evaluation fails, throw away the argument entirely.
  11114. ArgValues[I - Args.begin()] = APValue();
  11115. if (Info.EvalStatus.HasSideEffects)
  11116. return false;
  11117. }
  11118. // Build fake call to Callee.
  11119. CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
  11120. ArgValues.data());
  11121. return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
  11122. }
  11123. bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
  11124. SmallVectorImpl<
  11125. PartialDiagnosticAt> &Diags) {
  11126. // FIXME: It would be useful to check constexpr function templates, but at the
  11127. // moment the constant expression evaluator cannot cope with the non-rigorous
  11128. // ASTs which we build for dependent expressions.
  11129. if (FD->isDependentContext())
  11130. return true;
  11131. Expr::EvalStatus Status;
  11132. Status.Diag = &Diags;
  11133. EvalInfo Info(FD->getASTContext(), Status,
  11134. EvalInfo::EM_PotentialConstantExpression);
  11135. Info.InConstantContext = true;
  11136. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  11137. const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
  11138. // Fabricate an arbitrary expression on the stack and pretend that it
  11139. // is a temporary being used as the 'this' pointer.
  11140. LValue This;
  11141. ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
  11142. This.set({&VIE, Info.CurrentCall->Index});
  11143. ArrayRef<const Expr*> Args;
  11144. APValue Scratch;
  11145. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  11146. // Evaluate the call as a constant initializer, to allow the construction
  11147. // of objects of non-literal types.
  11148. Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
  11149. HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
  11150. } else {
  11151. SourceLocation Loc = FD->getLocation();
  11152. HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
  11153. Args, FD->getBody(), Info, Scratch, nullptr);
  11154. }
  11155. return Diags.empty();
  11156. }
  11157. bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
  11158. const FunctionDecl *FD,
  11159. SmallVectorImpl<
  11160. PartialDiagnosticAt> &Diags) {
  11161. assert(!E->isValueDependent() &&
  11162. "Expression evaluator can't be called on a dependent expression.");
  11163. Expr::EvalStatus Status;
  11164. Status.Diag = &Diags;
  11165. EvalInfo Info(FD->getASTContext(), Status,
  11166. EvalInfo::EM_PotentialConstantExpressionUnevaluated);
  11167. Info.InConstantContext = true;
  11168. // Fabricate a call stack frame to give the arguments a plausible cover story.
  11169. ArrayRef<const Expr*> Args;
  11170. ArgVector ArgValues(0);
  11171. bool Success = EvaluateArgs(Args, ArgValues, Info);
  11172. (void)Success;
  11173. assert(Success &&
  11174. "Failed to set up arguments for potential constant evaluation");
  11175. CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
  11176. APValue ResultScratch;
  11177. Evaluate(ResultScratch, Info, E);
  11178. return Diags.empty();
  11179. }
  11180. bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
  11181. unsigned Type) const {
  11182. if (!getType()->isPointerType())
  11183. return false;
  11184. Expr::EvalStatus Status;
  11185. EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
  11186. return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
  11187. }